This topic is locked

REST API - How to implement rate limiting

9/2/2020 10:11:48 AM
PHPRunner Tips and Tricks
Myr0n author

In this example, will gonna suppose that we already has been set the API function in our project and already have a business logic to maintenance the quota for rate limit, like a process to initialize the quota every month or send an email when the rate limit quota for a user is been gone, stuff like that.
Step 1:

We need to add 2 fields in our table users, ratelimit& ratelimitquotatype int default 0
Step 2:

We need to increment and check the ratelimitquotavs ratelimitin AfterSuccessfulLoginusing the next code.



if (inRestApi()) {

//Updating the quota for this user.

$UpdatedData = array();

$UpdatedData["ratelimitquota"] = $data["ratelimitquota"] + 1;

DB::Update("users", $UpdatedData, "username = '" . $username . "'" );

//

if ( $UpdatedData["ratelimitquota"] > $data["ratelimit"] ) //Verifying the quoteavs their rate limit

{

API::sendError( 'Too many requests', 429 );

}

}


Step 3:

Test your api in a browser, add a rate limit to a test user



http://localhost/test/api/v1.php?table=users&action=list


I hope this help to anyone.