Throttling API requests in Laravel

Occasionally it's  required that a user is not allowed to hit an API endpoint multiple times. For example a route that delivers a big amount of content, i.e an articles api route, could be taken advantage of, by concurrently sending GET requests to it and increasing workload on the server, thus achieving an effect similar to a DoS attack.  

For that reason, laravel offers the throttling middleware. It can be used as it is, out of the box, or you can add your own throttling middleware.

You can apply throttling to a group of routes like so:

Route::group(['prefix' => 'api', 'middleware' => 'throttle'], function () {
    Route::get('people', function () {
        return Person::all();
    });
});

This will throttle the API requests according to the presets in your Kernel.php:

 'api' => [
    'throttle:60,1',
    'bindings',
],

If you would like to set your own throttling, you can achieve that by using the following notation:

Route::group(['prefix' => 'api', 'middleware' => 'throttle:5,10'], function () {
    Route::get('people', function () {
        return Person::all();
    });
});

The code above sets the throttling to 5 requests per 10 minutes. 

Things to be noted:

The custom throttling limit  you will set has to be less than the limit set in Kernel.php. If that is not the case then you can increase the limit in your kernel file to allow for more requests and then set smaller limits to the API routes that require it.

Your Cache driver set in your env file can be anything but array. This is because the throttling function uses the cache to store the key of the user that makes the request, so that it can recognise that concurrent requests are coming from the same user.