Creating and Consuming RESTful API in Laravel

Madhavendra Dutt
6 min readNov 30, 2020

--

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.
  2. Stateless — Each request from the client to the server must contain all of the information necessary to understand the request, and cannot take advantage of any stored context on the server. Session state is therefore kept entirely on the client.
  3. Cacheable — Cache constraints require that the data within a response to a request be implicitly or explicitly labeled as cacheable or non-cacheable. If a response is cacheable, then a client cache is given the right to reuse that response data for later, equivalent requests.
  4. Uniform interface — By applying the principle of generality to the component interface, the overall system architecture is simplified and the visibility of interactions is improved.
  5. Layered system — The layered system style allows an architecture to be composed of hierarchical layers by constraining component behavior such that each component cannot “see” beyond the immediate layer with which they are interacting.
  6. Code on demand (optional) — REST allows client functionality to be extended by downloading and executing code in the form of applets or scripts. This simplifies clients by reducing the number of features required to be pre-implemented.

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
  • Get all posts of a category GET /categories/{id}/posts

Related to the post:

  • Get all posts GET /posts
  • Get a post by ID GET /posts/{id}
  • Get all comments on a post GET /posts/{id}/comments

Related to the author:

  • Get details of an author GET /authors/{id}
  • Get all posts by an author GET /authors/posts
  • Get all comments by an author GET /authors/{id}/comments

Related to the tag:

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

Related to auth:

  • Register a userPOST /register
  • Login the userPOST /login
  • Forgot password POST /forgot-password

API endpoint for the authenticated route

Related to comment:

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

Related to auth:

  • Logout the userPOST /logout
  • Update password POST /update-password

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
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
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
  • In Authorization tab select Type as Bearer Token and paste the plainTextToken in Token text box.
  • Then in Headers tab Key as Accept and Value as application/json.
  • Then in Body tab select form-data radio button and in Key, Value write id159, commentTesting some comment on post 159
  • Now hit the send button and you will get back the newly created comment.
authorization
Authorization Type — Bearer Token
accept
Header — Accept — application/json
Body — form-data
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

--

--

Responses (1)