slowapi icon indicating copy to clipboard operation
slowapi copied to clipboard

Update fastapi snippet so it can work from copy paste

Open swartchris8 opened this issue 2 years ago • 2 comments

Hello, This project is awesome thanks for all the work could the docs for fastapi be updated to this:

from fastapi import FastAPI, Request, Response
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 "test"

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

The current snippet misses the Request and Response import and I can't find a text response in fastapi

The above edited snippet will work when copy pasted!

swartchris8 avatar Apr 19 '22 15:04 swartchris8

Hi @swartchris8 thanks for providing this code sample (and the kind words)! Just to make sure I've got the right context, can you confirm which version of fastapi you're running this with?

laurentS avatar Apr 20 '22 12:04 laurentS

I am on fastapi==0.67.0

swartchris8 avatar Apr 22 '22 10:04 swartchris8