0

I want to use slowapi on a fastapi python app, for implementing RateLimiter. However, The definitions of the endpoints use a data model for parameters (inheriting from BaseModel) rather than a request, as the documentation of slowapi require. here is a sample endpoint from the code:

@app.post("/process_user")
def process_user(
    params: NewUser,
    pwd: str = Depends(authenticate),
):

where NewUser is the data model

class NewUser(BaseModel):
   ...

How can I add a slowapi rate limiter with minimum change of the design of the code?

Thanks.

amit
  • 3,332
  • 6
  • 24
  • 32

1 Answers1

1

You need to pass a Starlette request with your Pydantic model. For example...

from fastapi import FastAPI
from pydantic import BaseModel
from slowapi import Limiter
from slowapi.util import get_remote_address
from starlette.requests import Request


limiter = Limiter(key_func=get_remote_address)
app = FastAPI()
app.state.limiter = limiter


class NewUser(BaseModel):
   ...


@app.post("/process_user")
@limiter.limit("1/second")
def process_user(
    params: NewUser,
    pwd: str = Depends(authenticate),
    request: Request
):
nlinc1905
  • 11
  • 1