slowapi icon indicating copy to clipboard operation
slowapi copied to clipboard

Can global limits make this in FastAPI?

Open stilleshan opened this issue 2 years ago • 4 comments

If I set the global limit to "10/minute" with default_limits, can some API endpoints receive the global limit even if they don't have a limit decorator, while other endpoints with limit decorators receive the limits set by the decorators?

Here's an example: I want to limit access to the /test endpoint to 3 times, and then limit access to both the / and /home endpoints to a total of 7 times. I don't want to add decorators to / and /home separately.

limiter = Limiter(key_func=get_remote_address, default_limits=["10/minute"])
app.state.limiter = limiter
app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)
app.add_middleware(SlowAPIMiddleware)

@app.get("/")
async def root_page(request: Request):
    return 'root'

@app.get("/home")
async def homepage(request: Request):
    return 'home'

@app.get("/test")
@limiter.limit("3/minute")
async def test(request: Request):
    return 'test'

stilleshan avatar Mar 03 '23 04:03 stilleshan

Hi @stilleshan yes, this should work. See this example in the docs. If your code above does not work, then I believe you've found a bug.

laurentS avatar Mar 06 '23 12:03 laurentS

Hi! just stumbled accross this issue. I tried to create default limits for all routes without the decorator like this

limiter = Limiter(key_func=get_remote_address, default_limits=["5/minute"], storage_uri="mongodb://localhost:27017", strategy="moving-window")

But it seems to not work. The mongodb storrage seems not to be the issue, because adding the @limiter.limit("5/minute") decorator directly to a route works. Can it be that default_limits is bugged?

Snawe avatar May 04 '24 08:05 Snawe

Hi @Snawe yes, it could be a bug in the middleware. But can you check a few points first?

  • did you setup the middleware like in this example? The default limits won't work without it
  • if so, does the global limit work when you remove the various kwargs in your call to Limiter ('storage_uri, strategy)? if it is a bug, this would help isolate under which conditions it appears.
  • if you're still seeing the issue, then can you share more details about your setup, starlette or fastapi, version numbers, and a minimal code sample that reproduces the issue?

Please let us know if any of the above fixes your problem. It might be worth adjusting the docs if they're unclear (or fixing the bug, if indeed you found one!).

laurentS avatar May 06 '24 07:05 laurentS

Hi @laurentS ! Thanks for your reply and sorry for my very late response. It was actually me. I commented out the line to add the middleware during some testing. everything works fine! Thanks.

Snawe avatar Jun 09 '24 15:06 Snawe