What Is Middleware?
Exit

What Is Middleware?

Understand how middleware wraps every request and response in your API

The request lifecycle

When a request hits your API, FastAPI routes it to the matching endpoint function. But sometimes you need code that runs on every request — logging, timing, authentication, or header injection. Writing that code inside every endpoint would be repetitive and error-prone.

Middleware solves this. A middleware function wraps the entire request-response cycle. It runs before the endpoint processes the request and after the endpoint generates the response.

Client
  |
  |  Request
  v
Middleware (before)
  |
  v
Endpoint function
  |
  |  Response
  v
Middleware (after)
  |
  v
Client

What middleware can do

Middleware has access to the incoming request and the outgoing response. Common uses:

  • Logging: record the HTTP method, URL path, status code, and how long the request took
  • Timing: measure the duration of each request for performance monitoring
  • CORS: add headers that allow browsers to call your API from a different domain
  • Authentication: check for a valid token before the endpoint runs

How FastAPI middleware works

In FastAPI, you define middleware with the @app.middleware("http") decorator. Your middleware function receives the request and a call_next function. You call call_next(request) to pass the request to the endpoint, and it returns the response. Anything you do before call_next runs before the endpoint. Anything you do after runs after.

In the next chapter, you will write a middleware that logs every request with its method, path, status code, and duration in milliseconds.

Next Chapter →