Understanding When and The best way to Implement FastAPI Middleware (Examples and Use Circumstances) | by Mike Huls | Dec, 2024
Middleware sits between an API router its routes, performing as a layer the place you may 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: take a look at
which simulates precise work by sleeping for a couple of milliseconds earlier than returning “OK”.
import random
import timefrom fastapi import FastAPI
app = FastAPI(title="My API")
@app.get('/take a look at')
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 performed by your software. Consider it like airport safety: each passenger should undergo safety earlier than and after boarding the airplane. Equally, each API request passes by way of middleware: each earlier than being dealt with…