Laravel REST API with Passport Authentication
Today we are going to build a REST API using Laravel and Laravel Passport. To implement API, we use php framework Laravel , Laravel Passport and we use MYSQL to store our data.
Prerequisites
Setting up the Project
First you need to create a new laravel project by running below command in your terminal
1
composer create-project laravel/laravel laravel-passport-auth --prefer-dist
1 | composer create-project laravel/laravel laravel-passport-auth --prefer-dist |
Then navigate to your project directory by using below command in your terminal
1 | cd laravel-passport-auth |
Setting up Database
To setup up Database for our project, open the application using your favourite text editor and and then navigate to .env
file in it and then change below section acording to your Database settings:
1
2
3
4
5
6
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel-passport-auth
DB_USERNAME=root
DB_PASSWORD=
1 | DB_CONNECTION=mysql |
Install Passport Package
Now we need to o install the passport package through Composer package manager.
1
composer require laravel/passport
1 | composer require laravel/passport |
Now we need to run the default migration to create a new tables in the MySQL database.
1 | php artisan migrate |
Next, to generate token keys for securing our application.
1 | php artisan passport:install |
Configure Passport Module
To configure the Passport package in our Laravel application, open app/Models/User.php
file and include HasApiTokens
trait inside the User
model, as mentioned below.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
<?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
{
use HasFactory, Notifiable, HasApiTokens;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
1 | <?php |
Now open app/Providers/AuthServiceProvider.php
file and paste below code:
1 | <?php |
Then you shoul register register the PassportServiceProvider
class in providers
array inside the config/app.php
file:
1 | 'providers' => [ |
Finally we need to configure the driver for the Passport. To do it get inside the config/auth.php
file and make the changes as shown below.
1 | <?php |
Create Posts Model & Run Migration
To make the connection between the client and the server, we we require to create the Post
model by running below command:
1
php artisan make:model Post -m
1 | php artisan make:model Post -m |
After executing the above command, navigate to database/migrations/timestamp_create_posts_table
and change it shown as below:
1 | <?php |
Then navigate to app/Models/Post.php
file and register the following values inside $fillable
array.
1 | <?php |
Then, run the migration by using the below command:
1 | php artisan migrate |
Create a New Controller
Then we need to create a new controller in our laravel app to create a login and registration REST API.
1
php artisan make:controller PassportAuthController
1 | php artisan make:controller PassportAuthController |
Now you need to replace PassportAuthController.php
by inserting below code:
1 | <?php |
Now we need to establish our connection between Post
and User
model. Change app/Models/User.php
file.
1 | <?php |
Then create Post Controller by running below command:
1 | php artisan make:controller PostController |
Then add following code in to PostController.php
1 | <?php |
Define API Routes
Go to your routes/api.php
file and place below code in it:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\PassportAuthController;
use App\Http\Controllers\PostController;
/*
|--------------------------------------------------------------------------
| 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::post('register', [PassportAuthController::class, 'register']);
Route::post('login', [PassportAuthController::class, 'login']);
Route::middleware('auth:api')->group(function () {
Route::resource('posts', PostController::class);
});
1 | <?php |
Run our application
Now we have already finished with our API creation. Before testing our API in Postman, you need to run your application using below command:
1
php artisan serve
1 | php artisan serve |
Testing APIs
To test our API endpoints, we need to use Postman.
Register
Method: POST
URL:http://localhost:8000/api/register
Body
x-www-form-urlencoded
Key
Value
name
name
email
example@example.com
password
password
Login
Method: POST
URL:http://localhost:8000/api/login
Authorization: Bearer “access-token”
Body
x-www-form-urlencoded
Key
Value
email
example@example.com
password
password
Create new post
Method: POST
URL:http://localhost:8000/api/posts
Authorization: Bearer “access-token”
Body
x-www-form-urlencoded
Key
Value
title
title
description
description
Get all posts
Method: GET
URL:http://localhost:8000/api/posts
Authorization: Bearer “access-token”
Get single post
Method: GET
URL:http://localhost:8000/api/posts/:id
Authorization: Bearer “access-token”
Update post
Method: PUT
URL:http://localhost:8000/api/posts/:id
Authorization: Bearer “access-token”
Delete post
Method: DELETE
URL:http://localhost:8000/api/posts/:id
Authorization: Bearer “access-token”
Register
Method: POST
URL:http://localhost:8000/api/register
Body
x-www-form-urlencoded
Key | Value |
---|---|
name | name |
example@example.com | |
password | password |
Login
Method: POST
URL:http://localhost:8000/api/login
Authorization: Bearer “access-token”
Body
x-www-form-urlencoded
Key | Value |
---|---|
example@example.com | |
password | password |
Create new post
Method: POST
URL:http://localhost:8000/api/posts
Authorization: Bearer “access-token”
Body
x-www-form-urlencoded
Key | Value |
---|---|
title | title |
description | description |
Get all posts
Method: GET
URL:http://localhost:8000/api/posts
Authorization: Bearer “access-token”
Get single post
Method: GET
URL:http://localhost:8000/api/posts/:id
Authorization: Bearer “access-token”
Update post
Method: PUT
URL:http://localhost:8000/api/posts/:id
Authorization: Bearer “access-token”
Delete post
Method: DELETE
URL:http://localhost:8000/api/posts/:id
Authorization: Bearer “access-token”