Laravel RESTful API Tutorial | Laravel RESTful API Example | Login, Register, Logout, and CRUD API in Laravel | Laravel RESTful API Development

A Web API is like a web service which works entirely with HTTP. A RESTful API must follow the REST (REpresentational State Transfer) practices, allowing to orientate the design to the resources, provide standard responses based on the different HTTP status codes.

Methods

HTTP methods are mapped to CRUD (create, read, update and delete) actions for a resource. Although you can make slight modifications such as making the PUT method to create or update, the basic patterns are listed as follows.

HTTP GET: Get/List/Retrieve an individual resource or a collection of resources.
HTTP POST: Create a new resource or resources.
HTTP PUT: Update an existing resource or collection of resources.
HTTP PATCH: Update an existing resource or collection of resources with specified parameters like in all users data if you wanted to update the email id only you can use PATCH.
HTTP DELETE: Delete a resource or collection of resources.

Laravel is a powerful PHP framework which follows MVC coding standard. It provides beautiful support for RESTful API development. We can manage our JSON request validations, returning JSON response etc.. Laravel also provides routing feature with REST standard methods like GET, POST, PUT and DELETE.
In this article I'm going to explain how we can develop RESTful API in Laravel in a simplest way.
Here is the below code explanation in Video:

Download Full code of RESTful API in Laravel


First of all I'll create a middle ware which will validate every API request.

\App\Http\Middleware\ApiSecureKeyAuth.php

In this middle ware I'm validating weather the API request is authorized or not. I have set some secure key in .env file with the name 'API_KEY'. A developer who will consume my API will pass that secure key in the request header with key name 'apiKey'. Then I'll match that API secure key sent in header should match to the secure API key which is declared in .env file. If key matched then will move to next request else will send 'unauthorized' message in response.

So write in your .env file like:

We also need to add this middle ware into  $routeMiddleware array in kernel.php file like:

In kernel.php, Before class you also will require to use 'ApiSecureKeyAuth' Middle ware class like:

In above middle ware code I have used BaseApiController to return the unauthorized response. In BaseApiController.php, I have written all the common functions like returning response functions. Here is BaseApiController.php.

\App\Http\Controllers\BaseApiController.php

Now I wanted to create an API to register the user. So here is the route code for the register request.

\routes\api.php

So here I have created a middle ware group named as 'apikeyAuth' which will be authenticating the API request. Now we will create UserController.php for user registration which will contain the create() function.

\App\Http\Controllers\UserController.php

In UserController, I have used ServiceProvider for business logics of application like UserServiceProvider has been used for defining business logics for user functionalities.

I also have used RegisterUserRequest to writing validation rules for validating the API request parameters. You need to create a directory named as 'Requests' in Http directory and inside this directory we'll be creating all validation classes.

\App\Http\Requests\RegisterUserRequest.php

Here we are extending the BaseApiRequest class so here is the BaseApiRequest.php.

\App\Http\Requests\BaseApiRequest.php

Now I'll write the UserServiceProvider.php inside the Providers directory to write the business logic for registering user.

\App\Providers\UserServiceProvider.php

Here UserServiceProvider class has extended the BaseServiceProvider class. BaseServiceProvider class contains some common functions and properties which will be used in service providers.

\App\Providers\BaseServiceProvider.php

I also have used AppUtility class in UserServiceProvider for hashing the password. So basically I have created a helper class named as AppUtility which contains some common functions which can be used in the application.

\App\Helpers\AppUtility.php

In UserServiceProvider I also have used some models like AccessToken and User model. But for using model I will require to create the tables. I'll be creating my tables through the migrations. You can take a look over Laravel migrations here.

Laravel already provides migration for user table. I have edited user table migration according to my need like:

\database\migrations\some_timestamp_create_users_table.php

You also can crate migration class for products by following command:

\database\migrations\some_timestamp_create_products_table.php

You also can crate migration class for access tokens by following command:

\database\migrations\some_timestamp_access_tokens_table.php

After creating your migration classes you can run migrations with following command:

\App\Models\AccessToken.php

\App\Models\User.php

 

 

Now you will be able to register the user through the RESTfull API in Laravel. After registration you'll get an access token in JSON response. That access token will be used for user authentication.

Now I'll explain how you can write the Login  RESTfull API in Laravel.

You route for login will be like:

Your login function in UserController will look like:

\App\Http\Requests\LoginUserRequest.php

Here will be your UserServiceProvider code for login function.

After Login/Registration you will get the access token. This token will be used for user authentication. For example if you have products in your database and you wanted to allow CRUD operation over products only for those who has got access token after login/registration.

API consumer will have to send the access token in the header of API request. Here will be the middle ware for authenticating the access token.

\App\Http\Middleware\UserAuth.php

Now you require to add this middle ware into kernel.php $routeMiddleware array like:

In kernel.php, Before class you also will require to use 'UserAuth' Middle ware class like:

Here will be the final route for all APIs.

routes\api.php

A user who has valid access toke can access the following APIs:

  1. Logout User API
  2. Get Product listing API
  3. Update Product API
  4. Delete Product API

So final Files will look like:

\App\Http\Controllers\UserController.php

\App\Providers\UserServiceProvider.php

For products APIs:

\App\Http\Controllers\ProductController.php

\App\Http\Requests\UpdateProductRequest.php

\App\Http\Requests\DeleteProductRequest.php

\App\Providers\ProductServiceProvider.php

\App\Models\Product.php

Create a new file messages.php for writing all API messages.

\resources\lang\en\messages.php

 

Download Full code of RESTful API in Laravel

Testing:

For user registration API:

URL: http://localhost/laravel/webservice/public/api/user/create
Headers : { "apiKey":"coding4developers", "Content-Type":"application/json" }
Method : POST
Body : {
"name" : "Coding 4 Developers",
"email" : "info@coding4developers.com",
"password" : "5454asfasfafa",
"role" : 2,
"deviceId" : "sdfjgsdjfgsdf",
"deviceType" : 1,
"deviceToken" : "ajhfgahfasfaf"
}

For user login API:

URL: http://localhost/laravel/webservice/public/api/user/login
Headers : { "apiKey":"coding4developers", "Content-Type":"application/json" }
Method : POST
Body : {
"email" : "info@coding4developers.com",
"password" : "5454asfasfafa",
"deviceId" : "sdfjgsdjfgsdf",
"deviceType" : 1,
"deviceToken" : "ajhfgahfasfaf"
}

For user logout API:

URL: http://localhost/laravel/webservice/public/api/user/logout
Headers : { "apiKey":"coding4developers", "Content-Type":"application/json", "accessToken":"f0df618a279944e59615ccd5ffce2875" }
Method : POST

For get products list API:

URL: http://localhost/laravel/webservice/public/api/product/get
Headers : { "apiKey":"coding4developers", "Content-Type":"application/json", "accessToken":"f0df618a279944e59615ccd5ffce2875" }
Method : GET

Share This:

Leave a Reply

Your email address will not be published. Required fields are marked *