HTTP middleware

suggest change

Middleware is code that sits between the web server and your application and runs for every request. It can:

Middleware layers wrap each other like an onion. A request passes through the layers from the outside in, reaches the application, and the response passes back through them from the inside out:

request  ──►  outer  ──►  middle  ──►  inner  ──►  app
response ◄──  outer  ◄──  middle  ◄──  inner  ◄──  app

In Python this idea is built into the two server interfaces:

Every framework also has its own, more convenient API for middleware. This article first builds middleware from scratch for WSGI and ASGI, so you understand what actually happens, and then shows the idiomatic way to do it in Flask, FastAPI and Django.

WSGI middleware from scratch

A WSGI application is a callable app(environ, start_response) that calls start_response(status, headers) and returns an iterable of bytes. A WSGI middleware is a callable with exactly the same signature that holds a reference to another WSGI application. To the server it looks like the app; to the app it looks like the server.

To run the examples without starting a server, we call WSGI apps directly with a small helper. wsgiref from the standard library fills in the required environ keys:

# helper.py
from wsgiref.util import setup_testing_defaults

def hello_app(environ, start_response):
    body = f"Hello from {environ['PATH_INFO']}\n".encode()
    start_response("200 OK", [("Content-Type", "text/plain"),
                              ("Content-Length", str(len(body)))])
    return [body]

def call(app, path="/", method="GET", headers=None):
    environ = {"PATH_INFO": path, "REQUEST_METHOD": method}
    for name, value in (headers or {}).items():
        environ["HTTP_" + name.upper().replace("-", "_")] = value
    setup_testing_defaults(environ)
    captured = {}
    def start_response(status, response_headers, exc_info=None):
        captured["status"] = status
        captured["headers"] = response_headers
    body = b"".join(app(environ, start_response))
    return captured["status"], captured["headers"], body

Note how request headers end up in environ: X-API-Key becomes HTTP_X_API_KEY.

The simplest middleware is a function that takes an app and returns a new app. Here it measures how long the request takes:

import time
from helper import hello_app, call

def timing_middleware(app):
    def middleware(environ, start_response):
        start = time.perf_counter()
        result = app(environ, start_response)
        elapsed = (time.perf_counter() - start) * 1000
        print(f"{environ['REQUEST_METHOD']} {environ['PATH_INFO']} took {elapsed:.2f} ms")
        return result
    return middleware

app = timing_middleware(hello_app)
print(call(app, "/hello"))
GET /hello took 0.01 ms
('200 OK', [('Content-Type', 'text/plain'), ('Content-Length', '18')], b'Hello from /hello\n')

If this looks like a decorator, that's because it is one: a function that wraps a callable and returns a callable with the same signature.

Modifying the request and the response

To change the request, modify environ before calling the app. To change the response status or headers, pass the app your own start_response that adjusts them and then calls the real one:

import uuid
from helper import hello_app, call

def request_id_middleware(app):
    def middleware(environ, start_response):
        request_id = environ.get("HTTP_X_REQUEST_ID") or uuid.uuid4().hex[:8]
        environ["app.request_id"] = request_id     # visible to the app

        def custom_start_response(status, headers, exc_info=None):
            headers.append(("X-Request-ID", request_id))
            return start_response(status, headers, exc_info)

        return app(environ, custom_start_response)
    return middleware

app = request_id_middleware(hello_app)
print(call(app, "/a", headers={"X-Request-ID": "abc123"}))
print(call(app, "/b")[1])
('200 OK', [('Content-Type', 'text/plain'), ('Content-Length', '14'), ('X-Request-ID', 'abc123')], b'Hello from /a\n')
[('Content-Type', 'text/plain'), ('Content-Length', '14'), ('X-Request-ID', 'c162d14d')]

By convention, keys you add to environ should contain a dot and a prefix (app.request_id, myframework.user) so they don't collide with CGI variables or keys added by the server.

Short-circuiting: answering without calling the app

Middleware doesn't have to call the application. An authentication layer can reject the request on its own:

from helper import hello_app, call

