intermediate
Step 8 of 15
API Development
Laravel Framework
API Development
Laravel excels at building RESTful APIs with its API resource controllers, JSON responses, API resource transformations, rate limiting, and authentication via Sanctum (token-based). API development in Laravel follows RESTful conventions while providing powerful tools for transforming data, handling pagination, and implementing authentication. Laravel's API features make it easy to build backends for mobile apps, single-page applications, and third-party integrations.
API Resources
<?php
// php artisan make:resource PostResource
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class PostResource extends JsonResource
{
public function toArray($request): array
{
return [
'id' => $this->id,
'title' => $this->title,
'excerpt' => str()->limit($this->body, 150),
'category' => $this->category,
'author' => [
'id' => $this->user->id,
'name' => $this->user->name,
],
'comments_count' => $this->whenCounted('comments'),
'created_at' => $this->created_at->toISOString(),
];
}
}
// API Controller
class PostController extends Controller
{
public function index()
{
$posts = Post::with('user')
->withCount('comments')
->published()
->paginate(20);
return PostResource::collection($posts);
}
public function store(Request $request)
{
$validated = $request->validate([
'title' => 'required|string|max:255',
'body' => 'required|string',
]);
$post = $request->user()->posts()->create($validated);
return new PostResource($post);
}
}
// routes/api.php
Route::middleware('auth:sanctum')->group(function () {
Route::apiResource('posts', PostController::class);
});
Pro tip: API Resources separate your database schema from your API response format. This means you can change your database structure without breaking API clients. Always version your API endpoints (/api/v1/posts) and use pagination for list endpoints.
Key Takeaways
- API Resources transform models into JSON responses, decoupling database schema from API format.
- Use
Route::apiResource()for CRUD API routes (excludes HTML form routes). - Laravel Sanctum provides simple token-based authentication for SPAs and mobile apps.
- Always paginate list endpoints and include pagination metadata in responses.
- Use form request validation for clean, reusable input validation in API controllers.