How to Use API Rate Limiting in Laravel: Simple Guide
In Laravel, use the built-in
throttle middleware to limit API request rates. You can apply it in your routes/api.php file by specifying limits like throttle:60,1 which means 60 requests per minute per user or IP.Syntax
The throttle middleware syntax is throttle:attempts,minutes. Here, attempts is the max number of requests allowed, and minutes is the time window in minutes.
You can add this middleware to routes or route groups to control how many requests a user or IP can make in that time.
php
Route::middleware('throttle:60,1')->group(function () { Route::get('/user', function () { return response()->json(['message' => 'User data']); }); });
Example
This example shows how to limit API requests to 10 per minute for a route. If the limit is exceeded, Laravel returns a 429 Too Many Requests response automatically.
php
<?php use Illuminate\Support\Facades\Route; Route::middleware('throttle:10,1')->get('/api/data', function () { return response()->json(['data' => 'Here is your data']); });
Output
HTTP/1.1 200 OK
Content-Type: application/json
{"data":"Here is your data"}
// After 10 requests in 1 minute:
HTTP/1.1 429 Too Many Requests
Content-Type: application/json
{"message":"Too Many Requests."}
Common Pitfalls
- Not applying
throttlemiddleware on API routes, so no rate limiting happens. - Using the same rate limit for all users without considering authentication or IP differences.
- Forgetting to handle the 429 response gracefully on the client side.
Always test your limits and customize the middleware if needed.
php
<?php // Wrong: No throttle middleware Route::get('/api/data', function () { return response()->json(['data' => 'No limit']); }); // Right: With throttle middleware Route::middleware('throttle:5,1')->get('/api/data', function () { return response()->json(['data' => 'Limited to 5 requests per minute']); });
Quick Reference
Here is a quick cheat sheet for Laravel API rate limiting:
| Feature | Description |
|---|---|
| throttle:attempts,minutes | Limits requests to 'attempts' per 'minutes' |
| Applying middleware | Use in routes or route groups to enable rate limiting |
| 429 Response | Returned automatically when limit exceeded |
| Customizing keys | Use custom keys for user/IP based limits in advanced cases |
| Handling 429 | Client should handle 'Too Many Requests' response gracefully |
Key Takeaways
Use Laravel's built-in throttle middleware to limit API request rates easily.
Apply throttle middleware in your API routes with the format 'throttle:attempts,minutes'.
Laravel automatically returns a 429 error when the limit is exceeded.
Test your rate limits and handle 429 responses properly on the client side.
Customize rate limiting keys for more precise control if needed.