def api_key_middleware(app, valid_keys, public_paths=("/health",)):
    def middleware(environ, start_response):
        if environ["PATH_INFO"] in public_paths:
            return app(environ, start_response)
        if environ.get("HTTP_X_API_KEY") not in valid_keys:
            body = b'{"error": "invalid or missing API key"}'
            start_response("401 Unauthorized", [
                ("Content-Type", "application/json"),
                ("Content-Length", str(len(body))),
            ])
            return [body]
        return app(environ, start_response)
    return middleware

app = api_key_middleware(hello_app, valid_keys={"secret-1", "secret-2"})
print(call(app, "/health"))
print(call(app, "/orders"))
print(call(app, "/orders", headers={"X-API-Key": "secret-1"}))
('200 OK', [('Content-Type', 'text/plain'), ('Content-Length', '19')], b'Hello from /health\n')
('401 Unauthorized', [('Content-Type', 'application/json'), ('Content-Length', '39')], b'{"error": "invalid or missing API key"}')
('200 OK', [('Content-Type', 'text/plain'), ('Content-Length', '19')], b'Hello from /orders\n')

Class-based middleware

When middleware needs configuration or state, a class with __call__ reads better than nested closures. This one catches any exception from the app and returns a JSON 500 response:

import json
import logging
import sys
from helper import call

logging.basicConfig(level=logging.ERROR, stream=sys.stdout, format="%(levelname)s %(message)s")

class ErrorMiddleware:
    def __init__(self, app, debug=False):
        self.app = app
        self.debug = debug
        self.log = logging.getLogger("errors")

    def __call__(self, environ, start_response):
        try:
            return self.app(environ, start_response)
        except Exception as e:
            self.log.error("unhandled error on %s: %r", environ["PATH_INFO"], e)
            payload = {"error": "internal server error"}
            if self.debug:
                payload["detail"] = repr(e)
            body = json.dumps(payload).encode()
            start_response("500 Internal Server Error", [
                ("Content-Type", "application/json"),
                ("Content-Length", str(len(body))),
            ], sys.exc_info())
            return [body]

def buggy_app(environ, start_response):
    return [str(1 / 0).encode()]

app = ErrorMiddleware(buggy_app, debug=True)
print(call(app, "/divide"))
ERROR unhandled error on /divide: ZeroDivisionError('division by zero')
('500 Internal Server Error', [('Content-Type', 'application/json'), ('Content-Length', '85')], b'{"error": "internal server error", "detail": "ZeroDivisionError(\'division by zero\')"}')

Passing sys.exc_info() as the third argument tells the server that we're replacing a response because of an error. That's required by WSGI if the app had already called start_response before failing.

Order matters

Each wrap adds a new outer layer, so the last middleware you apply runs first:

from helper import hello_app, call

def tag(name):
    def decorator(app):
        def middleware(environ, start_response):
            print(f"{name}: before")
            result = app(environ, start_response)
            print(f"{name}: after")
            return result
        return middleware
    return decorator

app = hello_app
for mw in [tag("inner"), tag("middle"), tag("outer")]:
    app = mw(app)
call(app, "/")
outer: before
middle: before
inner: before
inner: after
middle: after
outer: after

A small compose helper lets you list middleware in the order requests see them, outermost first:

def compose(app, *middlewares):
    """First middleware in the list is the outermost."""
    for mw in reversed(middlewares):
        app = mw(app)
    return app

app = compose(hello_app, tag("A"), tag("B"))
call(app, "/")
A: before
B: before
B: after
A: after

Order is not cosmetic. Error-handling middleware must be outside the layers whose errors it should catch. Authentication should run before anything expensive. A request ID should be assigned before the logging layer that prints it.

Streaming responses and the response body

The timing middleware above has a subtle bug: it measures how long app() takes to return, not how long it takes to produce the body. If the app returns a generator, no work has happened yet when app() returns. To see the whole body you must iterate over it, and you must call its close() method afterwards, as the WSGI spec requires:

import time
from helper import call

