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
Apply the decorator
@app.route(‘/endpoint/’, methods=[‘GET’])
@limits(calls=1, period=1) #max 1 call per second
def respond():
#API code
If the limit is exceeded, the following exception will be raised.
raise RateLimitException(‘too many calls’, period_remaining)
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 .
Top comments (4)
pip install? It would be almost
import antigravity
.For requests, or Flask?
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?
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
What library is that?