Introduction
APIs are the backbone of modern applications, powering SPAs, mobile apps, and integrations with external services. Laravel is not just a great web framework – it’s also one of the most developer-friendly ways to build APIs.
In this post, we’ll walk through how Laravel handles API development, from setting up routes and controllers to using authentication and JSON resources.
1. Setting Up API Routes
Laravel provides a dedicated routes/api.php file. Unlike web.php, routes defined here are stateless and automatically assigned the api middleware group.
// routes/api.php
use App\Http\Controllers\Api\PostController;
Route::apiResource('posts', PostController::class);
2. Using Resource Controllers
Resource controllers give you RESTful endpoints instantly:
php artisan make:controller Api/PostController --api
This generates methods like index, show, store, update, and destroy, covering standard CRUD operations.
3. API Authentication Options
Laravel offers two robust ways to secure APIs:
- Sanctum – Lightweight token-based auth, perfect for SPAs and mobile apps.
- Passport – Full OAuth2 server implementation, great for large-scale enterprise apps.
4. Eloquent API Resources
Instead of returning raw models, Laravel lets you transform responses with API Resource classes:
// app/Http/Resources/PostResource.php
class PostResource extends JsonResource {
public function toArray($request) {
return [
'id' => $this->id,
'title' => $this->title,
'author' => $this->user->name,
'published_at' => $this->created_at->toDateString(),
];
}
}
Then in your controller:
return new PostResource($post);
This ensures consistent, secure, and maintainable JSON structures.
5. Best Practices
- Keep API logic separate from web controllers.
- Use versioning (
/api/v1/posts) to future-proof your API. - Document your endpoints with tools like Laravel OpenAPI or Swagger.
Conclusion
Laravel makes API development fast, scalable, and elegant. With built-in routing, controllers, Sanctum/Passport, and JSON resources, you can ship production-ready APIs in record time.

Leave a Reply