Learn to develop Laravel RESTful API
  • api
  • Framework
  • Laravel
  • web development
  • website

Learn to develop Laravel RESTful API

Laravel RESTful API Development, Step By Step Previously we have discussed how to integrate Laravel APIs in Angular app. In this tutorial we will learn how…

   
Learn to develop Laravel RESTful API

Laravel RESTful API Development, Step By Step

Previously we have discussed how to integrate Laravel APIs in Angular app. In this tutorial we will learn how to create RESTful API’s using php Laravel framework and its different methods with authentication.First of all, let’s talk about what is RESTful API.

What is RESTful API?

Representational State Transfer (REST) is an architectural style for network communication between applications, which relies on a stateless protocol (usually HTTP) for interaction. In REST standard API requests, we have four methods.
  • Get: to retrieve data
  • Post: to create or store data
  • Put: to update data
  • Delete: to delete data
There are other methods but these are the most used ones.

RESTful API Authentication

Now let’s talk about the authentication in REST APIs. API authentication means to allow only authorized people with key/token access and mandate to the inner data or actions of the application underlying the API. Authentication is very important in API’s because every app wants its data to be secure and save. So, for that purpose we will use Laravel Passport to make our API’s authenticated, now let’s jump to a short intro about Laravel Passport

Laravel Passport

1. Introduction

APIs typically use tokens to authenticate users and do not maintain session state between requests. Laravel makes API authentication a breeze using Laravel Passport, which provides a full OAuth2 server implementation for your Laravel application.

2. Installation

For this discussion, we are assuming that we already have a working Laravel project. First of all, we need to install the Laravel Passport package in our Laravel project and after that we have to perform some configuration to make it functional, so let’s start.
composer require laravel/passport
This command will install Laravel passport package, it will take some time depending on internet speed, when the package is installed after that you need to run another command
php artisan migrate
The Passport service provider registers its own database migration directory with the framework, so we need to run migration command once again because it will generate some tables which are necessary for laravel passport, now once we are done with migration then we will run another command
php artisan passport:install
This command will create the encryption keys needed to generate secure access tokens. In addition, the command will create “personal access” and “password grant” clients which will be used to generate access tokensAfter running that command you need to add “Laravel\Passport\HasApiTokens” trait to our User Model class. This trait will provide a few helper methods to your model which allow you to inspect the authenticated user’s token and scopes
namespace App;
use Laravel\Passport\HasApiTokens;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use HasApiTokens, Notifiable;
}
Now moving further we need to call the “Passport::routes” method with in the boot method of our AuthServiceProvider, this method will register routes necessary access token and revoke access token
namespace App\Providers;
use Laravel\Passport\Passport;
use Illuminate\Support\Facades\Gate;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
class AuthServiceProvider extends ServiceProvider
{
/**
* The policy mappings for the application.
*
* @var array
*/
protected $policies = [
	'App\Model' => 'App\Policies\ModelPolicy',
];
/**
* Register any authentication / authorization services.
 *
* @return void
*/
public function boot()
{
	$this->registerPolicies();
	Passport::routes();
}
}
Now one final thing needs to be changed then we will be ready to go with it. In our “config/auth.php” configuration file, we have to set the driver option to API authentication guard to passport.
guards' => [
    			'web' => [
        			'driver' => 'session',
        			'provider' => 'users',
    			],

    		'api' => [
        			'driver' => 'passport',
        			'provider' => 'users',
   	 	],
	],
Now let’s dive into to API creation process.Note: We will be using users table as main table and respectively User Model and UserController as an example

Create Laravel fresh project and database and put some records in database.

Basically there are two different methods of developing the RESTful API’s one is the simple method and the second one is the advance method we will discuss both of them in detail in this tutorial

Method 1: (Simple method)

In this method we will create four different routes to get, create, update and delete the data and after that we will have to create different four functions to perform functionality respectivelyNow let’s jump into our first step and starts implementation

Step 1:

In this step we will create a new database if already not created and if it is so we will create model for a specific table and then we’ll define that what fields/columns of our database table are fillable, now let’s move towards the code and see how it will works If you have empty database run the command
“php artisan migrate”
This will create some tables in you database, after that navigate to User.php (Model) inside app folder and add following code in it which is listed below inside User Class
protected $fillable = [
        'name', 'email', 'password',
    ];
Fillable are the names of columns of your table so you can change them according to your table structure If you are using any other table than users than you have to create a new model for it and named it as the name of table but in singular, command to generate the model is listed below:
“php artisan make:model modelName”
Then same you have to define fillable for your own table like I have done for the users table above

Step 2:

In this step we will create some api routes to perform the CRUD functionality Navigate to api.php file inside routes folder and add some code of lines in it
a. Route::get(‘get-users’, ‘UserController@getUsersDetails’)
i. This route will be used to get all the records of the users table
b. Route::post(‘store-user’, ‘UserController@storeUserDetails);>/pre>
i. This route will be used to upload a user record into database
c. Route::put('update-user/{id}', 'UserController@updateUserDetails');
i. This route will be used to update the user record of a specific user
d. Route::delete('delete-user/{id}', 'UserController@deleteUserDetails');
i. This route will be used to delete the record of a specific user

Step 3:

In this step we will create a new controller to handle the CRUD request and its functionalities.

Create new Controller named “UserController” using command
“php artisan make:controller UserController”
Then navigate to UserController.php inside App\Http\Controllers\, and paste the following code in UserController class Note: Don’t forget to include the Model at the top of the controller method to include model is App\ModelName; In my case I am using User (model) so I have to include it, App\User; Function to get all the user records, this function will retrieve all the records in users table
“
public function getUsersDetails()
    	{
        $userDetails = User::all();
        if ($userDetails) {
            return response()->json([
                'userDetails' => $userDetails
            ], 200);
        }
        return response()->json([
            'errorMsg' => 'No record found'
        ], 404);
    	}

