RESTful API with Lumen

Rahul Bari June 14, 2019

RESTful API with Lumen

Lumen is a micro-framework built on top of Laravel’s core components. Lumen utilizes a lot of familiar concepts from Laravel such as Eloquent, caching, routing, middleware and its service container. The biggest advantage of Lumen is its speed which makes it the most preferred framework for building fast micro-services or APIs.

Setting up Lumen:

There are several ways to set up Lumen locally, the Composer being one of them which we are going to use here.
To know about other ways to set up Lumen, Click here.

From your terminal, run composer create-project — prefer-dist laravel/lumen lumen_api

This will install Lumen and all its dependencies for you in the lumen_api directory.
After that, rename the .env.example file located in the root directory to .env.

To run your project locally, you can make use of PHP’s built-in server by running the following command: php -S localhost:8000 -t public or just type the following URL:

localhost:8000/lumen_api/public/

You will see the screen indicating that Lumen is successfully installed as shown in the following screenshot:
lumen setup

REST API Endpoints:

You will be building a REST API that handles Create, Read, Update and Delete tasks for a product resource. Let’s take a look at our endpoints:

  • GET /products — Fetch all product resource
  • POST /products— Create a new product resource
  • GET /product/{id} — Fetch a product resource by id
  • PUT /product/{id} — Update a product resource by id
  • DELETE /product/{id}- Delete a product resource by id

Database and Migrations:

Run the following command to create a migration file:

php artisan make:migration create_products_table

This will create a new migration file for you in the database/migrations directory.
Your product resource will have 3 attributes i.e. name, price, and description.

Add the following code to the created migration file:

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
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');
}
}

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

Creating 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

Go to the app directory and create a new model called Product.php

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

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

Controller Methods:

Let’s create our controller. Navigate to the app\Http\Controller directory and create a ProductController.php file. Add the following code to the controller:

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Product;
use Laravel\Lumen\Routing\Controller as BaseController;
use DB;
use Response;

class ProductController extends BaseController {

    public function index() {
        $products = DB::select('select * from products');
        if (empty($products)) {
            $arr = array('code' => 404, 'message' => 'No data found');
            echo json_encode($arr);
        } else {
            $countallproducts = count($products);
            if ($countallproducts > 0) {
                return response()->json(array(
                            'code' => 200,
                            'data' => $products
                                ), 200);
            }
        }
    }

    public function create(Request $request) {
        $product = new Product;
        $product->name = $request->name;
        $product->price = $request->price;
        $product->description = $request->description;
        $datainsert = $product->save();
        if ($datainsert == 1) {
            $lastid = DB::getPdo()->lastInsertId();
            $product_inserted = DB::select('select * from products where id = ?', [$lastid]);
            return response()->json(array(
                        'code' => 200,
                        'data' => $product_inserted
                            ), 200);
        }
    }

    public function show($id) {
        $product = Product::find($id);
        $product_show = DB::select('select * from products where id = ?', [$id]);

        if (empty($product_show)) {
            $arr = array('code' => 404, 'message' => 'ID not found or invalid');
            echo json_encode($arr);
        } else {
            $count = count($product_show);
            if ($count == 1) {
                return response()->json(array(
                            'code' => 200,
                            'data' => $product
                                ), 200);
            }
        }
    }

    public function productupdate(Request $request, $id) {
        $product = Product::find($id);
        $prod_data = DB::select('select * from products where id = ?', [$id]);
        if (empty($prod_data)) {
            $arr = array('code' => 404, 'message' => 'ID not found or invalid');
            echo json_encode($arr);
        } else {
            $product->name = $request->input('name');
            $product->price = $request->input('price');
            $product->description = $request->input('description');
            $array = array('name' => $request->input('name'), 'price' => $request->input('price'), 'description' => $request->input('description'));
            $dataupdate = DB::table('products')->where('id', '=', $id)->update($array);
            $product_updated = DB::select('select * from products where id = ?', [$id]);

            if ($dataupdate == 1) {
                return response()->json(array(
                            'code' => 200,
                            'data' => $product_updated,
                            'message' => 'Data updated'
                                ), 200);
            }
            if ($dataupdate == 0) {
                return response()->json(array(
                            'code' => 200,
                            'data' => $product_updated,
                            'message' => 'Data already updated'
                                ), 200);
            }
        }
    }

    public function productdelete($id) {
        $datadelete = DB::table('products')->where('id', '=', $id)->delete();
        if ($datadelete == 1) {
            return response()->json(array(
                        'code' => 200,
                        'message' => 'Data deleted'
                            ), 200);
        }
        if ($datadelete == 0) {
            return response()->json(array(
                        'code' => 404,
                        'message' => 'ID not found or invalid'
                            ), 404);
        }
    }
}
  • The Index method returns all available products as a JSON response.
  • The Create method creates a new product and returns the newly created product as a JSON response.
  • The Show method returns a single product resource by its id. This is also returned as a JSON response.
  • The Productupdate method updates a single product resource by its id as well.
  • The Productdelete method deletes a product resource by its id and returns a success message.

Adding the routes:

Open up the web.php file in the routes folder and add the following code:

$app->group(['prefix'=>'api'], function() use($app){
$app->get('/products', 'ProductController@index');
$app->post('/product', 'ProductController@create');
$app->get('/product/{id}', 'ProductController@show');
$app->put('/product/{id}', 'ProductController@update');
$app->delete('/product/{id}', 'ProductController@destroy');
});

API Testing:

We’ll be using Postman to test our API as follows:

1. View All Products

2. View Specific Product

3. Insert Product

4. Update Product

5. Delete Product

“In case I missed something, do let me know in the comments!”

Cheers!!

Lets’s Talk

About your ideas and concept