def streaming_app(environ, start_response):
    start_response("200 OK", [("Content-Type", "text/plain")])
    for i in range(3):
        time.sleep(0.1)            # pretend each chunk is expensive
        yield f"chunk {i}\n".encode()

def access_log_middleware(app):
    def middleware(environ, start_response):
        start = time.perf_counter()
        status_holder = {}

        def capture_start_response(status, headers, exc_info=None):
            status_holder["status"] = status
            return start_response(status, headers, exc_info)

        result = app(environ, capture_start_response)
        print(f"app() returned after {(time.perf_counter() - start) * 1000:.0f} ms")
        size = 0
        try:
            for chunk in result:
                size += len(chunk)
                yield chunk
        finally:
            if hasattr(result, "close"):
                result.close()
            elapsed = (time.perf_counter() - start) * 1000
            print(f'{environ["REQUEST_METHOD"]} {environ["PATH_INFO"]} '
                  f'{status_holder.get("status")} {size}B {elapsed:.0f} ms')
    return middleware

app = access_log_middleware(streaming_app)
print(call(app, "/stream"))
app() returned after 0 ms
GET /stream 200 OK 24B 301 ms
('200 OK', [('Content-Type', 'text/plain')], b'chunk 0\nchunk 1\nchunk 2\n')

Because the middleware yields chunks as they arrive, the response is still streamed to the client instead of being buffered in memory.

Running it with a real server

Any WSGI server works with middleware-wrapped apps, because the result is just another WSGI app. With the standard library:

from wsgiref.simple_server import make_server
from helper import hello_app
# compose, access_log_middleware and request_id_middleware are defined above

app = compose(hello_app, access_log_middleware, request_id_middleware)

with make_server("127.0.0.1", 8000, app) as server:
    print("Serving on http://127.0.0.1:8000")
    server.serve_forever()

In production you'd run the same app object with Gunicorn or Waitress: gunicorn mymodule:app. See Web Server Gateway Interface WSGI for more on the interface itself.

Flask

Flask gives you two levels: request hooks inside the framework, and plain WSGI middleware around it.

before_request, after_request, teardown_request

For most application-level needs, hooks are simpler than WSGI middleware because you work with Flask's request and Response objects instead of raw environ:

import time
import uuid
from flask import Flask, g, request

app = Flask(__name__)

@app.before_request
def start_timer():
    g.start = time.perf_counter()
    g.request_id = request.headers.get("X-Request-ID", uuid.uuid4().hex[:8])

@app.before_request
def require_api_key():
    if request.path.startswith("/admin") and request.headers.get("X-API-Key") != "secret":
        return {"error": "forbidden"}, 403   # short-circuits: the view never runs

@app.after_request
def add_headers(response):
    elapsed = (time.perf_counter() - g.start) * 1000
    response.headers["X-Request-ID"] = g.request_id
    response.headers["Server-Timing"] = f"app;dur={elapsed:.1f}"
    return response

@app.teardown_request
def cleanup(exc):
    print(f"teardown {request.path}, exception={exc!r}")

@app.get("/")
def index():
    return "home"

@app.get("/admin/stats")
def stats():
    return {"users": 42}

client = app.test_client()
for path, headers in [("/", {"X-Request-ID": "r-1"}), ("/admin/stats", {}),
                      ("/admin/stats", {"X-API-Key": "secret"})]:
    r = client.get(path, headers=headers)
    print(r.status, r.get_data(as_text=True).strip(),
          r.headers["X-Request-ID"], r.headers["Server-Timing"])
teardown /, exception=None
200 OK home r-1 app;dur=0.1
teardown /admin/stats, exception=None
403 FORBIDDEN {"error":"forbidden"} 250102a5 app;dur=0.1
teardown /admin/stats, exception=None
200 OK {"users":42} e262c0c5 app;dur=0.0

How the hooks behave:

Hooks registered on a blueprint (bp.before_request) run only for that blueprint's routes. The CORS article shows a real-world after_request hook.

Wrapping app.wsgi_app

For things that should happen before Flask even sees the request, use WSGI middleware. Wrap app.wsgi_app rather than app itself, so that app stays a Flask object and app.run(), app.test_client() and extensions keep working:

