...

Easiest Laravel Lumen Restful API Tutorial (easy steps)

Laravel Lumen is a micro framework that was developed for the purpose of API Development. According to Lumen’s official website:

“Lumen is the perfect solution for building Laravel based micro-services and blazing fast APIs. In fact, it's one of the fastest micro-frameworks available. It has never been easier to write stunningly fast services to support your Laravel applications.”

In this blog I am going to show you how you can develop a simple API using the amazingly fast Lumen in simplest steps possible. Without any more boring paragraphs lets move to the steps.

Step 1 - Setting Up Basic Project:

- Open command prompt and go to htdocs/www folder (depending on xampp,wamp).

- Run the following command to create project in that folder:

composer create-project --prefer-dist laravel/lumen rest-api

- Open the created project in code editor (I am using VS Code)

- Rename the .env.example to .env (if not already created)

- Open the .env file and replace

CACHE_DRIVER=file
QUEUE_CONNECTION=sync

with

CACHE_DRIVER=array
QUEUE_DRIVER=database

- Start the localhost services

- Press ctrl + ` to open up terminal in VS Code and run the following command:

php -S localhost:8000 -t public

- Visit localhost:8000 on your browser and you will see the following screen

Step 2:

The basic project has been created and now we will move to RESTful API part. In this tutorial I am going to show you how you can implement CRUD operations on an entity.

C = POST

R = GET

U = PUT

D = DELETE

- Detail of routes and methods:

GET /users— Fetch all users resource

POST /users — Create a new users resource

GET /user/{id} — Fetch a user resource by id

PUT /user/{id} — Update a user resource by id

DELETE /user/{id}- Delete a user resource by id

Database and Migration:

- Visit localhost/phpmyadmin and create database named rest_db

- Update .env file database variables to:

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

- In the terminal run the following command:

php artisan make:migration create_users_table

- open migration file from database/migrations and replace the code with following:

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('address');
            $table->timestamps();
        });
    }
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
}

- Run the command php artisan migrate

- Create model in app folder named User.php and paste the following:

namespace App;
use Illuminate\Auth\Authenticatable;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Database\Eloquent\Model;
use Laravel\Lumen\Auth\Authorizable;
class User extends Model implements AuthenticatableContract, AuthorizableContract
{
    use Authenticatable, Authorizable;
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'address',
    ];
    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = [
    ];
}

- Un-comment following lines from bootstrap/app.php

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

Step 3:

- In app/Http/Controllers create a php file named UserController.php and paste the following code in it

namespace App\Http\Controllers;
use App\User;
use Illuminate\Http\Request;
class UserController extends Controller
{
   /**
    * Create a new controller instance.
    *
    * @return void
    */
   public function index()
   {
      $users = User::all();
      return response()->json($users);
   }
   public function create(Request $request)
   {
      $user = new User;
      $user->name = $request->name;
      $user->address = $request->address;
      $user->save();
      return response()->json($user);
   }
   public function show($id)
   {
      $user = User::find($id);
      return response()->json($user);
   }
   public function update(Request $request, $id)
   {
      $user = User::find($id);
      $user->name = $request->input('name');
      $user->address = $request->input('address');
      $user->save();
      return response()->json($user);
   }
   public function destroy($id)
   {
      $user = User::find($id);
      $user->delete();
      return response()->json('User removed successfully');
   }
}
  1. index method returns all users as a JSON response.
  2. create method creates a new user and returns the newly created user as a JSON response.
  3. show method returns a single user by its id as a JSON response.
  4. update method updates a single user by its id as well.
  5. delete method deletes a user resource by its id and returns a success message.

Step 4:

Open routes/web.php and paste following routes in it

$router->group(['prefix' => 'api/v1'], function () use ($router) {
    $router->get('/users', 'UserController@index');
    $router->post('/user', 'UserController@create');
    $router->get('/user/{id}', 'UserController@show');
    $router->put('/user/{id}', 'UserController@update');
    $router->delete('/user/{id}', 'UserController@destroy');
});

Your Restful API is ready and you can easily test it using Postman Software.

All users:

Method: GET

URL: http://localhost:8000/api/v1/users

Create user:

Method: POST

URL: http://localhost:8000/api/v1/user

Required: name,address

Get specific user:

Method: GET

URL: http://localhost:8000/api/v1/user/1

Update specific user:

Method: PUT

URL: http://localhost:8000/api/v1/user/1

Required: name,address

Delete specific user:

Method: DELETE

URL: http://localhost:8000/api/v1/user/1

If you need a web app developer for your amazing app development or fix than please have a look at my portfolio. You can contact me anytime you like :)