Skip to content

API Development

Tuhin Bepari edited this page Jul 30, 2018 · 12 revisions

We are going to use Dingo API.

Quick Installation of Dingo API

If you already install dingo then ignore this section.

Step One: add this line to your composer.json

   "require": {
       "dingo/api": "^2.0",
       "tymon/jwt-auth": "1.0.*"
   }

Step Two: add this dingo configuration into your .env file

API_STANDARDS_TREE=x
API_NAME="Laracrud API"
API_SUBTYPE=laracrud
API_PREFIX=api
API_VERSION=v1
API_STRICT=false
API_DEBUG=false

For authentication you can use either jwt-auth or laravel passport

After install JWT-Auth

Step Three: Please add the following lines of code into your App\Providers\AuthServiceProvider::boot method if you want to use Jwt-Auth.

   app('Dingo\Api\Auth\Auth')->extend('jwt', function ($app) {
        return new \Dingo\Api\Auth\Provider\JWT($app['Tymon\JWTAuth\JWTAuth']);
    });

Step Four: run following command

   php artisan jwt:secret

Step Five: Implement JWTSubject into your User Model

namespace App\Models;

use Illuminate\Foundation\Auth\User as Authenticatable;
use Tymon\JWTAuth\Contracts\JWTSubject;
class User extends Authenticatable implements JWTSubject
{
   
    public function getJWTIdentifier()
    {
        return $this->getKey();
    }
 
    public function getJWTCustomClaims()
    {
        return [];
    }
}

Step Six: Change api driver to jwt from config/auth

    'api' => [
            'driver' => 'jwt',
            'provider' => 'users',
        ],

Step Seven: Generate and Use Token

namespace App\Http\Controllers\Api\Auth;

use JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;
use Illuminate\Http\Request;

class TokenController extends ApiController
{

    public function authenticate(Request $request)
    {
        $credentials = $request->only('email', 'password');

        try {
            if (!$token = JWTAuth::attempt($credentials)) {
                return response()->json(['error' => 'Email or Password does not match'], 401);
            }
        } catch (JWTException $e) {
            return $this->response->errorInternal('Could not create token');
        }

        return $this->response->array([
            'token' => $token,
            'expire_in' => \Carbon\Carbon::now()->addMinutes(config('jwt.ttl'))->format('Y-m-d H:i:s')
        ]);

    }
}

This method will generate token and you have to use it using header like below

header("Authorization: Bearer YOUR_TOKEN");

Congratulation you are ready to use Dingo API now.

Create Request Class

      php artisan laracrud:request posts --resource=all --api

This will create Request classes into app/Http/Requests/Api/Posts folder for your resourceful controller. You can configure Request root namespace from config/laracrud.php

Create Transformer Class

      php artisan laracrud:transformer Post

Transformer are special class that will control how much data you like to expose from your model to outside world

Create Controller

If you have not create your models then you must create by laracrud:model command .

      php artisan laracrud:controller Post --api

This command will create PostController into app/Http/Controllers/Api folder. You can able to define root api controller's namespace from config/laracrud.php.

Define Routes

We can able to manage api versions in dingo api easily. Create a version1.php file into your routes folder. Then change the api route file path from your config/laracrud.php.

Your routes/api.php file will looks like below

$router = app('Dingo\Api\Routing\Router');
$router->version('v1', ['namespace' => 'App\Http\Controllers\Api'], function ($api) {
    require __DIR__ . '/version1.php';
});

This command will generate routes for your api

   php artisan laracrud:route PostController --api

N.B: Remove closure routes if you have. Dingo does not able to parse route if you have any closure based route.

Now run

      php artisan api:cache

This command will register your routes and cache it. Dingo routes resolve from cache. So each time you make a change to your routes you have to run the above command.

API Documentation

Documentation are vital part of a API . Its the guideline to others developer who will consume your API. LaraCrud generate basic crud method's documentation for you. For more info you can have a look to Dingo Documentation Now run

      php artisan api:docs --output-file=apidocs.md

This will create apidocs.md file into your base directory.

Video Tutorial

watch video tutorial