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:
- If the incoming request has an
X-Request-IDheader, that value is used - Otherwise, a new UUID is generated
- The ID is stored in
request.state.request_id - The ID is added to the response as an
X-Request-IDheader - 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:
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)