Tutorial how to create a web API with Lumen
- Repository
https://github.com/laravel/lumen
What Will I Learn?
- Create a project web API with Lumen
• Configuration Lumen
• Database Migration Lumen
• Validation token with the Middleware
• Providers
Requirements
• A PC/laptop with any Operating system such as Linux, Mac OSX, Windows OS
• PHP
• OpenSSL PHP Extension
• PDO PHP Extension
• Mbstring PHP Extension
Difficulty
• Intermediate
Tutorial Contents
• Create a project web API with Lumen
Lumen utilizes composer to manage its dependencies so before installing lumen, make sure you have composer already installed. You can download composer https://getcomposer.org/
• Configuration Lumen
Now after finished install, now I will do the configuration for the database connection like I do if using laravel, namely in the file .env like this.
APP_ENV=local
APP_DEBUG=true
APP_KEY=jwwZ4pdXVGKu3MT4842ofrX2YdPjv4wCLlbS
DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=web
DB_USERNAME=root
DB_PASSWORD=hFd21*
CACHE_DRIVER=memcached
QUEUE_DRIVER=sync
Next I go to file boostrap/app.php. Here I will enable the Facades and eloquent. For that we need to remove the comments in some parts, such as the following.
// $app->withFacades();
// $app->withEloquent();
Now open console and go to the public directory and run like the following command.
php -S localhost:1000
Open in a web browser and open the http://localhost:1000/ If it is already showing Lumen (5.3.0) (Laravel Components 5.3.*) then we've managed to do the installation of the lumen.
Database Migration Lumen
Database migration is one of the features of the framework laravel database using laravel we can create the database schema without we create a mysql query that is quite long. Now I will create the schema for the user. In the lumen there is also a php artisan who can create the class by using the console. Okay now I will make the migration database by running a command like the following.
php artisan make:migration create_users_table --create=users
And then in /web/database/migrations/2018_05_13_664529_create_users_table.php and create a schema like the following.
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('username');
$table->string('email')->unique();
$table->string('password');
$table->string('api_token');
$table->rememberToken();
$table->timestamps();
$table->softDeletes();
});
Schema is a standard that we use when creating a table user. Migration laravel already support many of the features in the create schema database.
If you are finished with the create schema now we do the migration by running the following command.
php artisan migrate
If successful then we will got the message Migration table created successfully.
Validation token with the Middleware
Now we will create the validation how do we know if this user get permissions to access the API that we create.
when the user request we will check if he sent the token which he had and if so whether token it exists in the database. Here every user can have access token each so later token will vary from each user.
For that we need to add the code below in the file app/Http/Middleware/Authenticate.php The following code.
1
public function handle($request, Closure $next, $guard = null)
2
{
3
if ($this->auth->guard($guard)->guest()) {
4
if ($request->has('api_token')) {
5
$token = $request->input('api_token');
6
$check_token = User::where('api_token', $token)->first();
7
if ($check_token == null) {
8
$res['success'] = false;
9
$res['message'] = 'Permission not allowed!';
10
11
return response($res);
12
}
13
}else{
14
$res['success'] = false;
15
$res['message'] = 'Login please!';
16
17
return response($res);
18
}
19
}
20
return $next($request);
21
}
Providers
This providers is a class that is executed after the user is successfully verified. So if the user has a login and access the API with a token that they have got, we can get information from the user who have the token, in this case the Provider has the role to get the data of the user based on this token.
app/Providers/AuthServiceProvider.php to get the user data based on the token has been verified.
$this->app['auth']->viaRequest('api', function ($request) {
if ($request->input('api_token')) {
return User::where('api_token',
$request->input('api_token'))->first();
}
});
The above code is the code which resides in the method boot () where the boot itself is the method used to get user data based on the token that has been verified by the middleware.
Thank you for your contribution.
The content of your post has portions taken from other sources of the web. This is considered plagiarism and is a serious offense.
https://medium.com/@ocittwo/membangun-web-api-dengan-lumen-5-3-part-1-d6a3522772a4
If you are interested in contributing into utopian and the tutorial category, you need to provide genuine effort and create your own useful tutorial.
In case you rely on some external source for some information, you need to cite your references, but with providing added value as well.
You have been banned for 15 days now. Continuous plagiarism attempts could lead to permanent ban from Utopian.
Need help? Write a ticket on https://support.utopian.io/.
Chat with us on Discord.
[utopian-moderator]