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.

  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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.

API endpoints for the unauthenticated route

Related to category:

  • Get all posts of a category GET /categories/{id}/posts
  • Get a post by ID GET /posts/{id}
  • Get all comments on a post GET /posts/{id}/comments
  • Get all posts by an author GET /authors/posts
  • Get all comments by an author GET /authors/{id}/comments
  • Login the userPOST /login
  • Forgot password POST /forgot-password

API endpoint for the authenticated route

Related to comment:

  • Update password POST /update-password
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"
];
}
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);
}
<?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

categories
categories
RESTful API Returning Response
tinker
tinker
Generate access token
  • 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
Authorization Type — Bearer Token
accept
accept
Header — Accept — application/json
Body — form-data
comment response
comment response
Success Response after comment insert

Software Developer @ mditech.net