DEV Community

Paymon Wang Lotfi
Paymon Wang Lotfi

Posted on • Updated on

The Easiest Way to Rate-Limit a Python API

It is considered good practice to rate limit an API to allow for a better flow of data and to increase security by mitigating attacks such as DDoS. Rate limiting will restrict the number of requests that can be made from a unique IP address during a designated period of time.

Import the library

from ratelimit import limits
Enter fullscreen mode Exit fullscreen mode

Apply the decorator

@app.route(/endpoint/, methods=[GET])
@limits(calls=1, period=1) #max 1 call per second
def respond():
    #API code
Enter fullscreen mode Exit fullscreen mode

If the limit is exceeded, the following exception will be raised.

raise RateLimitException(too many calls, period_remaining)
Enter fullscreen mode Exit fullscreen mode

And that’s all. Just as developers are taught to code around SQL injections, rate limiting is another necessary measure that should be implemented with any API .

Discussion (4)

Collapse
patarapolw profile image
Pacharapol Withayasakpunt

pip install? It would be almost import antigravity.

For requests, or Flask?

Collapse
hextrace profile image
hextrace

Hi, thx

I have some questions

What's a better flow of data? Requests are queued if limit is hit, can we configure a timeout? Is rate based on request emits or response receives?

Collapse
paymon123 profile image
Paymon Wang Lotfi Author

This is all configurable with the ratelimit API, this post is just showing how easy it is to get started. In this situation it is IP address

Collapse
jonr profile image
Jón Ragnarsson

What library is that?