Middleware sits between the routes of an API router and acts as a layer where it can execute code before and after a request is handled. In this article we will explore two key use cases for middleware in FastAPI, demonstrating both as works and because It is useful. Let's code!
To get started, let's create a simple API to serve as the basis for our middleware examples. The following application has only one route: test
which simulates the real job by sleeping for a few milliseconds before returning “OK”.
import random
import timefrom fastapi import FastAPI
app = FastAPI(title="My API")
@app.get('/test')
def test_route() -> str:
sleep_seconds:float = random.randrange(10, 100) / 100
time.sleep(sleep_seconds)
return "OK"
What is middleware?
The middleware acts as a filter between the incoming HTTP request and the processing performed by your application. Think of it like airport security: each passenger must go through security before and after boarding the plane. Similarly, every API request goes through the middleware: both before being handled…