from flask import Flask, request
from werkzeug.middleware.proxy_fix import ProxyFix

app = Flask(__name__)

@app.get("/ip")
def ip():
    return {"remote_addr": request.remote_addr, "scheme": request.scheme}

def strip_prefix(prefix):
    def decorator(wsgi_app):
        def middleware(environ, start_response):
            path = environ["PATH_INFO"]
            if path.startswith(prefix):
                environ["PATH_INFO"] = path[len(prefix):] or "/"
                environ["SCRIPT_NAME"] = environ.get("SCRIPT_NAME", "") + prefix
            return wsgi_app(environ, start_response)
        return middleware
    return decorator

app.wsgi_app = strip_prefix("/api")(app.wsgi_app)
app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1, x_proto=1)

client = app.test_client()
r = client.get("/api/ip", headers={"X-Forwarded-For": "203.0.113.7",
                                   "X-Forwarded-Proto": "https"})
print(r.status, r.json)
200 OK {'remote_addr': '203.0.113.7', 'scheme': 'https'}

ProxyFix from Werkzeug is the middleware you want when your app runs behind nginx or a load balancer: it takes the client IP and scheme from X-Forwarded-* headers. Only enable it when there really is a proxy in front, and set x_for to the number of proxies, otherwise clients can spoof their IP address. Werkzeug also ships DispatcherMiddleware (mount several apps under different paths) and SharedDataMiddleware (serve static files).

ASGI middleware from scratch

An ASGI application is an async callable app(scope, receive, send):

ASGI middleware is again an object with the same signature that wraps another app. Since the response isn't a return value but a sequence of send() calls, you modify it by wrapping send:

import asyncio
import time

async def app(scope, receive, send):
    assert scope["type"] == "http"
    body = f"Hello from {scope['path']}\n".encode()
    await send({"type": "http.response.start", "status": 200,
                "headers": [(b"content-type", b"text/plain")]})
    await send({"type": "http.response.body", "body": body})

class TimingMiddleware:
    def __init__(self, app):
        self.app = app

    async def __call__(self, scope, receive, send):
        if scope["type"] != "http":          # pass through websocket, lifespan
            await self.app(scope, receive, send)
            return

        start = time.perf_counter()

        async def send_wrapper(message):
            if message["type"] == "http.response.start":
                elapsed = (time.perf_counter() - start) * 1000
                headers = list(message.get("headers", []))
                headers.append((b"server-timing", f"app;dur={elapsed:.1f}".encode()))
                message = {**message, "headers": headers}
            await send(message)

        await self.app(scope, receive, send_wrapper)

app = TimingMiddleware(app)

async def call(app, path="/"):
    scope = {"type": "http", "method": "GET", "path": path, "headers": []}
    async def receive():
        return {"type": "http.request", "body": b"", "more_body": False}
    messages = []
    async def send(message):
        messages.append(message)
    await app(scope, receive, send)
    return messages

for m in asyncio.run(call(app, "/hi")):
    print(m)
{'type': 'http.response.start', 'status': 200, 'headers': [(b'content-type', b'text/plain'), (b'server-timing', b'app;dur=0.0')]}
{'type': 'http.response.body', 'body': b'Hello from /hi\n'}

Always pass through scope types you don't handle. Forgetting the scope["type"] check is a classic way to break WebSockets or startup/shutdown events.

FastAPI and Starlette

Install with pip install fastapi httpx2 (the TestClient used below needs httpx2). FastAPI's middleware support comes from Starlette, so everything here applies to Starlette apps too.

@app.middleware("http") and BaseHTTPMiddleware

The convenient API gives you a Request and a call_next function that runs the rest of the stack and returns the Response:

import time
import uuid
from contextvars import ContextVar

from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
from fastapi.testclient import TestClient
from starlette.middleware.base import BaseHTTPMiddleware

request_id_var: ContextVar[str] = ContextVar("request_id", default="-")

app = FastAPI()

