Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel - Rate Limiting specific API routes

Tags:

php

laravel

api

I'm currently working on a Laravel-driven site which is powered by two separate servers, an API server and a public web server (both running Laravel).

The API has a number of routes which are used to validate availability of certain key terms, such as email address and URL slug. These routes are called via AJAX to check the database, and are triggered on keypresses.

As can be expected with the AJAX request being triggered many times a minute, the API throws a "Too many requests" error. I know this can be fixed with increasing the request limit, however I only want to do this for a two routes, not all of them.

How can I disable the rate limit on a single API route?

Here is one of the routes, it's pretty standard:

Route::post('/email/is-available', function(Request $request) {

    ...

})->middleware('my_own_api_key_checking_middleware');

Many thanks in advance!

like image 869
Ryan Avatar asked Mar 29 '19 15:03

Ryan


1 Answers

You are recieving the too many requests message because Laravel is appying the throttle middleware to all api routes by default, to disable it go to app/Http/Kernel.php and delete or comment the throttle array entry from the property $middlewareGroups, this will disable throttling for every route on the group. Now on your routes file add it to the route you want:

->middleware('throttle:240,1');

Where the first number is the limit of requests and the second one is the time.

like image 149
namelivia Avatar answered Oct 12 '22 04:10

namelivia