Middlewares
The thing that will be put between our application and limiting logic is our Middleware.
our limiting logic won't work without this piece and has no way to intercept incoming requests.
FastAPI Middlewares
you can read more about middlewares in FastAPI's documentation from here.
First of all, we have to setup our middleware, we also need some stuff from our backend library limits. we will go into more details about these later.
from fastapi import FastAPI
from limits.aio.storage import MemoryStorage
from limits.aio.strategies import FixedWindowRateLimiter
from fastlimits import RateLimitingMiddleware
# create our fastapi app
app = FastAPI()
# create our limiter object
limiter = FixedWindowRateLimiter(storage=MemoryStorage())
# add our middleware to our fastapi app
app.add_middleware(
RateLimitingMiddleware,
strategy=limiter,
)
And thats it! our setup is Done, now we can start adding limits to our endpoints.
but first, let's breakdown some parts and explain a little more.
The limits library supports multiple storage and strategies to use, we used the simples storage that is MemoryStorage and does not need anything to be installed and works out of the box.
for the strategy, we used FixedWindowRateLimiter that has the least overhead and meets the needs of most applications. but you are free to use anything that limits library supports!
sync or async
limits library supports both sync and async storage backends, but it will be best to use the async version.
so you sould import modules from limits.aio for example from limits.aio.storage import MemoryStorage.
and if you happen to use the sync version. FastAPI will handle everything as it's documented here.
More Storages
If you want to know more about different storage backends supported you can refer to limits documentation here.
More Strategies
If you want to know more about different strategies supported you can refer to limits documentation here.