”

Function to create new user

In this function you have to pass some parameters accordingly your database table columns and then it will be by Request method and will be stored in database table
“
public function storeUserDetails(Request $request) 
    	{
        $createUser = User::create($request->all());
        return response()->json([
            'successMsg' => 'New User Created'
        ], 200);
    	}
”

Function to update user Details

If this function there are two types of parameters one is the data which we need to update and the  second one is the id of user which we need to update
“
public function updateUserDetails(Request $request, $userId)
    	{
        $updateUser = find($userId);
        if ($updateUser) {
            $updateUser = $updateUser->update([$request->all()]);
            return response()->json([
                'userDetails' => $updateUser
            ], 200);
        }
        return response()->json([
            'errorMsg' => 'No user found'
        ], 404);
    	}

”

Function to delete user details

This function requires 1 parameter which will be the user id to delete the record of that specific user
“
public function deleteUserDetails($userId)
    	{
        $deleteUser = find($userId);
        if ($deleteUser) {
            $deleteUser->delete();
            return response()->json([
                'successMsg' => 'User Record Deleted'
            ], 200);
        }
        return response()->json([
            'errorMsg' => 'No user found'
        ], 404);
    	}
”

Method 2:

Note: Step 1 of method 2 is same as the step 1 of method 1 If you are following method 2 directly please go through step 1 of method 1

Step 2:

In this step we will add a single route which will perform 5 functionalities
  • Get all users
  • Get specific user
  • Create new user
  • Update a user
  • Delete a user
Navigate to api.p Navigate to api.php file inside routes folder and add some code of lines in it.
a. Route::apiResource('user', 'API\UserController');
In this route we did not mentioned any methods like get, post, because this single route will entertain all the methods. apiResource is collection of different routes let me explain it with a table

Method

URI

Action

Route Name

GET

/users

index

users.index

GET

/users/{user}

show

users.show

POST

/user

store

users.store

PUT

/user/{user}

update

users.update

DELETE

/user/{user}

destroy

user.destroy

These are the 5 methods which exist in a single apiResource route

Step 3:

In this step we will create a new resource User controller inside the API folder to differentiate between the existing UserController which we have created in step 3 of method 1. Create new Controller named “UserController” using command
“php artisan make:controller API/UserController --api”
This command will create a new UserController inside App\Http\Controllers\API\ folder. Navigate to UserController inside the API folder you will find 5 functions are created by defualt which are 1. index i. Paste the function getUsersDetails() code inside the function index() of new UserController2. store i. Paste the function storeUserDetails() code inside the function store() of new UserController3. show4. update i. Paste the function updateUserDetails() code inside the function update() of new UserController5. destroy i. Paste the unction deleteUserDetails() code inside the function destroy() of new UserController There is 1 new function you will see in the list which is function show(), this function will be used to get the record of the single user you just have to pass the user id as a parameter, code for this function is listed below: This function requires 1 parameter which will be the user id to get the record of that specific user
public function show($id)
    	{
        $userDetails = find($id);
        if ($userDetails) {
            return response()->json([
                'userDetails' => $userDetails
            ], 200);
        }
        return response()->json([
            'errorMsg' => 'No user found'
        ], 404);
    	}

Usage of Laravel Passport for authentication:

Step 1:

In this step we will add some routes to our api.php file for user signup and login, so navigate into api.php file and paste the following code in it.
a. Route::post('/register’, ‘Auth\RegisterController@register’);
b. Route::post(‘/login’, ‘Auth\LoginController@login’);

Step 2:

Now we have to create functions in register and login controllers to specify the functionality So first of all navigate to RegisterContoller inside the app\Http\Controller\Auth\ and paste the lines of code in it.
public function register(Request $request)
{
	$userDetails = $request->all();
	$userDetails->password = bcrypt($userDetails->password);
	$registerUser = User::create($userDetails);
	return response()->json([
		'successMsg' => 'New User Registered'
	], 200);

}
Now navigate to LoginController inside app\Http\Controller\Auth\ and paste the following code in it
public function login(Request $request)
{
	if (auth()->attempt(['email' => $request->input('email'), 'password' => $request->input('password')])) {
		$user = auth()->user();
		$userToken = $user->createToken()->accessToken;
		return response()->json([
			'userDetails' => $user,
			'access_token' => $userToken
		], 200);
	}
	return response()->json([
		'errorMsg' => 'Invalid credentials'
	], 404);
}
This function will return us user details and access_token, access_token will be that token we will be using for authentication.

Step 3:

In this step we will secure our routes which means routes will be accessible if you have a valid access token otherwise you will not able to use those route Now once again navigate to api.php file and remove one file from it
a. Route::apiResource('user', 'API\UserController');
Reason for removing this route is that we will put this route under the authenticated section now after removing it please add the following lines of code in api.php file
Route::group(['middleware' => ['auth:api']], function () {
	Route::apiResource('user', 'API\UserController');
}
So, We have created a group route which means any route under the group route will be effected whatever the properties of middleware’s are applied on the group route for example, in this group route you can see that we have added a middleware ‘auth:api’ which means any that person will be able to access that route who have a valid access_token otherwise you will get the error of unauthorized request.
So this is it for today, hopefully you have learn how to create API’s using laravel framework with various methods and authentication of API’s using Laravel Passport package in this tutorial for further tutorials stay tuned. If you want to integrate APIs into your Laravel app, you can discuss with us below.