How to create a custom middleware in Laravel for handling API throttling



Image not found!!

In Laravel, middleware provides a convenient mechanism for filtering HTTP requests entering your application. You can create custom middleware to handle API throttling based on your specific requirements. Here's a step-by-step guide on how to create a custom middleware for API throttling in Laravel.

Let's assume you want to throttle API requests based on the number of requests per minute and that you have an ApiThrottle middleware to handle this.

  1. 1. Create the Middleware:

    Run the following Artisan command to generate a new middleware:

    bash
    php artisan make:middleware ApiThrottle

    This will create a new file at app/Http/Middleware/ApiThrottle.php.


  2. 2. Edit the Middleware:

    Open the app/Http/Middleware/ApiThrottle.php file and update its contents:

    php
    <?php namespace App\Http\Middleware; use Closure; use Illuminate\Cache\RateLimiter; use Symfony\Component\HttpFoundation\Response; class ApiThrottle { protected $limiter; public function __construct(RateLimiter $limiter) { $this->limiter = $limiter; } public function handle($request, Closure $next, $key = 'default', $maxAttempts = 60, $decayMinutes = 1) { if ($this->limiter->tooManyAttempts($key, $maxAttempts)) { return response()->json(['message' => 'Too Many Attempts. Please try again later.'], Response::HTTP_TOO_MANY_REQUESTS); } $this->limiter->hit($key, $decayMinutes); $response = $next($request); return $this->addHeaders( $response, $maxAttempts, $this->calculateRemainingAttempts($key, $maxAttempts), $this->limiter->availableIn($key) ); } protected function addHeaders($response, $maxAttempts, $remainingAttempts, $retryAfter) { return $response ->header('X-RateLimit-Limit', $maxAttempts) ->header('X-RateLimit-Remaining', $remainingAttempts) ->header('X-RateLimit-Reset', $retryAfter); } protected function calculateRemainingAttempts($key, $maxAttempts) { return max(0, $maxAttempts - $this->limiter->attempts($key)); } }

    This middleware uses Laravel's RateLimiter to handle throttling. It checks if there are too many attempts and, if so, returns a response with a 429 Too Many Requests status code.


  3. 3. Register the Middleware:

    Open app/Http/Kernel.php and add your middleware to the $routeMiddleware array:

    php
    protected $routeMiddleware = [ // ... 'api.throttle' => \App\Http\Middleware\ApiThrottle::class, ];

  4. 4. Apply the Middleware to Routes or Route Groups:

    You can apply the middleware to specific routes or route groups in your routes/api.php file or wherever your API routes are defined:

    php
    Route::middleware('api.throttle')->group(function () { // Your API routes here });

    This will apply the ApiThrottle middleware to all routes within the group.


  5. 5. Configure Throttle Parameters:

    You can customize the parameters like $maxAttempts and $decayMinutes when applying the middleware:

    php
    Route::middleware('api.throttle:custom-key,60,1')->group(function () { // Your API routes here });

    This example sets the throttle key to 'custom-key', allows 60 attempts per minute, and has a decay period of 1 minute.

Remember to adjust the parameters and logic according to your specific requirements. This example provides a basic setup for API throttling using Laravel middleware.



=== Happy Coding :)