Middleware sits between an API router its routes, acting as a layer where you’ll be able to run code before and after a request is handled. In this text we’ll explore two key use cases of middleware in FastAPI, demonstrating each how it really works and why it’s useful. Let’s code!
To start, let’s create a straightforward API that serves as a base for our middleware examples. The app below has just one route: test
which simulates actual work by sleeping for a couple of 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’s middleware?
Middleware acts as a filter between the incoming HTTP request and the processing done by your application. Consider it like airport security: every passenger must undergo security before and after boarding the plane. Similarly, every API request passes through middleware: each before being handled…