A Beginner’s Guide To The Developing RESTful APIs with Lumen Microservices
Lumen is an open-source PHP micro-framework created by Taylor Otwell as an alternative to Laravel to meet the demand of lightweight installations that are faster than existing PHP micro-frameworks such as Slim and Silex. With Lumen, you can build lightning-fast microservices and APIs that can support your Laravel applications.
Lumen Features and Architecture
Lumen utilizes the Illuminate components that power the Laravel framework. As such, Lumen is built to painlessly upgrade directly to Laravel when needed. These are some of the built-in features of Lumen:
- Routing is provided out of the box in Lumen. This includes basic routing, routing parameters, named routes, and route groups such as middleware.
- Authentication does not support session state. However, incoming requests are authenticated via stateless mechanisms such as tokens.
- Caching is implemented the same as in Laravel. Cache drivers such as Database, Memcached, and Redis are supported. For example, you can install the
illuminate/redis
package via Composer to use a Redis cache with Lumen. - Errors and Logging are implemented via the Monolog library, which provides support for various log handlers.
- Queuing services are similar to the ones offered by Laravel. A unified API is provided across a variety of different queue back-ends.
- Events provide a simple observer implementation that allows you to subscribe and listen for events in your application.
- Bootstrapping processes are located in a single file.
We will see lumen rest api authentication in this article. So you can learn a lot of things from this laravel lumen. You can create rest based microservices with lumen after finishing this article.
Lumen Key Requirements
To use Lumen, you need to have the following tools installed on your machine:
- PHP: Make sure
PHP >= 7.2
is installed on your machine. Furthermore, ensure that the following PHP extensions are installed.OpenSSL
,PDO
andMbstring
. - Composer: Navigate to the Composer website and install it on your machine. Composer is needed to install Lumen’s dependencies.
Building a Users API Rapidly With Lumen
This is what we need the API to do:
- Get all users.
- Get one user.
- Add a new user.
- Edit a user.
- Delete a user.
Let’s flesh out the possible endpoints for this API. Given some authors resource, we’ll have the following endpoints:
- Get all users —
GET /user/list
- Get one user —
GET /user/show/2
- Create a user —
POST /user/create
- Edit a user —
POST /user/update/23
- Delete a user —
DELETE /user/delete/23
What will be the user attributes? Let’s flesh it out like we did the endpoints.
- Author:
username
,email
,number
,about
, andgender.
Install Lumen
Run the following command in your terminal to create a new project with Lumen:
composer create-project laravel/lumen LumenApiCrud "6.*"
cd
into the newly created project.
cd LumenApiCrud/
Now, run php -S localhost:8000 -t public
to serve the project. Head over to your browser. You should see the index page like so:
Activate Eloquent and Facades
As I mentioned earlier, the entire bootstrap process is located in a single file.
Open up the bootstrap/app.php
and uncomment this line, // app->withEloquent
. Once uncommented, Lumen hooks the Eloquent ORM with your database using the connections configured in the .env
file.
Make sure you set the right details for your database in the .env file.
Next uncomment this line //$app->withFacades();
, which allows us to make use of Facades in our project.
.env
file and replace the default CACHE_DRIVER
and QUEUE_DRIVER
values file into array and sync into database with the following:
Setup Database, Models and Migrations
At the time of this writing, Lumen supports four database systems: MySQL, Postgres, SQLite, and SQL Server. We are making use of MySQL.
Run the command below in the terminal to create the users
table migration:
php artisan make:migration create_users_table
The new migration will be placed in your database/migrations
directory. Each migration file name contains a timestamp, which allows Lumen to determine the order of the migrations. Next, we'll modify the recently created migration to include the attributes we need for the users
table. Open up the migration file and modify it like so:
Now, go ahead and run the migration like so:
php artisan migrate
Installation Lumen Generator
To use some generators command in Lumen (just like you do in Laravel), you need to add this package:
composer require flipbox/lumen-generator
Now configure the lumen generator class in our application. Inside your bootstrap/app.php
file, add:
$app->register(Flipbox\LumenGenerator\LumenGeneratorServiceProvider::class);
Also uncomment the registry classes inside your bootstrap/app.php
Inside your bootstrap/app.php
Let’s create the User
model.
php artisan make:model User
Create an app/User.php
file and add the code into User class scope:
protected $table = 'users';
protected $fillable = [];
protected $guarded = ['id'];
Set up User Controller
Create a new file, UserController.php
php artisan make:controller UserController --resource
Lumen API Validation
When developing applications, never trust the user. Always validate incoming data. In Lumen, it’s very easy to validate your application’s incoming data.
In UserControllers
file load the model and validator.
php artuse App\User;
use Validator;
Now in index function we code for the get all user list:
// get all user from users table
$user = User::all();
return response()->json($user);
Now Make route for the index function
Now in create function we code for create the new user:
$validator = Validator::make($request->all(), [ //make validation
'username' => 'required|max:20',
'email' => 'required|email|unique:users,email',
'number' => 'required|max:11',
'about' => 'max:50',
'gender' => 'min:3'
]);if ($validator->fails()) { // if validation fails
return $validator->errors();
}// sit new entry
$user = new User;
$user->username = $request->username;
$user->email= $request->email;
$user->number= $request->number;
$user->about= $request->about;
$user->gender= $request->gender;$user->save();
return response()->json($user);
Now in show function we code for specific user details against the id:
public function show($id)
{
$user = User::find($id);
return response()->json($user);
}
Now in update function we code for specific user details update against the id:
public function update(Request $request, $id)
{
$user = User::find($id); //get user by id // update values
$user->username = $request->input('username');
$user->email = $request->input('email');
$user->number = $request->input('number');
$user->about = $request->input('about');
$user->gender = $request->input('gender');
$user->save();
return response()->json(['User Has been Updated!',$user]);
}
Now in destroy function we code for specific user remove from the db against the id:
public function destroy($id)
{
$user = User::find($id);
$user->delete();
return response()->json(['User has been removed!', $user]);
}
Set up the all Routes
Routing is fairly straight-forward. Open up routes/web.php
and modify it like so:
$router->group(['prefix'=>'user'], function() use($router){$router->get('/list', 'UserController@index'); //for list of users
$router->post('/create', 'UserController@create'); // new user create
$router->get('/show/{id}', 'UserController@show'); // show specific user
$router->post('/update/{id}', 'UserController@update'); // update specific user
$router->delete('/delete/{id}', 'UserController@destroy'); // delete specific user});
Finally, test the API routes with Postman.
User GET operation — http://localhost:8000/user/list
You should now see an array of objects, including the user you just created plus any others in the database.
User POST operation — http://localhost:8000/user/create.
Make sure you have selected POST
from the dropdown, and then you can fill the form data in by clicking on Body
and then selecting form-data
. Fill in a value for name
, email
, etc. to create a new author.
User GET operation — http://localhost:8000/user/show/1
The GET
operation allows us to view an existing user details. Notice the user’s id
in the URL.
User POST operation — http://localhost:8000/user/update/3
The POST
operation allows us to edit an existing user. Notice the user’s id
in the URL.
User DELETE operation — http://localhost:8000/user/delete/3
The DELETE
operation allows us to delete an existing user. Notice the user’s id
in the URL.
Conclusion
I recently developed an API with Lumen, since it’s a far lighter and faster framework than Laravel. Well done! You have learned how to build a rest API with the powerful PHP micro-framework Lumen. I’d bet on Lumen as the tool of choice for speed and ease of use.
You can check the git repository from here Rest api with lumen. Please, let me know if you have any questions in the comment section. 😊