Courses

How to Build Laravel 12 API From Scratch

Rate Limit: Maximum Requests per Minute

You're reading a FREE PREVIEW of a PREMIUM course.
Summary of this lesson:
- Implementing API rate limiting/throttling
- Configuring request limits per minute
- Custom rate limiting based on user roles

Video Version of the Lesson

[Only for premium members]

Let's talk about a feature called Rate Limiting, or in other words, called Throttling. What happens if the API is called too many times per minute or hour? Then the user receives an error with the message Too Many Attempts. and 429 Too Many Requests HTTP status.


First, we must enable the API throttling for the Middleware.

bootstrap/app.php:

return Application::configure(basePath: dirname(__DIR__))
->withProviders()
->withRouting(
web: __DIR__.'/../routes/web.php',
api: __DIR__.'/../routes/api.php',
commands: __DIR__.'/../routes/console.php',
health: '/up',
apiPrefix: 'api/v1',
)
->withMiddleware(function (Middleware $middleware) {
$middleware
->statefulApi()
->withThrottledApi();
})
->withExceptions(function (Exceptions $exceptions) {
//
})->create();

Next, we can configure the rate limiter in the AppServiceProvider boot method. For example, we can limit the whole API to six requests per minute.

app/Providers/AppServiceProvider.php:

use Illuminate\Http\Request;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Support\Facades\RateLimiter;
 
class AppServiceProvider extends ServiceProvider
{
// ...
 
public function boot(): void
{
RateLimiter::for('api', function (Request $request) {
return Limit::perMinute(6)->by($request->user()?->id ?: $request->ip());
});
}
}

If you need to set different rate limiters on some routes, this can be done using...

The full lesson is only for Premium Members.
Want to access all 28 video+text lessons of this course? (1 h 21 min)

You also get:

  • 83 courses
  • Premium tutorials
  • Access to repositories
  • Private Discord