TDS Archive

An archive of data science, data analytics, data engineering, machine learning, and artificial intelligence writing from the former Towards Data Science Medium publication.

Member-only story

Understanding When and How to Implement FastAPI Middleware (Examples and Use Cases)

Mike Huls
4 min readDec 25, 2024

--

Image by ChatGPT

Middleware sits between an API router its routes, acting as a layer where you can run code before and after a request is handled. In this article we’ll explore two key use cases of middleware in FastAPI, demonstrating both how it works and why it’s useful. Let’s code!

A. Setting up

To begin, let’s create a simple API that serves as a base for our middleware examples. The app below has only one route: test which simulates actual work by sleeping for a few milliseconds before returning "OK".

import random
import time

from 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?

Middleware acts as a filter between the incoming HTTP request and the processing done by your application. Think of it like airport security: every passenger must go through security before and after boarding the plane. Similarly, every API request passes through middleware: both before being handled…

--

--

TDS Archive
TDS Archive

Published in TDS Archive

An archive of data science, data analytics, data engineering, machine learning, and artificial intelligence writing from the former Towards Data Science Medium publication.

Mike Huls
Mike Huls

Written by Mike Huls

I write about interesting programming-related things: techniques, system architecture, software design and how to apply them in the best way. — mikehuls.com

Responses (1)