Documentation FastAPI Middleware
5 min read | June 24, 2026
Tutorial

FastAPI Middleware

The Astralog FastAPI middleware automatically intercepts every HTTP request, calculates latency, tracks status codes, and generates distributed trace_id headers without blocking the Event Loop.

View on GitHub

Installation

pip install astralog-fastapi astralog

Setup

# main.py
from fastapi import FastAPI
from astralog import Client
from astralog.middlewares import AstralogFastAPIMiddleware

client = Client(api_key="ast_sk_live_xxxxxxxxxxxxx")
app = FastAPI()

# Magically intercept all HTTP traffic
app.add_middleware(AstralogFastAPIMiddleware, client=client)

@app.get("/checkout")
def process_payment():
    # Manual logging works perfectly alongside the middleware
    client.info("User accessed checkout", {"user_id": "usr_123"})
    return {"status": "success"}

Background Mechanics

Because FastAPI is heavily asynchronous, Astralog runs the network flushing in a separate daemon thread. Intercepting a route injects practically 0ms latency to your user’s request.