Building A REST API With Laravel Microservices Lumen

Introducing Lumen from Laravel

Lumen is a new project from Laravel creator Taylor Otwell. It's a "micro-framework", meaning it's a smaller, faster, leaner version of a full web application framework. PHP has two other popular micro-frameworks, Slim and Silex.

Lumen has the same foundation as Laravel, and many of the same components. But Lumen is built for microservices, not so much for user-facing applications although it can be used for anything. 

Though this tutorial is about Lumen, a simple understanding of how Laravel works is all you need to follow along. You can check the git repository from here Rest api with lumen

We will see lumen rest api authentication in this tutorial. So you can learn a lot of things from this laravel lumen tutorial. You can create rest based microservices with lumen after finishing this tutorial.

RESTful APIs

First, we need to understand what exactly is considered a RESTful API. REST stands for REpresentational State Transfer and is an architectural style for network communication between applications, which relies on a stateless protocol (usually HTTP) for interaction.

HTTP Verbs Represent Actions

In RESTful APIs, we use the HTTP verbs as actions, and the endpoints are the resources acted upon. We’ll be using the HTTP verbs for their semantic meaning:

  • GETretrieve resources
  • POST: create resources
  • PUT: update resources
  • DELETEdelete resources

 

Installing Lumen

Lumen utilizes Composer to manage its dependencies. So, before using Lumen, make sure you have Composer installed on your machine.

Via Lumen Installer

First, download the Lumen installer using Composer:

composer global require "laravel/lumen-installer"

 

Make sure to place the ~/.composer/vendor/bin directory in your PATH so the lumen executable can be located by your system.Once installed, the lumen new command will create a fresh Lumen installation in the directory you specify.

For instance, lumen new blog will create a directory named blog containing a fresh Lumen installation with all of Lumen's dependencies already installed. This method of installation is much faster than installing via Composer:

lumen new blog

 

Via Composer Create-Project

You may also install Lumen by issuing the Composer create-project command in your terminal:

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

 

Serving Your Application

To serve your project locally, you may use the Laravel Homestead virtual machine, Laravel Valet, or the built-in PHP development server:

php -S localhost:8000 -t public

 

If you run this command and visit http://localhost:8080, you will be able to see the following page. So let' start laravel lumen rest api tutorial.

api-develoment-with-lumen-in-laravel-6

Step 1: Configuration

.env file and replace the default CACHE_DRIVER and QUEUE_DRIVER values with the following:

CACHE_DRIVER=array
QUEUE_DRIVER=database

 

Read also: Laravel 6 REST API with Passport Tutorial with Ecommerce Project

 

Step 2 : Database and Migrations

Let’s create our migration file. Run the following command:

php artisan make:migration create_products_table

 

This will create a new migration file for you in the database/migrations directory. Our product resource will have the following attributes  nameprice and description.

Add the following code to the newly created migration file.

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateProductsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->integer('price');
            $table->longText('description');            
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('products');
    }
}

 

Edit .env with your database configurations and then run the following command to execute the migration.

php artisan migrate

 

Step 3: Create product model

You might already be used to creating models and controllers via artisan commands in Laravel, but unfortunately Lumen doesn’t support those commands. To see a list of available artisan commands in Lumen, run:

php artisan

 

Navigate to the app directory and create a new model called Product.php and paste those following code.

App/Product.php

namespace App;
use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    protected $table = 'products';
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'price','description'
    ];

}

 

Unlike Laravel, Lumen does not initially load Eloquent and Facades. To be able to use them, we have to uncomment the following lines of code located in bootstrap/app.php

bootstrap/app.php

$app->withFacades();
$app->withEloquent();

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

 

Step 4: Setup controller

Let’s rename the ExampleController to ProductController. Navigate to the app\Http\Controller directory and paste those code to this ProductController.php file.

app/Http/Controllers/ProductController.php

namespace App\Http\Controllers;
use App\Product;
use Illuminate\Http\Request;

class ProductController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }
    
     public function index()
     {
     
       $products = Product::all();
       return response()->json($products);
     }

     public function create(Request $request)
     {
       $product = new Product;
       $product->name= $request->name;
       $product->price = $request->price;
       $product->description= $request->description;
       
       $product->save();
       return response()->json($product);
     }

     public function show($id)
     {
        $product = Product::find($id);
        return response()->json($product);
     }

     public function update(Request $request, $id)
     { 
        $product= Product::find($id);
        
        $product->name = $request->input('name');
        $product->price = $request->input('price');
        $product->description = $request->input('description');
        $product->save();
        return response()->json($product);
     }

     public function destroy($id)
     {
        $product = Product::find($id);
        $product->delete();
        return response()->json('product removed successfully');
     }
   
}

 

Step 5 : Setup routes

It’s time to finally add our routes. Open up the web.php file in the routes folder and add the following code:


$router->group(['prefix'=>'api/v1'], function() use($router){

    $router->get('/items', 'ProductController@index');
    $router->post('/items', 'ProductController@create');
    $router->get('/items/{id}', 'ProductController@show');
    $router->put('/items/{id}', 'ProductController@update');
    $router->delete('/items/{id}', 'ProductController@destroy');

});

 

We define group our routes and add the prefix api/v1 since it’s a common parameter shared by all our URIs

Now insert some dummy data to products table like below. Then we will be able to test our application.

lumen-laravel-rest-api-development-with-crud

Step 6 : Testing our API

We’ll be making use of Postman to test our API. You can read more on getting started with Postman here.

GET Request with all items preview:

building-api-with-laravel-using-lumen

 

GET Request with single items preview:

rest-api-development-with-laravel-and-lumen

 

POST Request for inserting new items preview:

laravel-post-request-example-lumen

 

PUT Request for updating items preview:

product-updated-lumen-laravel-restapi

 

DELETE Request to delete items preview:

delete-request-lumen-laravel-restapi

 

Read also : Laravel 6 REST API with JWT Authentication with CRUD

 

In this tutorial, we’ve learnt how to build a simple REST API with Lumen. Hope this tutorial will help you. You can check the git repository from here Rest api with lumen

 

#laravel #lumen #laravel-lumen #laravel-6 #rest-api #software-development