Create REST API using passport authentication in laravel

Create REST API using passport authentication in laravel

In this article let us create REST API using passport authentication in laravel.

Basically, REST API is an interface that use to exchange information securely over the internet using set of rules and methods.

Lets understand it by creating step by step guide over creating a Laravel project.

Step 1 : Create laravel project

Create a Laravel project using below command which will generate a folder Laravel with its default file.

composer create-project laravel/laravel --prefer-dist

After that you will need to make manual changes to your .env file from root for database connection. Set below parameters as per your configuration.

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

Step 2 : Configure passport Auth

Next we will install passport library using below command.

composer require laravel/passport  --with-all-dependencies

Next we need to migrate our database and generate passport token to use.

php artisan migrate

This will create Laravel default tables with passport required tables.

Checkout to app/Models/User.php file and include HasApiTokens trait inside the User model, as mentioned below.

<?php
namespace App\Models;
// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Passport\HasApiTokens;

class User extends Authenticatable
{
.
.

Next, open app/Providers/AuthServiceProvider.php file and register the registerPolicies() method inside the boot() function, It will evoke the required routes.

protected $policies = [
        'App\Models\Model' => 'App\Policies\ModelPolicy',
    ];
public function boot(): void
    {
        $this->registerPolicies();
    }

Configure facade in providers at the config/app.php file:

'providers' => [
        .
        .
        Laravel\Passport\PassportServiceProvider::class,
    ],

Next, configure driver for passport at config/auth.php. Add api guard as below.

<?php
    return [
    .
    .

        'guards' => [
            'web' => [
                'driver' => 'session',
                'provider' => 'users',
            ],
    
            'api' => [
                'driver' => 'passport',
                'provider' => 'users',
            ],
        ],
    .
    .
]

Step 3: Create new model and migration

Next, create Blog model and migration using below command and edit migration file as per your need.

php artisan make:model Blog -m
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('blogs', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('user_id');
            $table->text('title');
            $table->longText('text');
            $table->timestamps();
            $table->foreign('user_id')->references('id')->on('users'); 
        });
    }

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

Next Checkout to app/Models/Blog.php and add fields to fillable array.

class Blog extends Model
{
    use HasFactory;
    protected $fillable = [
        'title', 'text'
    ];
}

Run the migration using below commands. This will create blog table with necessary fields.

php artisan migrate

Step 4: Create auth controller for register and login functionality

We need to create register and login method to simply add user to our system using api. Lets create a controller using below command to generate methods.

php artisan make:controller ApiAuthController

Checkout to newly created controller and add user model to the header and methods as per below.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\User;
class ApiAuthController extends Controller
{
    /**
     * Registration
     */
    public function register(Request $request)
    {
        $this->validate($request, [
            'name' => 'required|min:4',
            'email' => 'required|email',
            'password' => 'required|min:8',
        ]);
 
        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => bcrypt($request->password)
        ]);
       
        $token = $user->createToken('ApiAuth')->accessToken;
 
        return response()->json(['token' => $token], 200);
    }
 
    /**
     * Login
     */
    public function login(Request $request)
    {
        $data = [
            'email' => $request->email,
            'password' => $request->password
        ];
 
        if (auth()->attempt($data)) {
            $token = auth()->user()->createToken('ApiAuth')->accessToken;
            return response()->json(['token' => $token], 200);
        } else {
            return response()->json(['error' => 'Unauthorised'], 401);
        }
    }   
}

We need to add these routes to api routing. Checkout to routes/api.php and add below routes for register and login.

use App\Http\Controllers\ApiAuthController;

Route::post('register', [ApiAuthController::class, 'register']);
Route::post('login', [ApiAuthController::class, 'login']);

Serve the Laravel project to get it started using below command.

php artisan serve

Checkout to postman and call below route. Make sure to add header Accept: application/json.

http://localhost:8000/api/register

Add parameters as below and after successful registration you will see below results.

Lets login using above added user.

http://localhost:8000/api/login

You will see below result upon successful login.

Step 5: Create blog methods and routes

Next let’s create blog module using our api routes.

First create blog controller using below command.

php artisan make:controller BlogController

Head to the newly created blogcontrller and add below code. It’s simply crud operation you will easily understand. Add blog model in header.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Blog;

class BlogController extends Controller
{
    public function index()
    {
        $blogs = auth()->user()->blogs;
 
        return response()->json([
            'success' => true,
            'data' => $blogs
        ]);
    }
 
    public function show($id)
    {
        $blog = auth()->user()->blogs()->find($id);
 
        if (!$blog) {
            return response()->json([
                'success' => false,
                'message' => 'blog not found '
            ], 400);
        }
 
        return response()->json([
            'success' => true,
            'data' => $blog->toArray()
        ], 400);
    }
 
    public function store(Request $request)
    {
        $this->validate($request, [
            'title' => 'required',
            'text' => 'required'
        ]);
 
        $blog = new Blog();
        $blog->title = $request->title;
        $blog->text = $request->text;
 
        if (auth()->user()->blogs()->save($blog))
            return response()->json([
                'success' => true,
                'data' => $blog->toArray()
            ]);
        else
            return response()->json([
                'success' => false,
                'message' => 'blog not added'
            ], 500);
    }
 
    public function update(Request $request, $id)
    {
        $blog = auth()->user()->blogs()->find($id);
 
        if (!$blog) {
            return response()->json([
                'success' => false,
                'message' => 'blog not found'
            ], 400);
        }
 
        $updated = $blog->fill($request->all())->save();
 
        if ($updated)
            return response()->json([
                'success' => true
            ]);
        else
            return response()->json([
                'success' => false,
                'message' => 'blog can not be updated'
            ], 500);
    }
 
    public function destroy($id)
    {
        $blog = auth()->user()->blogs()->find($id);
 
        if (!$blog) {
            return response()->json([
                'success' => false,
                'message' => 'blog not found'
            ], 400);
        }
 
        if ($blog->delete()) {
            return response()->json([
                'success' => true
            ]);
        } else {
            return response()->json([
                'success' => false,
                'message' => 'blog can not be deleted'
            ], 500);
        }
    }
}

Next, we need to add blog routes in out api route as per below.

use App\Http\Controllers\BlogController;
Route::middleware('auth:api')->group(function () {
    Route::resource('blogs', BlogController::class);
});

We need to define our user model relationship with blog model. Head to app//Models/User.php and add below function.

public function blogs()
    {
        return $this->hasMany(Blog::class);
    }  

Now to use these apis we need to take that token from login and add into blog apis header to get it work. Lets add few posts see below:

//post method
http://localhost:8000/api/blogs

See below we have now added new blog for logged in user.

To list all the blogs we will use get method as we defined in our controller. See below.

//GET method
http://localhost:8000/api/blogs

That’s it. It’s all about out passport auth in Laravel. Hope you find it usefull.