Introduction
APIs are the backbone of modern web applications. In this comprehensive guide, we'll explore how to build scalable, maintainable APIs using Laravel.
Setting Up Your API
First, let's set up the foundation for our API. Laravel provides excellent tools out of the box for API development.
php artisan install:api
Authentication with Sanctum
Laravel Sanctum provides a featherweight authentication system for SPAs and simple APIs. Here's how to implement it:
<?php
namespace App\Models;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens;
protected $fillable = [
'name',
'email',
'password',
];
protected $hidden = [
'password',
'remember_token',
];
}
Creating API Resources
API Resources transform your models into JSON responses. They give you granular control over the JSON structure:
<?php
namespace App\Http\Resources;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
class UserResource extends JsonResource
{
public function toArray(Request $request): array
{
return [
'id' => $this->id,
'name' => $this->name,
'email' => $this->email,
'avatar' => $this->avatar_url,
'created_at' => $this->created_at->toISOString(),
'posts_count' => $this->whenCounted('posts'),
'posts' => PostResource::collection($this->whenLoaded('posts')),
];
}
}
Rate Limiting
Protect your API from abuse with Laravel's built-in rate limiting:
<?php
// In App\Providers\AppServiceProvider
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Support\Facades\RateLimiter;
public function boot(): void
{
RateLimiter::for('api', function (Request $request) {
return Limit::perMinute(60)->by(
$request->user()?->id ?: $request->ip()
);
});
// Custom rate limiter for sensitive endpoints
RateLimiter::for('uploads', function (Request $request) {
return Limit::perMinute(10)->by($request->user()->id);
});
}
Caching Responses
Implement response caching to dramatically improve performance for read-heavy endpoints:
<?php
namespace App\Http\Controllers\Api;
use App\Http\Resources\PostResource;
use App\Models\Post;
use Illuminate\Support\Facades\Cache;
class PostController extends Controller
{
public function index()
{
$posts = Cache::remember('posts.published', 3600, function () {
return Post::query()
->published()
->with(['author', 'category'])
->latest()
->paginate(15);
});
return PostResource::collection($posts);
}
}
Conclusion
By following these practices, you'll have a solid foundation for building scalable Laravel APIs. Remember to always validate input, use API resources for consistent responses, and implement proper error handling.