Introduction
Building a RESTful API in Laravel is a common backend task, especially when developing applications that serve frontend frameworks like React or Vue. In this Laravel REST API tutorial, we'll walk through structuring your routes using api.php, formatting JSON responses with API Resources, authenticating requests using Laravel Sanctum, and ensuring your API returns standardized HTTP status codes.
1. Structuring Routes Using api.php
Laravel provides a dedicated routes/api.php file for defining API routes. This file automatically applies the api middleware group, which is optimized for stateless APIs.
// routes/api.php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
Route::middleware('auth:sanctum')->group(function () {
Route::get('/user', function (Request $request) {
return $request->user();
});
Route::apiResource('posts', 'App\Http\Controllers\PostController');
});
// Public route
Route::post('/login', 'App\Http\Controllers\AuthController@login');
This structure keeps your API routes clean and applies authentication middleware where necessary.
Pro-Tip:
Use route versioning like Route::prefix('v1')->group(...) to maintain backward compatibility as your API evolves.
2. Using API Resources to Format JSON Responses
Laravel's API Resources simplify transforming your models into JSON responses, ensuring consistency and control over the output.
// Generate resource
php artisan make:resource PostResource
// In app/Http/Resources/PostResource.php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class PostResource extends JsonResource
{
public function toArray($request)
{
return [
'id' => $this->id,
'title' => $this->title,
'content' => $this->content,
'author' => $this->user->name,
'created_at' => $this->created_at->toIso8601String(),
];
}
}
// In controller
use App\Http\Resources\PostResource;
public function show($id)
{
$post = Post::findOrFail($id);
return new PostResource($post);
}
This approach cleanly separates presentation logic from your controllers and models.
Pro-Tip:
Combine resources with whenLoaded() to conditionally include relationships only when eager loaded, reducing unnecessary data transfer.
3. Authentication with Laravel Sanctum
Laravel Sanctum offers a lightweight, SPA-friendly authentication system for your API. Here's how to integrate it:
// Install Sanctum
composer require laravel/sanctum
// Publish Sanctum config
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
// Run migrations
php artisan migrate
// Add Sanctum middleware in app/Http/Kernel.php
'api' => [
\Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
'throttle:api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
// In AuthController
use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
public function login(Request $request)
{
$credentials = $request->validate([
'email' => 'required|email',
'password' => 'required',
]);
$user = User::where('email', $credentials['email'])->first();
if (! $user || ! Hash::check($credentials['password'], $user->password)) {
return response()->json(['message' => 'Invalid credentials'], 401);
}
$token = $user->createToken('api-token')->plainTextToken;
return response()->json(['token' => $token], 200);
}
After login, protect your routes with auth:sanctum middleware to require valid tokens.
Pro-Tip:
Use token abilities/scopes to limit what API tokens can do — this enhances security for third-party integrations.
4. Standardizing HTTP Status Codes
Consistent HTTP status codes improve API client reliability and debugging. Here's how to apply them:
200 OK— Successful GET, PUT, or DELETE requests.201 Created— Successful POST requests creating new resources.404 Not Found— When a resource is not found.
// Example in controller
public function store(Request $request)
{
$post = Post::create($request->all());
return (new PostResource($post))
->response()
->setStatusCode(201); // 201 Created
}
public function show($id)
{
$post = Post::find($id);
if (! $post) {
return response()->json(['message' => 'Post not found'], 404);
}
return new PostResource($post); // Defaults to 200 OK
}
Pro-Tip:
Use Laravel’s built-in abort() helper to throw HTTP exceptions with custom messages and status codes for cleaner controller code.
Conclusion
Following this Laravel REST API tutorial equips you with the foundational knowledge to build scalable and maintainable APIs. By structuring your routes in api.php, leveraging API Resources for JSON transformation, securing your API with Sanctum, and standardizing your HTTP status codes, you create a professional API backend ideal for React, Vue, or any frontend framework.
Keep evolving your API by adding versioning and enhancing authentication scopes as your application grows.
No comments yet. Be the first to comment!