In the previous article Laravel api integration & configuration, we have successfully set up a Passport package in a fresh Laravel application. Now in this article, we are going to create API using the passport and we will protect all API routes and can be accessed If the user passes bearer token in each API request, otherwise the user can’t get any response.

build api using laravel passport

Now before we jump to build API using the Laravel passport package, we need to create a movie table and that will be used for the movies listing API and only accessible via a bearer token so let’s create a migration and seeder for that.

Step 1:

php artisan make:migration movies

Add below schema code to your movies migration file which will be placed in your database/migrations directory.

/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::create('movies', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('year');
        $table->string('duration');
        $table->string('type');
        $table->string('about');
        $table->timestamps();
    });
}

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

Run migrate command to generate movies table.

php artisan migrate

To generate a seeder, execute the below code on your terminal screen.

php artisan make:seeder MoviesSeeder

Now add some dummy movies data in your MoviesSeeder seeder file which will be used for listing API.

<?php

use Carbon\Carbon;
use Illuminate\Database\Seeder;

class MoviesSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        DB::table('movies')->insert([
            [
                'name'       => 'The Shawshank Redemption',
                'year'       => '1994',
                'duration'   => '142 mins',
                'type'       => 'Drama',
                'about'      => 'Two imprisoned men bond over a number of years, finding solace and eventual redemption through acts of common decency.',
                'created_at' => Carbon::now(),
                'updated_at' => Carbon::now()
            ],
            [
                'name'       => 'Forrest Gump',
                'year'       => '1994',
                'duration'   => '142 mins',
                'type'       => 'Drama, Romance',
                'about'      => 'The presidencies of Kennedy and Johnson, the events of Vietnam, Watergate, and other history unfold through the perspective of an Alabama man with an IQ of 75.',
                'created_at' => Carbon::now(),
                'updated_at' => Carbon::now()
            ]
        ]);
    }
}

Don’t forget to include MoviesSeeder in your DatabaseSeeder class file.

Run seeder command to generate dummy entries.

php artisan db:seed

Step 2:

Now we are going to work on the following API so follow the code step by steps and implement in your application:

  • Registration
  • Login
  • Movies List
  • Logout

Create an API folder at app/Http/Controllers directory and generate the following controllers:

  • AuthController
  • MoviesController

Step 3:

Open your api.php file from the routes directory and update login, registration, movies & logout API routes.

<?php

use Illuminate\Http\Request;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/

Route::group([
    'prefix' => 'auth'
], function () {
    Route::post('login', 'API\AuthController@login');
    Route::post('register', 'API\AuthController@register');

    Route::group([
      'middleware' => 'auth:api'
    ], function () {
        Route::get('movies', 'API\MoviesController@getMovies');
        Route::get('logout', 'API\AuthController@logout');
    });
});

Movies [app/Movies.php]

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Movies extends Model
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'movies';

    /**
     * The primary key associated with the table.
     *
     * @var string
     */
    protected $primaryKey = 'id';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'year', 'duration', 'type', 'about', 'created_at', 'updated_at'
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [];
}

AuthController [app/Http/Controllers/API/AuthControllers]

<?php

namespace App\Http\Controllers\API;

use App\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\URL;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;

class AuthController extends Controller
{
    protected $user;

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct(User $user)
    {
        $this->user = $user;
    }

    /**
     * Login user and create token.
     *
     * @param Request $request
     * @return void
     */
    public function login(Request $request)
    {
        // Validate incoming request
        $validator = Validator::make($request->all(), [
           'email'    => 'required',
           'password' => 'required'
        ]);

        if ($validator->fails()) {
            $data = [
                'data'    => '',
                'message' => $validator->messages()->first(),
                'status'  => 0
            ];
        } else {
            if (!Auth::attempt(['email' => $request->email, 'password' => $request->password])) {
                $data = [
                    'data'    => '',
                    'message' => 'Unauthorized.',
                    'status'  => 0
                ];
            } else {
                $user = $request->user();
                $tokenResult = $user->createToken('Personal Access Token');
                $token = $tokenResult->token;
                $token->save();

                $data = [
                    'user_id'      => $user->id,
                    'name'         => $user->name,
                    'email'        => $user->email,
                    'token_type'   => 'Bearer',
                    'access_token' => $tokenResult->accessToken,
                    'message'      => 'You are authenticated successfully.',
                    'status'       => 1
                ];
            }
        }

        $header = array(
            'Content-Type' => 'application/json; charset=UTF-8',
            'charset'      => 'utf-8'
        );

        return response()->json(['data' => $data], 200, $header, JSON_UNESCAPED_UNICODE);
    }

    /**
     * Register new user.
     *
     * @param Request $request
     * @return void
     */
    public function register(Request $request)
    {
        // Validate incoming request
        $validator = Validator::make($request->all(), [
            'name'     => 'required',
            'email'    => 'required|email|unique:users',
            'password' => 'required'
        ]);

        if ($validator->fails()) {
            $data = [
                'data'    => '',
                'message' => $validator->messages()->first(),
                'status'  => 0
            ];
        } else {
            $userObj = new $this->user([
                'name'         => $request->name,
                'email'        => $request->email,
                'password'     => Hash::make($request->password),
            ]);
            if ($userObj->save()) {
                $data = [
                    'user_id'      => $userObj->id,
                    'name'         => $userObj->name,
                    'email'        => $userObj->email,
                    'token_type'   => 'Bearer',
                    'access_token' => $userObj->createToken('Personal Access Token')->accessToken,
                    'message'      => 'You account created successfully.',
                    'status'       => 1
                ];
            } else {
                $data = [
                    'data'    => '',
                    'message' => 'Oops! Something went wrong.',
                    'status'  => 0
                ];
            }
        }

        $header = array(
            'Content-Type' => 'application/json; charset=UTF-8',
            'charset'      => 'utf-8'
        );

        return response()->json(['data' => $data], 200, $header, JSON_UNESCAPED_UNICODE);
    }

    /**
     * Logout user (Revoke the token).
     *
     * @param Request $request
     * @return void
     */
    public function logout(Request $request)
    {
        $request->user()->token()->revoke();

        $data = [
            'data' => '',
            'message' => 'You are successfully logged out.',
            'status' => 1
        ];

        return response()->json(['data' => $data]);
    }
}

MoviesController [app/Http/Controllers/API/MoviesControllers]

<?php

namespace App\Http\Controllers\API;

use App\Movies;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\URL;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;

class MoviesController extends Controller
{
    protected $movies;

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct(Movies $movies)
    {
        $this->movies = $movies;
    }

    /**
     * Get list of movies.
     *
     * @return void
     */
    public function getMovies()
    {
        $moviesObj = $this->movies->get();

        $data = [
            'data'    => $moviesObj,
            'message' => 'You are successfully logged out.',
            'status'  => 1
        ];

        return response()->json(['data' => $data]);
    }
}

Now open postman in your system and start palying with your API.

  • Registration (http://localhost/passport/public/api/auth/register)
  • Login (http://localhost/passport/public/api/auth/login)
  • List Of Movies (http://localhost/passport/public/api/auth/movies)
  • Logout (http://localhost/passport/public/api/auth/logout)

Screenshots:

That’s it. You have successfully build API using the Laravel Passport package in your Laravel application.

Keep visiting for new stuff and give your feedback.

Happy Coding 😉

Categories: Laravel

%d bloggers like this: