'using slowapi with a datamodel instead of request as parameter

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.



Solution 1:[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
):

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 nlinc1905