Middleware sits between an API router its routes, appearing as a layer the place you’ll be able to run code earlier than and after a request is dealt with. On this article we’ll discover two key use circumstances of middleware in FastAPI, demonstrating each how it really works and why it’s helpful. Let’s code!
To start, let’s create a easy API that serves as a base for our middleware examples. The app under has just one route: check
which simulates precise work by sleeping for just a few milliseconds earlier than returning “OK”.
import random
import timefrom fastapi import FastAPI
app = FastAPI(title="My API")
@app.get('/check')
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 carried out by your utility. Consider it like airport safety: each passenger should undergo safety earlier than and after boarding the aircraft. Equally, each API request passes by means of middleware: each earlier than being dealt with…