API Throttle Using Laravel 7

This tutorial help to implement API throttle in Laravel 7.This help to prevent mass usage of API as well as DoS attack.You can block the malicious API user after implementing throttle middleware into laravel api.

The Laravel has built-in rate limiting which limits the actions/responses per minute. You can change the API wrapper for the use of Throttling Middleware.

The Laravel providing below class of throttle middleware-
throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,

Laravel comes with web and api middleware groups that contain common middleware you may want to apply to your web UI and API routes:

How To Apply Throttle into All APIs Endpoints

You can apply global throttle configuration that ll call on each api request.The below throttle configuration limit the api access for 60 call in 1 min, You can add this configuration into routes/api.php file.

protected $middlewareGroups = [
'api' => [
'throttle:60,1',
....
],

 

The Above will cap requests made by an IP to 60 every minute. When the user exceed the requests and limit hits the API from the same IP, the following response will be returned:

Response Message – Too Many Attempts
Http Status Code – 429

How To Apply Throttle On Group API

You Can also apply middleware into the particular group API, You just need to pass limit parameter into api middleware –

Route::group(['prefix' => 'api', 'middleware' => 'throttle:3,10'], function () {
...
});

How To Use Throttle on A single API call

You can also apply different throttle limit on each request, You just bind middle-ware on each requests –

Route::get('/employees','EmployeeController@getEmployees')->middleware("throttle:10,2");

Leave a Reply

Your email address will not be published. Required fields are marked *