[ad_1]
Supercharge Your FastAPI with Middleware: Sensible Use Instances and Examples
Middleware sits between an API router its routes, performing 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 the way it 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 beneath has just one route: take a look at which simulates precise work by sleeping for a number of milliseconds earlier than returning “OK”.
import randomimport time
from fastapi import FastAPIapp = FastAPI(title=”My API”)
@app.get(‘/take a look at’)def test_route() -> str:sleep_seconds:float = random.randrange(10, 100) / 100time.sleep(sleep_seconds)return “OK”
What’s middleware?
Middleware acts as a filter between the incoming HTTP request and the processing executed by your utility. Consider it like airport safety: each passenger should undergo safety earlier than and after boarding the airplane. Equally, each API request passes via middleware: each earlier than being dealt with…
[ad_2]
Source link


