Today we are going to build a REST API using Lumen which is a very popular microservice. When we develop want to develop only an API, we wont need default dependenices and libraries of Laravel. Therefore we'll use use Lumen.

Prerequisites

  • Lumen
  • To Continue with this tutorial, you should have installed Lumen in your pc. If you are still not installed Lumen in your machine you can configure it from here.
  • Postman
  • To test our API endpoints, you need a API Testing application like Postman. You can download Postman from here.

    Setting up the Project

    First you need to create a new lumen project by running below command in your terminal
    1
    composer create-project --prefer-dist laravel/lumen rest-api

    Then navigate to your project directory by using below command in your terminal

    1
    cd rest-api

    Setting up Database

    To setup up Database for our project, open the application using your favourite text editor and and then navigate to .env file in it and then change below section acording to your Database settings:

    1
    2
    3
    4
    5
    6
    DB_CONNECTION=mysql
    DB_HOST=127.0.0.1
    DB_PORT=3306
    DB_DATABASE=lumen_api
    DB_USERNAME=root
    DB_PASSWORD=

    Configuration

    Now in your .env file change CACHE_DRIVER and QUEUE_DRIVER values with given values below:
    1
    2
    CACHE_DRIVER=array
    QUEUE_DRIVER=database

    To obtain an APP_KEYpaste below code in your web.php and run your application.

    1
    2
    3
    $router->get('/key', function() {
    return \Illuminate\Support\Str::random(32);
    });

    Then goto postman and call http://localhost:8000/key

    Create Migartion

    Now we nedd to create our migration file for our products table. To create migration file run below command:
    1
    php artisan make:migration create_products_table

    It will create new migration file in database/migrations directory, Then add below code to that migration file:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    <?php

    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->increments('id');
    $table->string('name');
    $table->integer('price');
    $table->longText('description');
    $table->timestamps();
    });
    }

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

    Then run php artisan migrate command to migrate our newly created product table migration.

    Create Product Model

    Now we need to create Model for our Product but by defualt Lumen not allow to create model using artisan command. So, go to your app directory and create new model called Product.php and paste below code in it.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    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'
    ];

    }

    Note:

    By default Lumen not load Eloquent and Facades.To use this we need to uncomment the following lines in bootstrap/app.php
    1
    2
    3
    4
    5
    6
    $app->withFacades();
    $app->withEloquent();

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

    Create Product Controller

    Navigate to your app/Http/Controllers and create a new controller named ProductController and then paste this code within it.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    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');
    }

    }

    Setup routes

    Open up the web.php file and then paste this code in it.
    1
    2
    3
    4
    5
    6
    7
    8
    $router->group(['prefix'=>'api/v1'], function() use($router){
    $router->get('/items', '[email protected]');
    $router->post('/items', '[email protected]');
    $router->get('/items/{id}', '[email protected]');
    $router->put('/items/{id}', '[email protected]');
    $router->delete('/items/{id}', '[email protected]');

    })

    Run application

    To serve your project locally, you may use the Laravel Homestead virtual machine, Laravel Valet, or the built-in PHP development server:
    1
    php -S localhost:8000 -t public

    Testing our API

    Method Route Description
    POST /api/v1/items Create an item
    GET /api/v1/items Get All item
    GET /api/vi/items/:id Get a single item
    PUT /api/v1/items/:id Update item
    DELETE /api/v1/items/:id Delete a item

    Conclusion

    In this tutorial, we implemented simple Lumen REST API. If you have any issue regarding this tutorial, mention your issue in the comment section or reach me through my E-mail. You can obtain complete source code for this tutorial from this GitHub repository.