[Python] How to apply a global rate limit for all routes using SlowAPI and FastAPI?

Discussão em 'Python' iniciado por Stack, Março 14, 2025.

  1. Stack

    Stack Membro Participativo

    I want to configure Rate Limiting with SlowAPI (in-memory without Redis Cache etc.), but I don't want to add the @limiter.limit() decorator seperately for every endpoint. So something I don't want to do manually would be:

    @limiter.limit("5/minute")
    async def myendpoint(request: Request)
    pass


    So essentially, I want to include it to a middleware:

    from slowapi import Limiter

    limiter = Limiter(key_func=get_remote_address)

    @app.middleware("http")
    async def check_request(request: Request, call_next):
    client_ip = request.client.host
    prefix = "request_rate_limiter." + client_ip

    #... (logic from slowapi to get allowed flag)
    if allowed:
    response = await call_next(request)
    return response



    But I didn't find a solution how to receive a boolean from the limiter

    How would I proceed from this and does this work?

    It would be great if I could configure it for different routes and also for example depending on a user subscription (e.g. free/premium).

    Thanks!

    Continue reading...

Compartilhe esta Página