Laravel REST API Development
Introduction
Laravel makes building RESTful APIs straightforward with its routing system, resource controllers, and middleware. Whether you're building a mobile app backend, a microservices architecture, or integrating with third-party services, Laravel provides the tools you need.
In this guide, we'll explore Laravel REST API development, covering routing, controllers, request handling, and best practices for building production-ready APIs.
REST API Basics
REST (Representational State Transfer) APIs use standard HTTP methods:
- GET - Retrieve resources
- POST - Create new resources
- PUT/PATCH - Update existing resources
- DELETE - Remove resources
RESTful APIs should be stateless, use standard HTTP status codes, and return JSON responses.
API Routing
Define API routes in routes/api.php:
use App\Http\Controllers\Api\ProductController;
Route::apiResource('products', ProductController::class);
Route::get('/products/{product}/availability',
[ProductController::class, 'availability']);
Route::post('/products/{product}/stock',
[ProductController::class, 'updateStock'])
->middleware('auth:sanctum');
Group routes with common middleware:
Route::middleware('auth:sanctum')->group(function () {
Route::apiResource('orders', OrderController::class);
Route::get('/user', function (Request $request) {
return $request->user();
});
});
Controllers and Resources
Use API resources for consistent response formatting:
php artisan make:resource ProductResource
php artisan make:resource ProductCollection
Configure the resource:
class ProductResource extends JsonResource
{
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'price' => $this->price,
'category' => $this->category->name,
'created_at' => $this->created_at->toDateTimeString(),
];
}
}
Use the resource in your controller:
public function index()
{
$products = Product::with('category')->paginate();
return ProductResource::collection($products);
}
Error Handling
Implement consistent error handling:
public function store(Request $request)
{
$validated = $request->validate([
'name' => 'required|string|max:255',
'price' => 'required|numeric|min:0',
]);
$product = Product::create($validated);
return (new ProductResource($product))
->response()
->setStatusCode(201);
}
Create custom exception handler responses:
public function render($request, Throwable $e)
{
if ($request->expectsJson()) {
return response()->json([
'error' => $e->getMessage(),
'type' => get_class($e),
], $this->getStatusCode($e));
}
return parent::render($request, $e);
}
Best Practices
- Use API resources - Transform data consistently
- Implement pagination - Handle large datasets
- Version your API - Maintain backward compatibility
- Use rate limiting - Protect against abuse
- Log requests - Maintain audit trails
- Document endpoints - Use OpenAPI/Swagger
- Test thoroughly - Write comprehensive tests
Summary
Laravel provides excellent support for building RESTful APIs. By following these patterns and best practices, you can create robust, scalable APIs that meet modern development requirements.
For more information, check out our other tutorials on Enterprise APIs and Unit Testing.