Gajanan Rajput

Sep 10, 2025 • 3 min read

FastAPI Middleware Explained (Like You're 5 Years Old)

Understand middleware step by step with humor, real-life analogies, and beginner-friendly FastAPI code snippets.

FastAPI Middleware Explained (Like You're 5 Years Old)

When I first heard the word “Middleware”, I thought it sounded like some kind of fancy sandwich layer. You know… bread, cheese, middleware, bread.

👉 (For Non-Members link to the full story)

But in FastAPI, middleware isn’t about food (sadly 🍔). It’s about a magic layer that sits between the request (when you call an API) and the response (when the API sends something back).

In short:
 👉 Middleware = middle layer between request and response.


Why Do We Even Need Middleware?

Let me explain like I’m talking to my 5-year-old cousin:

Imagine you’re going into an amusement park. Before you enjoy the rides, you have to:

  • Show your ticket 🎟️

  • Pass through security 🛂

  • Maybe get your bag checked 🎒

Only after that can you scream your lungs out on the roller coaster 🎢.

That’s exactly what middleware does for your FastAPI app.
 It can:

  • Check the request before it reaches your API (like security guards).

  • Change or log something (like stamping your hand 🖐️).

  • Or even mess with the response before it goes back (like adding “Thank you, visit again”).


How Middleware Works in FastAPI

In FastAPI, middleware is just a function that:

  1. Takes the request.

  2. Does something before your API runs.

  3. Calls your API.

  4. Does something after your API runs.

  5. Returns the final response.


Let’s Write Our First Middleware

Here’s a simple middleware that logs the time taken for each request.

from fastapi import FastAPI, Request
import time

app = FastAPI()

@app.middleware("http")
async def log_request_time(request: Request, call_next):
 start_time = time.time()
 
 # Pass the request to the actual API (like saying: "Ok ride the roller coaster")
 response = await call_next(request)
 
 process_time = time.time() - start_time
 print(f"Request took: {process_time:.4f} seconds")
 
 # Add extra info in the response header (like giving you a wristband at the park)
 response.headers["X-Process-Time"] = str(process_time)
 
 return response

@app.get("/")
async def home():
 return {"message": "Hello from FastAPI 🎉"}

What’s Happening Here?

  • @app.middleware("http") → Tells FastAPI this is middleware for all HTTP requests.

  • request → That’s the incoming request (like the person entering the amusement park).

  • call_next(request) → Passes the request to the next step (like letting them onto the ride).

  • response → The API’s response that comes back.

  • We calculate how long the request took and add that info into the response header.

So whenever you call the API, it will not only give you the response but also secretly whisper:
 ⏱️ “By the way, I took 0.0021 seconds to do this.”


More Fun Middleware Ideas

Middleware isn’t just for timing things. You can use it to:

Log every request (like a diary 📓)
 ✅ Add authentication checks (like a bouncer at a club 🚪)
 ✅ Modify requests or responses (like changing someone’s outfit before the party 👗)
 ✅ Handle errors globally (like a first-aid tent 🏥)


Example: Block Naughty Users 🚫

Let’s say we don’t want requests from a certain IP (because they’re spamming us).

@app.middleware("http")
async def block_spammers(request: Request, call_next):
 client_ip = request.client.host
 if client_ip == "123.45.67.89": # example naughty IP
 return {"error": "You are banned! 🚫"}
 
 response = await call_next(request)
 return response

Boom 💥 — spammers get blocked before even touching your real API.


Middleware vs Dependency (What’s the Difference?)

You might be thinking:

“But hey, can’t I just use dependencies to check stuff?”

Yes, you can. But:

  • Dependencies → Run on specific routes (like guards at only one ride 🎡).

  • Middleware → Runs on every single request (like the security check at the main entrance 🏰).

So if you want a global rule → use middleware.
 If you want a local rule → use dependencies.


Wrapping It Up 🎁

So middleware in FastAPI is like the gatekeeper of your app.

  • It checks requests before they hit your API.

  • It can change the response before sending it back.

  • It runs on every request automatically.

Now, whenever someone asks you:
 👉 “What’s middleware in FastAPI?”
 You can proudly say:

“It’s the bouncer at the club of my API.” 🍹😎


Final Words

When I first learned middleware, I thought: “Wow, this is complicated.”
 But once I played with examples, I realized it’s just like a sandwich layer or a security check.

So don’t overthink it.
Just remember: Middleware is the middleman that helps your API stay safe, smart, and smooth.

Happy coding, my fellow amusement park riders 🎢✨


A Note From the Author

Thank you so much for taking the time to read the story. If you found my article helpful and interesting, please share your thoughts in the comment section, and don’t forget to share and clap 😊

Join Gajanan on Peerlist!

Join amazing folks like Gajanan and thousands of other builders on Peerlist.

peerlist.io/

It’s available... this username is available! 😃

Claim your username before it's too late!

This username is already taken, you’re a little late.😐

0

9

0