Creating and Consuming RESTful API in Laravel

RESTful API
RESTful API

What is API?

What is REST?

API endpoints for the unauthenticated route

API endpoint for the authenticated route

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

categories
categories
RESTful API Returning Response
tinker
tinker
Generate access token
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