Skip to content

Middleware

Craft Easy API includes a middleware stack that handles request tracking, domain routing, and error monitoring. Middleware is automatically configured when the application starts.

Request ID

Every HTTP request gets a unique identifier for tracing across logs and services.

How it works:

  1. If the incoming request has an X-Request-ID header, that value is used
  2. Otherwise, a new UUID is generated
  3. The ID is stored in request.state.request_id
  4. The ID is added to the response as an X-Request-ID header
  5. All log entries within the request inherit this ID via structlog contextvars

Usage in code:

@app.get("/my-endpoint")
async def my_endpoint(request: Request):
    request_id = request.state.request_id
    # Use for downstream service calls, log correlation, etc.

Client-side: Pass your own X-Request-ID header to correlate requests across services:

curl -H "X-Request-ID: my-trace-123" https://api.example.com/users

Domain Routing

When WHITE_LABEL_ENABLED=true, the middleware resolves the requesting domain to a specific tenant. This enables multi-tenant white-label deployments where each tenant has their own domain.

The middleware extracts the Host header and resolves it to a tenant_id, which is then used to scope all database queries for that request.

Sentry Integration

Error tracking via Sentry is built in. Configure with these settings:

Setting Default Description
SENTRY_DSN None Sentry DSN (disabled when not set)
SENTRY_ENVIRONMENT "development" Environment tag
SENTRY_TRACES_SAMPLE_RATE 0.1 Percentage of transactions to trace (0.0–1.0)
SENTRY_PROFILES_SAMPLE_RATE 0.1 Percentage of profiled transactions (0.0–1.0)
SENTRY_RELEASE None Release identifier

When a DSN is configured, Sentry automatically captures:

  • Unhandled exceptions with full stack traces
  • Request context (method, path, headers)
  • User context (user_id, tenant_id)
  • Performance traces (request duration, database queries)
# settings.py
SENTRY_DSN = "https://abc123@o456.ingest.sentry.io/789"
SENTRY_ENVIRONMENT = "production"
SENTRY_TRACES_SAMPLE_RATE = 0.2  # 20% of requests