Rate Limit Requests in FastApi

Deepanshu tyagi
DataEngineering.py
Published in
2 min readOct 23, 2023

--

Hello, readers. In this blog, I’ll show you how to implement rate limiting in your fast api. It is quite simple. We will keep this blog brief.

Lets start,

We will be using: SlowApi

Install it as follows:

pip install slowapi

So, Basically we can do two type of rate limiting:

  1. IP based rate limiting
  2. Token or variable based

IP based rate limiting

It is the slow API’s default.

from fastapi import FastAPI
from slowapi import Limiter, _rate_limit_exceeded_handler
from slowapi.util import get_remote_address
from slowapi.errors import RateLimitExceeded

limiter = Limiter(key_func=get_remote_address)
app = FastAPI()
app.state.limiter = limiter
app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)

# Note: the route decorator must be above the limit decorator, not below it
@app.get("/home")
@limiter.limit("5/minute")
async def homepage(request: Request):
return PlainTextResponse("test")

@app.get("/mars")
@limiter.limit("5/minute")
async def homepage(request: Request, response: Response):
return {"key": "value"}

Token or variable based

If you do not want to use the default one and instead want to use your own variable in place of ip address.

from slowapi import Limiter, _rate_limit_exceeded_handler
from starlette.requests import Request
from slowapi.errors import RateLimitExceeded


def get_token(request: Request) -> str:
"""
Returns the token
"""
token = request.headers.get("Authorization")

if not authorization:
return "127.0.0.1"

return token


# Create the rate limiter
limiter = Limiter(key_func=get_token)

app = FastAPI()
app.state.limiter = limiter
app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)

# Note: the route decorator must be above the limit decorator, not below it
@app.get("/home")
@limiter.limit("5/minute")
async def homepage(request: Request):
return PlainTextResponse("test")

@app.get("/mars")
@limiter.limit("5/minute")
async def homepage(request: Request, response: Response):
return {"key": "value"}

We learned how to create rate restriction in the fast api in this blog.

Follow me for more python blog and also clap if you like it.

Please reach out via Linkedin or Github in case of any questions!

--

--