Middleware in FastAPI

Middleware runs for every request and response in a FastAPI application.

It is useful for common functionality such as:

  • Logging requests
  • Processing requests
  • Adding response headers
  • Handling common operations across the application

Instead of writing the same logic in every route, middleware allows you to execute it centrally.

Creating Middleware

FastAPI provides the @app.middleware("http") decorator for creating HTTP middleware.

from fastapi import Request


@app.middleware("http")
async def log_request(
    request: Request,
    call_next
):
    print("Request:", request.url.path)

    response = await call_next(request)

    print("Status:", response.status_code)

    return response

Understanding the Code

Import Request

from fastapi import Request

Request provides information about the incoming HTTP request.

For example, we can access:

request.url.path

to get the requested URL path.

Middleware Function

@app.middleware("http")
async def log_request(
    request: Request,
    call_next
):

The @app.middleware("http") decorator tells FastAPI that this function should run for HTTP requests.

The middleware receives two important arguments:

  • request — the incoming request.
  • call_next — passes the request to the next middleware or API route.

Logging the Request

print("Request:", request.url.path)

This prints the requested URL path.

For example, if the user requests:

/users

the output will contain:

Request: /users

Calling the Next Handler

response = await call_next(request)

This passes the request forward.

The request eventually reaches the API endpoint, and the response is returned back through the middleware.

Logging the Response Status

print("Status:", response.status_code)

This prints the HTTP status code returned by the API.

For a successful request:

Status: 200

Returning the Response

return response

The middleware must return the response so that it can be sent back to the client.

Example Output

When requesting:

/users

the middleware produces:

Request: /users
Status: 200

Middleware Flow

The request flow looks like this:

Client
   ↓
Middleware
   ↓
API Route
   ↓
Response
   ↓
Middleware
   ↓
Client

This makes middleware useful when the same processing needs to happen for many or all API endpoints.

Common Uses of Middleware

Middleware can be used for:

Logging
   ↓
Request Processing
   ↓
Authentication-related Processing
   ↓
Response Headers
   ↓
Other Common Operations

The key advantage is that you can implement common functionality once instead of repeating it inside every route.

Summary

In this topic, we learned:

  • Middleware runs for HTTP requests.
  • It can process requests before they reach an endpoint.
  • It can process responses before they are returned.
  • call_next(request) passes the request to the next handler.
  • Middleware is useful for logging, request processing, headers, and other common functionality.