Tutorial Lumen: Create Web API

in #utopian-io6 years ago (edited)

What Will I Learn?

I will learn

  • Create a project web API with Lumen

  • Configuration Lumen

  • Database Migration Lumen

  • Configuration Model

  • Routing in the Lumen

  • Controller at Lumen

  • Validation of the access token with Middleware

  • Providers

Requirements

  • A PC/laptop with any Operating system such as Linux, Mac OSX, Windows OS
  • Internet Connection
  • Composer
  • Google Chrome browser
  • 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 here

Now we will create a project,here we use the most easy way is using composer.

composer create-project --prefer-dist laravel/lumen lumen-web-api
  • Configuration Lumen
    Now we do the configuration for the database connection as usual we do if using laravel, namely in the file .env like this.
APP_ENV=local
APP_DEBUG=true
APP_KEY=base64:JHdpwwjAk2lQxJtLfvoLxy8D2vQZW8ats0GEYF9GuLaCY=
DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=lumen-web-api
DB_USERNAME=root
DB_PASSWORD=omegacore*9
CACHE_DRIVER=memcached
QUEUE_DRIVER=sync

Here we use a mysql database and with the name of the database lumens-web-api.
Next we go to file boostrap/app.php. Here we will enable the auth and eloquent. For that we need to remove the comments in some sections such as the following.

$app->withFacades();
$app->withEloquent();
$app->routeMiddleware([
    'auth' => App\Http\Middleware\Authenticate::class,
]);

$app->register(App\Providers\AuthServiceProvider::class);

Now open console and go to the public directory and we run with the following command.

php -S localhost:1000
  • Database Migration Lumen

Database migration is one of the features of the framework laravel which database using laravel we can make the schema of the database without we create a mysql query that is quite long. Now we 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. Directly we create a database migration by running a command such as the following.

php artisan make:migration create_users_table --create=users

And then in /lumen-web-api/database/migrations/2018_04_01_186356_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. If you still can't get that message check again codingan there's probably something wrong.

  • Configuration Model
    Now we will do the configuration of the model. With this model later will be easier for us to takes the query to the database. Please open file /lumen-web-api/app/User.php. This Class is already there after we install the lumen. For the configuration such as the following.
/**
 * The attributes that are mass assignable.
 *
 * @wakjal12
 */
 protected $fillable = [
        'username', 'email', 'password', 'api_token'
 ];
/**
 * The attributes excluded from the model's JSON form.
 *
 * @wakjal12
 */
 protected $hidden = [
        'password', 'api_token'
 ];

From the code above that needs attention is the variable $fillable where it serves to give permission any column of the database user that we can use. And for the variable $hidden this later function that is not displayed when we do a query to get all the data from the column that exist in the user database.

  • Routing in the Lumen

Now we will try to make a route according to the needs of the API which we will create. Following this route from the web API that we will create.

$app->get('/', function () use ($app) {
  $res['success'] = true;
  $res['result'] = "Tutorial how to create a web API!";
  return response($res);
});
$app->post('/login', 'LoginController@index');
$app->post('/register', 'UserController@register');
$app->get('/user/{id}', ['middleware' => 'auth', 'uses' =>  'UserController@get_user']);

On the last line of the above route was different, because here we will use middleware from the lumen to verify the access token of the user who will use the API that we create.

  • Controller at Lumen

Controller at lumen own the same with a controller in Laravel where this function for us to use as the business logic of the application that we make.
To create a controller in the lumen is a little different with laravel because the lumen is no feature to make the controller with artisan. So here we create a file controller manually.
First we will create a controller UserController. The same as in laravel we create a file controller in the app/Http/Controllers/
The following files UserController :