@app.middleware("http")
async def add_timing(request: Request, call_next):
    start = time.perf_counter()
    response = await call_next(request)
    elapsed = (time.perf_counter() - start) * 1000
    response.headers["Server-Timing"] = f"app;dur={elapsed:.1f}"
    return response

class RequestIDMiddleware(BaseHTTPMiddleware):
    def __init__(self, app, header_name: str = "X-Request-ID"):
        super().__init__(app)
        self.header_name = header_name

    async def dispatch(self, request: Request, call_next):
        request_id = request.headers.get(self.header_name) or uuid.uuid4().hex[:8]
        token = request_id_var.set(request_id)
        try:
            response = await call_next(request)
        finally:
            request_id_var.reset(token)
        response.headers[self.header_name] = request_id
        return response

app.add_middleware(RequestIDMiddleware)

@app.middleware("http")
async def require_api_key(request: Request, call_next):
    if request.url.path.startswith("/admin") and request.headers.get("x-api-key") != "secret":
        return JSONResponse({"error": "forbidden"}, status_code=403)
    return await call_next(request)

@app.get("/items/{item_id}")
async def get_item(item_id: int):
    return {"item_id": item_id, "request_id": request_id_var.get()}

@app.get("/admin/stats")
async def stats():
    return {"users": 42}

client = TestClient(app)
r = client.get("/items/7", headers={"X-Request-ID": "r-42"})
print(r.status_code, r.json(), r.headers["x-request-id"], r.headers["server-timing"])
r = client.get("/admin/stats")
print(r.status_code, r.json(), r.headers.get("x-request-id"), r.headers.get("server-timing"))
200 {'item_id': 7, 'request_id': 'r-42'} r-42 app;dur=0.5
403 {'error': 'forbidden'} None None

Two things to notice:

@app.middleware("http") is just a shortcut for BaseHTTPMiddleware. Subclass BaseHTTPMiddleware directly when the middleware needs constructor arguments; add_middleware passes extra keyword arguments to __init__.

Pure ASGI middleware in FastAPI

BaseHTTPMiddleware is convenient but adds overhead and works on whole Request/Response objects. For reusable, performance-sensitive middleware (or anything that must not interfere with streaming responses and WebSockets) write pure ASGI middleware, as in the previous section, and register it with add_middleware. Starlette's MutableHeaders makes editing the raw header list easy:

from fastapi import FastAPI
from fastapi.responses import StreamingResponse
from fastapi.testclient import TestClient
from starlette.datastructures import MutableHeaders
from starlette.middleware.gzip import GZipMiddleware
from starlette.middleware.trustedhost import TrustedHostMiddleware
from starlette.types import ASGIApp, Message, Receive, Scope, Send

class SecurityHeadersMiddleware:
    def __init__(self, app: ASGIApp, hsts: bool = True) -> None:
        self.app = app
        self.hsts = hsts

    async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
        if scope["type"] != "http":
            await self.app(scope, receive, send)
            return

        async def send_wrapper(message: Message) -> None:
            if message["type"] == "http.response.start":
                headers = MutableHeaders(scope=message)
                headers["X-Content-Type-Options"] = "nosniff"
                headers["X-Frame-Options"] = "DENY"
                if self.hsts:
                    headers["Strict-Transport-Security"] = "max-age=31536000"
            await send(message)

        await self.app(scope, receive, send_wrapper)

class Trace:
    def __init__(self, app: ASGIApp, name: str) -> None:
        self.app, self.name = app, name

    async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
        print(f"{self.name}: in")
        await self.app(scope, receive, send)
        print(f"{self.name}: out")

app = FastAPI()
app.add_middleware(Trace, name="added first")
app.add_middleware(Trace, name="added second")
app.add_middleware(SecurityHeadersMiddleware, hsts=False)
app.add_middleware(GZipMiddleware, minimum_size=500)
app.add_middleware(TrustedHostMiddleware, allowed_hosts=["example.com", "testserver"])

@app.get("/numbers")
async def numbers():
    async def gen():
        for i in range(1000):
            yield f"{i}\n"
    return StreamingResponse(gen(), media_type="text/plain")

