Creating and Consuming RESTful API in Laravel

RESTful API
RESTful API

What is API?

An API — Application Programming Interface, is a computing interface that defines interactions between multiple software intermediaries. It is a way to programmatically interact with a separate software component or resource.

What is REST?

REST is an acronym for REpresentational State Transfer. This term was coined by Roy Fielding in 2000. It is an architecture style for designing loosely coupled applications over HTTP, that is often used in the development of web services.

REST defines 6 architectural constraints that make any web service a true RESTful API.

  1. Client-server — By separating the user interface from the data storage, we improve the portability of the user interface across multiple platforms and improve scalability by simplifying the server components.

Now let's jump into creating and consuming RESTful API in Laravel. I would recommend to read and implement Migration and data seeding & Creating Relationships before you dive into this tutorial.

Consumers of our API will be able to perform a few limited tasks. There would be the following endpoints:

API endpoints for the unauthenticated route

Related to category:

  • Get all categories GET /categories

Related to the post:

  • Get all posts GET /posts

Related to the author:

  • Get details of an author GET /authors/{id}

Related to the tag:

  • Get all posts of a tag GET /tags/{id}/posts

Related to auth:

  • Register a userPOST /register

API endpoint for the authenticated route

Related to comment:

  • Store user comment POST /comments/posts/{id}

Related to auth:

  • Logout the userPOST /logout

Check the details of the above API collection from https://documenter.getpostman.com/view/8942795/TVmJhJv2.

You have to create API Resources, Controllers, and API Routes for the above-mentioned API endpoints.

Step 1: Let's first create API Resources. To do so follow the below-mentioned steps (don’t forget to implement the Migration and Relationship part):

When building an API, you may need a transformation layer that sits between your Eloquent models and the JSON responses that are actually returned to your application’s users. Laravel’s resource classes allow you to expressively and easily transform your models and model collections into JSON.

Run the command php artisan make:resource CategoryResource. It will create CategoryResource in app\Http\Resources directory.

Open this file and return the desired data, eg. category_id in place of id. You can do a lot more than just masking the field names or number of fields to be returned like- we can return additional information with API, etc.

public function toArray($request)
{
return [
'category_id' => $this->id,
'category_title' => $this->title,
'category_color' => $this->color,
];
}
// (Optional) Additional code is attached to the response
public function with($request){
return [
'version' => "1.0.0",
'author_url' => "https://mditech.net"
];
}

The same way you have to create other required resources — CommentResource, PostResource, TagResource, UserResource, ImageResource, and VideoResource. Create these resources or check them out from the repository.

Step 2: The next activity is to create the required controllers. To do so follow the below steps:

Run the command php artisan make:controller Api\\CategoryApiController. It will create CategoryApiController in theapp\Http\Controllers\Api directory. Open that file and write the methods to perform actions.

public function index()
{
$categories = Category::all();
return CategoryResource::collection($categories);
}
public function posts($id)
{
$posts = Post::where('category_id', $id)->orderBy('id', 'desc')->paginate();
return PostResource::collection($posts);
}

Here you created two methods index and posts inside CategoryApiController.

The index method will return all the categories wrapped inside CategoryResource.

The posts method will return all the posts belonging to a specific category wrapped inside PostResource.

The same way create the desired methods in CommentApiController, PostApiController, TagApiController, and UserApiController or checkout repository.

Step 3: The last step is to create routes for the API. Proceed to the routes directory and open the api.php file and create the API endpoints that will reference the methods created in CategoryApiController, CommentApiController, PostApiController, TagApiController, and UserApiController.

<?php
use App\Http\Controllers\Api\CategoryApiController;
use App\Http\Controllers\Api\CommentApiController;
use App\Http\Controllers\Api\PostApiController;
use App\Http\Controllers\Api\TagApiController;
use App\Http\Controllers\Api\UserApiController;
use Illuminate\Support\Facades\Route;
Route::post('registration', [UserApiController::class, 'store']);
Route::post('login', [UserApiController::class, 'login']);
Route::post('forgot-password', [UserApiController::class, 'forgotPassword']);
Route::get('authors/{id}', [UserApiController::class, 'show']);
Route::get('authors/{id}/posts', [UserApiController::class, 'posts']);
Route::get('authors/{id}/comments', [UserApiController::class, 'comments']);
Route::get('categories', [CategoryApiController::class, 'index']);
Route::get('categories/{id}/posts', [CategoryApiController::class, 'posts']);
Route::get('posts', [PostApiController::class, 'index']);
Route::get('posts/{id}', [PostApiController::class, 'show']);
Route::get('posts/{id}/comments', [PostApiController::class, 'comments']);
Route::get('tags/{id}/posts', [TagApiController::class, 'posts']);Route::middleware('auth:sanctum')->group(function () {
Route::post('comments/posts', [CommentApiController::class, 'store']);
Route::post('logout', [UserApiController::class, 'logout']);
Route::post('update-password',[UserApiController::class, 'updatePassword']);
});

Testing the API endpoints

Start the database and run php artisan serve command. Laravel development server will start on http://127.0.0.1:8000

Open Postman and test all routes defined in api.php, but make sure to append your route with /api/

To get all categories you should send a GET request to http://127.0.0.1:8000/api/categories

categories
categories
RESTful API Returning Response

Now lets test authenticated route as well. There is only one authenticated route for storing comment of logged in user on a post.

We are using Laravel Sanctum for authentication and authorization. We will issue an API token and use that in Postman to authenticate the request.

Laravel Sanctum provides a featherweight authentication system for SPAs (single page applications), mobile applications, and simple, token based APIs. Sanctum allows each user of your application to generate multiple API tokens for their account. These tokens may be granted abilities / scopes which specify which actions the tokens are allowed to perform.

To issuse an API token we will run tinker command

php artisan tinker

It will now allow us to interact with the Laravel application from the command line. Here you need to create an API token for a user using createToken() method.

tinker
tinker
Generate access token

Copy plainTextToken, to be used in Postman.

Now open Postman and do the following:

  • New POST request to http://127.0.0.1:8000/api/comments/posts
authorization
authorization
Authorization Type — Bearer Token
accept
accept
Header — Accept — application/json
Body — form-data
comment response
comment response
Success Response after comment insert

In this article, we have been able to build and consume (Consumer was Postman)RESTful API using Laravel. We covered the API Resource creation, API Controller creation, and tested Authenticated and Non-Authenticated API Routes.

The source code is available at https://github.com/mdutt247/laravel-news for you to refer to.

Read the previous part, Creating Relationships of this tutorial.

Read the next part, Creating the Front End for Admin user.

Connect: Twitter, GitHub, Linkedin, MDITech

You can support by buying a coffee ☕️ here https://www.buymeacoffee.com/mdutt

Software Developer @ mditech.net

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store