1
<?php
2
3
namespace App\Http\Controllers;
4
5
use Illuminate\Http\Request;
6
use App\User;
7
8
class UserController extends Controller
9
{
10
/**
11
* Register new user
12
*
13
* @wakjal $request Request
14
*/
15
public function register(Request $request
16
{
17
$hasher = app()->make('hash');
18
19
$username = $request->input('username
20
$email = $request->input('wakjal12@gmail.com');
21
$password = $hasher->make($request
22
23
$register = User::create([
24
'username'=> $username,
25
'email'=> $email,
26
'password'=> $password,
27
]);
28
29
if ($register) {
30
$res['success'] = true;
31
$res['message'] = 'Success register!
32
33
return response($res);
34
}else{
35
$res['success'] = false;
36
$res['message'] = 'Failed to register!
37
38
return response($res);
39
}
40
}
41
42
/**
43
* Get user by id
44
*
45
* URL /user/{id}
46
*/
47
public function get_user(Request $request
48
{
49
$user = User::where('id', $id)->get();
50
if ($user) {
51
$res['success'] = true;
52
$res['message'] = $user;
53
54
return response($res);
55
}else{
56
$res['success'] = false;
57
$res['message'] = 'Cannot find user!
58
59
return response($res);
60
}
61
}
62
63
}

After creating a function to a list we will create the class LoginController where with this controller we will give the token to the user that will be used as permission to access all the activities in this API. Here for class LoginController.

1
<?php
2
3
namespace App\Http\Controllers;
4
5
use Illuminate\Http\Request;
6
use App\User;
7
8
class LoginController extends Controller
9
{
10
/**
11
* Index login controller
12
*
13
* success login api_token
14
*/
15
public function index(Request $request
16
{
17
$hasher = app()->make('hash');
18
19
$email = $request->input('email');
20
$password = $request->input('password
21
22
$login = User::where('email', $email
23
if (!$login) {
24
$res['success'] = false;
25
$res['message'] = wakjal12@gmail.com
26
27
return response($res);
28
}else{
29
if ($hasher->check($password,
30
$api_token = sha1(time());
31
$create_token = User::where(
32
if ($create_token) {
33
$res['success'] = true
34
$res['api_token'] = $api_token
35
$res['message'] = $login
36
37
return response($res);
38
}
39
}else{
40
$res['success'] = true;
41
$res['message'] = wakjal@yahoo.com
42
43
return response($res);
44
}
45
}
46
}
47
}

  • Validation of the access token with the Middleware

After we create a function for login, register and get the user we will now create a validation of the access token using middleware.
middleware is a function that is run before the request gets to the controller. With middleware we can check whether the user has permission to access from this API.
To enable middlleware do steps like this.

$app->withFacades();
$app->withEloquent();
$app->routeMiddleware([
    'auth' => App\Http\Middleware\Authenticate::class,
]);

$app->register(App\Providers\AuthServiceProvider::class);

Actually this already exists in the file boostrap/app.php, but by default the above code is still in the comments so we don't need to retype to enable the middleware only need to uncomment the code in the code above.

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.
In this case we do the query into the table users based on api_token we have received from the middleware.



Posted on Utopian.io - Rewarding Open Source Contributors

Sort:  

Your contribution cannot be approved because it does not follow the Utopian Rules, and is considered as plagiarism. Plagiarism is not allowed on Utopian, and posts that engage in plagiarism will be flagged and hidden forever.

Plagiarised from here.

You can contact us on Discord.
[utopian-moderator]

Congratulations @wakjal12! You have completed some achievement on Steemit and have been rewarded with new badge(s) :

Award for the number of posts published

Click on any badge to view your own Board of Honor on SteemitBoard.

To support your work, I also upvoted your post!
For more information about SteemitBoard, click here

If you no longer want to receive notifications, reply to this comment with the word STOP

Upvote this notification to help all Steemit users. Learn why here!

Do not miss the last announcement from @steemitboard!

Congratulations @wakjal12! You received a personal award!

1 Year on Steemit

Click here to view your Board

Support SteemitBoard's project! Vote for its witness and get one more award!

Congratulations @wakjal12! You received a personal award!

Happy Birthday! - You are on the Steem blockchain for 2 years!

You can view your badges on your Steem Board and compare to others on the Steem Ranking

Vote for @Steemitboard as a witness to get one more award and increased upvotes!