client = TestClient(app)
r = client.get("/numbers")
print(r.status_code, r.headers["content-encoding"], r.headers["x-frame-options"],
      len(r.text.splitlines()), "lines")
r = client.get("/numbers", headers={"Host": "evil.com"})
print(r.status_code, r.text)
added second: in
added first: in
added first: out
added second: out
200 gzip DENY 1000 lines
400 Invalid host header

The streamed response passed through all layers, got compressed by GZipMiddleware and received security headers. The request with a wrong Host was rejected by TrustedHostMiddleware, the outermost layer, so the Trace layers didn't print anything for it.

Starlette ships several ready-made middleware classes: CORSMiddleware, GZipMiddleware, TrustedHostMiddleware, HTTPSRedirectMiddleware and SessionMiddleware. Because they're plain ASGI apps, they also work with any other ASGI framework.

Django

Django middleware is a factory: a callable that receives get_response (the next layer) once at startup and returns a callable that handles each request. It can be a function or a class:

import time

from django.conf import settings
from django.http import JsonResponse
from django.urls import path

def timing_middleware(get_response):
    # one-time setup when the server starts
    def middleware(request):
        start = time.perf_counter()
        response = get_response(request)          # call the next layer
        elapsed = (time.perf_counter() - start) * 1000
        response["Server-Timing"] = f"app;dur={elapsed:.1f}"
        return response
    return middleware

class ApiKeyMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response
        self.valid_keys = set(settings.API_KEYS)

    def __call__(self, request):
        if request.path.startswith("/admin/"):
            if request.headers.get("X-API-Key") not in self.valid_keys:
                return JsonResponse({"error": "forbidden"}, status=403)
        return self.get_response(request)

    def process_exception(self, request, exception):
        if isinstance(exception, PermissionError):
            return JsonResponse({"error": str(exception)}, status=403)
        return None   # let Django handle other exceptions

def index(request):
    return JsonResponse({"page": "home"})

def stats(request):
    return JsonResponse({"users": 42})

def secret(request):
    raise PermissionError("not your file")

urlpatterns = [path("", index), path("admin/stats", stats), path("secret", secret)]

# a whole Django project in one file, for demonstration
settings.configure(
    DEBUG=False,
    ROOT_URLCONF=__name__,
    ALLOWED_HOSTS=["testserver"],
    API_KEYS=["secret-1"],
    MIDDLEWARE=[
        "django.middleware.security.SecurityMiddleware",
        f"{__name__}.timing_middleware",
        f"{__name__}.ApiKeyMiddleware",
    ],
)

import django
django.setup()

from django.test import Client

client = Client()
for url, headers in [("/", {}), ("/admin/stats", {}),
                     ("/admin/stats", {"X-API-Key": "secret-1"}), ("/secret", {})]:
    r = client.get(url, headers=headers)
    print(r.status_code, r.json(), "timing" if "Server-Timing" in r else "no timing")
200 {'page': 'home'} timing
403 {'error': 'forbidden'} timing
200 {'users': 42} timing
403 {'error': 'not your file'} timing

In a real project the middleware lives in a module such as myproject/middleware.py and you list it in settings.py:

MIDDLEWARE = [
    "django.middleware.security.SecurityMiddleware",
    "django.contrib.sessions.middleware.SessionMiddleware",
    "django.middleware.common.CommonMiddleware",
    "django.middleware.csrf.CsrfViewMiddleware",
    "django.contrib.auth.middleware.AuthenticationMiddleware",
    "myproject.middleware.timing_middleware",
    "myproject.middleware.ApiKeyMiddleware",
]

Unlike the wrapping style of WSGI and Starlette, Django's list is in request order: the first entry is the outermost layer, it sees the request first and the response last. Order matters here too. For example, anything that reads request.user must come after AuthenticationMiddleware, which sets it.

Besides __call__, a class-based Django middleware can define optional hooks:

Django middleware can also be async (mark it with @sync_and_async_middleware or define async def __call__), so it doesn't force a sync-async switch when running under ASGI.

Common uses and pitfalls

Things that are typically done in middleware:

Things to watch out for:

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents