How to Integrate Headroom as Middleware in FastAPI and ASGI Applications

Headroom provides a drop-in ASGI middleware that wraps any FastAPI or ASGI-compatible application to apply request/response transforms like compression and content routing without modifying existing route logic.

Headroom is an open-source proxy framework that ships with a native ASGI integration, allowing you to embed its transformation pipeline directly into Python web services. By integrating Headroom as middleware, you gain access to features like request compression, content routing, and tag protection while keeping your existing FastAPI routes unchanged.

Understanding the Headroom ASGI Middleware

The ASGI middleware is defined in headroom/integrations/asgi.py and implements the standard ASGI double-callable interface. When attached to your application, every incoming request passes through the Headroom pipeline before reaching your route handlers:

  1. Interception: The middleware captures the ASGI scope, receive, and send objects.
  2. Transformation: It extracts the raw request body, runs configured transforms (compression, routing, etc.), and rewrites request/response objects as needed.
  3. Delegation: Your FastAPI endpoint receives the transformed payload, and the response travels back through the pipeline for post-processing.

This approach is completely optional; if Headroom is not configured, your FastAPI app behaves exactly as usual, making it safe to add to existing services without risk.

Prerequisites and Configuration

Before adding the middleware, instantiate a ProxyConfig object that defines which transforms to apply. The configuration mirrors the JSON schema used by the standalone Headroom proxy and can be built programmatically.

Available transforms mentioned in the source include:

  • SearchCompressor – for response compression
  • ContentRouter – for request routing logic
  • TagProtector – for content filtering

Method 1: Direct Middleware Registration with FastAPI

The most explicit approach uses FastAPI's native add_middleware helper. Import HeadroomASGIMiddleware from headroom/integrations/asgi.py and pass your ProxyConfig instance.


# app.py – minimal FastAPI‑Headroom integration

from fastapi import FastAPI
from headroom.integrations.asgi import HeadroomASGIMiddleware
from headroom.proxy.config import ProxyConfig
from headroom.transforms import (
    SearchCompressor,
    ContentRouter,
    TagProtector,
)

# Build configuration with desired transforms

config = ProxyConfig(
    transforms=[
        SearchCompressor(),
        ContentRouter(),
        TagProtector(),
    ],
    # Optional: add custom telemetry, limits, etc.

)

# Create FastAPI application

app = FastAPI()

# Attach Headroom ASGI middleware

app.add_middleware(HeadroomASGIMiddleware, config=config)

# Define your standard routes

@app.get("/hello")
async def hello():
    return {"msg": "Hello from FastAPI with Headroom!"}

Method 2: Using the Generic Install Helper

For a more concise setup, use the install_headroom callable exposed in headroom/proxy/extensions.py. This utility internally registers the ASGI middleware while accepting the same configuration object.

from fastapi import FastAPI
from headroom.proxy.extensions import install_headroom
from headroom.proxy.config import ProxyConfig
from headroom.transforms import SearchCompressor, ContentRouter

app = FastAPI()

config = ProxyConfig(
    transforms=[SearchCompressor(), ContentRouter()]
)

# Installs HeadroomASGIMiddleware internally

install_headroom(app, config)

@app.post("/chat")
async def chat_endpoint():
    return {"response": "processed"}

Both methods result in identical runtime behavior. Choose the approach that best fits your project's conventions for middleware registration.

Configuration Deep Dive

The ProxyConfig class (referenced in headroom/proxy/config.py) accepts a list of transform instances. According to the source code in docs/spec/005-integrations.md, you can tune the middleware per-application, enabling or disabling particular transforms at runtime without affecting other services.

When using the middleware approach instead of the standalone proxy binary, you gain:

  • Single-process deployment – No separate Rust binary to manage
  • Fine-grained control – Transform policies scoped to individual FastAPI instances
  • Unified observability – Telemetry data flows through your existing logging pipeline

Summary

  • Headroom ships with HeadroomASGIMiddleware in headroom/integrations/asgi.py for seamless ASGI integration.
  • Attach the middleware via app.add_middleware(HeadroomASGIMiddleware, config=config) or use install_headroom(app, config) from headroom/proxy/extensions.py.
  • Configure transforms using the ProxyConfig class, supporting compression, routing, and protection policies.
  • The middleware intercepts ASGI scope objects to transform requests/responses without altering your business logic.
  • This pattern works with any ASGI-compatible framework, including FastAPI, Starlette, and LiteLLM.

Frequently Asked Questions

Can I use Headroom middleware with frameworks other than FastAPI?

Yes. The HeadroomASGIMiddleware class conforms to the ASGI specification, making it compatible with any ASGI-compatible framework such as Starlette, LiteLLM, or custom ASGI apps. Simply replace FastAPI() with your framework's application instance and use the same add_middleware call.

What file contains the actual middleware implementation?

The core middleware logic resides in headroom/integrations/asgi.py, which defines the HeadroomASGIMiddleware class that wraps your ASGI application. This file handles the extraction of request bodies, execution of transforms, and rewriting of response objects.

Do I need to run a separate Headroom proxy binary when using the middleware?

No. When you integrate Headroom as middleware directly into your FastAPI application, you embed the transformation pipeline into the same process. This eliminates the need to deploy the standalone Headroom proxy binary while still gaining access to the same transform capabilities defined in your ProxyConfig.

How do I configure custom telemetry for the middleware?

Pass telemetry configuration options directly to the ProxyConfig constructor when initializing the middleware. The configuration object supports the same fields used by the full Headroom proxy, allowing you to set custom metrics endpoints, logging levels, and limits that integrate with your FastAPI application's existing observability stack.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →