Creating A REST API With Lumen

in Lumen

In this article, we will investigate how you can easily create a simple REST API using Lumen. To illustrate this API, we'll create a Books table, and then perform CRUD operations on it using the Lumen REST API.

What Is Lumen?

Lumen is a micro framework that excels in the design and implementation of REST API. It is built upon Laravel and is the product of the core Laravel team.

Several reasons to use Lumen:

  • Lumen is blazing fast.
  • It can handle more requests per second then Laravel itself.
  • It uses nikic/FastRoute for routing instead of Symfony components.
  • You can use Artisan with Lumen.

Create A REST API With Lumen

Install Lumen

The first step of the REST API creation is the installation of Lumen.

Go to the project root directory and run the following command to create a new Lumen project with the name books.

composer create-project --prefer-dist laravel/lumen books

Create the Database and the Table

Once the installation finishes, create a new database with the name lumen. Add the database credentials and the name of the database in the .env file.

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

Now you can create a new migration by running the following Artisan command:

php artisan make:migration Books

The migration file will be created in database/migrations folder.

Open this file and add the table schema in it. Inside function up() add the following code:

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

Now, run the following command to migrate the table.

php artisan migrate

Create The Model And The Controller For Books

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/Http and create a new model called Books.php, and add the following code into the model:

namespace App;

use Illuminate\Database\Eloquent\Model;

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

Lumen does not initially load Eloquent and Facades. In order to use these tools, you’ll need to uncomment the relevant lines the in bootstrap/app.php file. Since we're 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 BooksController.php with the following code:

namespace App\Http\Controllers;

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

    /**
     * Get the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
        $book = Books::where('id', $id)->get();
        if(!empty($book['items'])){
            return response()->json($book);
        }
        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',
        'category' => 'required',
        'published_on' => 'required'
         ]);

        $book = new Books();
        $book->name = $request->name;
        $book->description = $request->description;
        $book->category = $request->category;
        $date = new \DateTime($request->published_on);
        $dd = $date->format('Y-m-d');
        $book->published_on = $dd; 
        $book->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',
        'category' => 'required',
        'published_on' => 'required'
         ]);

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

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

As you can see above we've created four methods to handle CRUD operation for a single book (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.

Create The 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' => 'book/'], function ($app) {
    $app->get('/','BooksController@index'); //get all the routes	
    $app->post('/','BooksController@store'); //store single route
    $app->get('/{id}/', 'BooksController@show'); //get single route
    $app->put('/{id}/','BooksController@update'); //update single route
    $app->delete('/{id}/','BooksController@destroy'); //delete single route
});

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

Testing The API

To test the API on localhost we're going to use the application, Postman. To test it on the localhost, run the following command in the folder to start a PHP server:

php -S localhost:8000 -t public

This will bind the Lumen public directory to localhost:8000.

Create A New Book

To create a new record for a book using the API, we need to send a post request to localhost:8000/book/ with the following parameters name, category, description, published_on.

We can test the validation by removing the published_on parameter.

Get All The Records

To get all the records, send a get request to localhost:8000/book/.

Get A Single Record

To get a single record, send a get request to localhost:8000/book/{id}.

Update A Record

To update a record, send a put request to localhost:8000/book/{id}.

Delete A Record

To delete a record, send a delete request to localhost:8000/book/{id}.

Conclusion

In this tutorial we've created a new API out of Lumen, added models and controllers to the API. We've also been able to test the API using Postman and make sure we're getting the correct return from each endpoint.

In a future tutorial, we're going to look at unit testing the API endpoints.

This was a guest post written by Ahmed Khan, he is the PHP Community Manager at Cloudway and writes about MySQL and PHP. An experienced professional in PHP related topics. Follow him on Twitter to keep up with his work and insights on PHP hosting.

Subscribe To Newsletter

Get weekly updates to your email