Community Post

Build a lightweight API with Lumen

Joseph Pascal NOMO SAMBOU

Hello this is my first post, i will show you how to build a fast API with Lumen, i hope it will help you. This article may provide you an easy way to fastly build a lightweight REST API for your project or just for learning.

Why Lumen?

Many PHP framework contains a lot of modules who wont be useful for just an API, so the app remain slow due to the autoload of file. So that now we have lightweight framework like Slim or Lumen by Laravel which contains some Laravel cool stuffs like artisan. Learning Lumen is very easy and may be very fun; with that one you can build very fast application.

Prerequisites

PHP 5.6+ Composer https://getcomposer.org MySQL

Install Lumen

The first step to start this tutorial is to install lumen on your machine to be able to use it. To do this one will use the following command :

composer global require "laravel/lumen-installer"

Make sure you refer Lumen in $path variable by adding the route ~/.composer/vendor/bin so you will be able to use lumen as a command.

Building our application

To start a new application we should create it with the lumen command just like that :

lumen new albums

Configuring our application

Now that we have create our application let create a database that will be use.

CREATE DATABASE album;

Now set the configuration

APP_ENV=local
APP_DEBUG=true
APP_KEY=
APP_TIMEZONE=UTC

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=album
DB_USERNAME=root
DB_PASSWORD=

CACHE_DRIVER=array
QUEUE_DRIVER=sync

Replace those parameters with your owns, but it should not be that different. Let's create the migration file who will generate our database table. Just execute this command line

php artisan make:migration Albums

Just open that file and add the table schema in the up() function who will be execute when we will perform the migration.

Schema::create('albums', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name');
    $table->string('style');
    $table->string('description');
    $table->date('published_on');
$table->timestamps();
});

And perform the migration with the command line

php artisan migrate

Create Model and Controller

Since Lumen does not allow the use of Artisan controller and model commands, you will need to create these yourself, if you're familiar with Laravel then this is done in the same way.

Navigate to app/ and create a new model called Albums.php, and add the following code into the model:

namespace App;

use Illuminate\Database\Eloquent\Model;

class Albums extends Model
{
    //
    protected $fillable = ['name','style','description','published_on'];
}

Lumen does not initially load Eloquent and Facades. In order to use these tools, you will need to uncomment the relevant lines the in bootstrap/app.php file. Since we are using Eloquent, uncomment the line $app->withEloquent(); in bootstrap/app.php file.

To create the controller, navigate to app\Http\Controllers, create a new controller with name AlbumsController.php with the following code:

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Albums;
class AlbumsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
        $albums = Albums::all();
        return response()->json($albums);
    }

    /**
     * Get the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
        $album = Albums::where('id', $id)->get();
        if(!empty($album)){
            return response()->json($album);
        }
        else{
            return response()->json(['status' => 'fail']);
        }
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
        $this->validate($request, [
        'name' => 'required',
        'description' => 'required',
        'style' => 'required',
        'published_on' => 'required'
         ]);

        $album = new Albums();
        $album->name = $request->name;
        $album->description = $request->description;
        $album->category = $request->category;
        $date = new \DateTime($request->published_on);
        $dd = $date->format('Y-m-d');
        $album->published_on = $dd; 
        $album->save();
        return response()->json(['status' => 'success']);

    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
        $this->validate($request, [
        'name' => 'required',
        'description' => 'required',
        'style' => 'required',
        'published_on' => 'required'
         ]);

        $album = Albums::find($id);
        $album->name = $request->name;
        $album->description = $request->description;
        $album->category = $request->category;
        $date = new \DateTime($request->published_on);
        $dd = $date->format('Y-m-d');
        $album->published_on = $dd; 
        $album->save();
        return response()->json(['status' => 'success']);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
        if(Albums::destroy($id)){
             return response()->json(['status' => 'success']);
        }
    }
}

As you can see above we have created four methods to handle CRUD operation for a single album (show, create, update and destroy) and one method, index(), to show all the added books. The structure of this controller closely resembles a Laravel controller.

Creating API Routes

In Lumen, the routes are created in routes/web.php file. Open the file and paste the following group routes in it.

$app->group(['prefix' => 'album/'], function ($app) {
    $app->get('/','AlbumsController@index'); //get all the albums   
    $app->post('/','AlbumsController@store'); //store single album
    $app->get('/{id}/', 'AlbumsController@show'); //get single album
    $app->put('/{id}/','AlbumsController@update'); //update single album
    $app->delete('/{id}/','AlbumsController@destroy'); //delete single album
});

The above block defines a group of routes so they are all prefixed with book/ on every route

Enjoy our routes

Open Postman and test all the routes. Note do not put / at the end of the route. Write it like that http://localhost:8000/book

Conclusion

That was my first experience in writing content. I hope that it will help, give me some feedback to help me improve.

Joseph Pascal NOMO SAMBOU

Passionate in software technologies. Web API Python, PHP, NodeJs(Lumen, Flask, Bottle, Slim, Express), Some client technologies like Angular and Android.