Install & Compatibility
Where this runs
tested against v5.0.1 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
muslpy 3.10–3.915 runs
installs and imports cleanly · install 0.0s · import 0.229s · 26.3MB
glibcpy 3.10–3.915 runs
installs and imports cleanly · install 2.3s · import 0.208s · 27MB
24MB installed
● package 24MB
Code
Verified usage
Verified import paths — ran on the pinned version, not inferred.
CorrelationIdMiddleware
✓ from asgi_correlation_id import CorrelationIdMiddleware
correlation_id
✓ from asgi_correlation_id import correlation_id
A `contextvars.ContextVar` holding the current request's correlation ID.
correlation_id_filter
✓ from asgi_correlation_id import correlation_id_filter
A logging filter to automatically inject the correlation ID into log records.
This quickstart demonstrates how to integrate `asgi-correlation-id` with a FastAPI application. It shows how to add the `CorrelationIdMiddleware` and configure standard Python logging with `correlation_id_filter` to automatically include the correlation ID in log records. It also illustrates how to access the current request's correlation ID directly using `correlation_id.get()`.
import logging
from fastapi import FastAPI
from asgi_correlation_id import CorrelationIdMiddleware, correlation_id, correlation_id_filter
# Configure standard Python logging to include correlation ID
# This adds the 'correlation_id' attribute to log records
logging.basicConfig(level=logging.INFO, format='%(levelname)s: %(asctime)s - %(correlation_id)s - %(message)s')
logging.getLogger('your_app_logger').addFilter(correlation_id_filter)
# Note: For uvicorn's access logs, you need to configure uvicorn's log_config separately,
# e.g., uvicorn.run(app, log_config={'format': '%(levelprefix)s %(asctime)s - %(correlation_id)s - %(message)s'})
app = FastAPI()
# Add the CorrelationIdMiddleware to your ASGI application
app.add_middleware(
CorrelationIdMiddleware,
# You can customize the header name, default is 'X-Request-ID'
# header_name="X-Correlation-ID",
# Optionally, generate UUIDv4 if no header is present (default True)
# generate_uuid_if_not_found=True
)
@app.get("/items/{item_id}")
async def read_item(item_id: int):
# The correlation ID is automatically available in logs configured with the filter
logging.getLogger('your_app_logger').info(f"Processing request for item {item_id}")
# You can also access the correlation ID directly within your code
current_correlation_id = correlation_id.get()
logging.getLogger('your_app_logger').info(f"Correlation ID retrieved directly: {current_correlation_id}")
return {"item_id": item_id, "correlation_id": current_correlation_id}
if __name__ == '__main__':
# To run this application:
# 1. Save this code as 'main.py'
# 2. Run from your terminal: 'uvicorn main:app --port 8000'
# Then access http://localhost:8000/items/123
print("To run: save as main.py and execute 'uvicorn main:app --port 8000'")
Debug
Known issues
breakingVersion 4.0.0 removed the `Access-Control-Expose-Headers` response header by default. If your frontend relies on this header for fetching the correlation ID, you must explicitly configure your CORS middleware to expose `X-Request-ID` or your custom correlation ID header.fixManually add the correlation ID header name (e.g., `X-Request-ID`) to `Access-Control-Expose-Headers` in your ASGI CORS middleware (e.g., `CORSMiddleware` in Starlette/FastAPI).
affects: >=4.0.0
breakingIn version 4.0.0, the default value of the `update_request_header` parameter in `CorrelationIdMiddleware` changed. This might affect how incoming `X-Request-ID` headers are handled and whether the response header reflects the *generated* or *incoming* ID.fixReview your `CorrelationIdMiddleware` initialization. If specific behavior regarding incoming header updates or response header values is required, explicitly set `update_request_header=True` or `False` as needed.
affects: >=4.0.0
deprecatedOfficial support for Python 3.7 was dropped in version 4.3.0. While the middleware might still function on 3.7 for now, future compatibility is not guaranteed.fixUpgrade your Python environment to 3.8 or newer to ensure continued compatibility and receive ongoing support and updates.
affects: >=4.3.0
gotchaIntegrating the correlation ID into Uvicorn's default access logs requires explicit configuration. It is not automatically included in the default `uvicorn.run()` log format.fixUse the `uvicorn` extra (`pip install asgi-correlation-id[uvicorn]`) and configure Uvicorn's `log_config` or `log_format` with a custom format string that includes `%(correlation_id)s` (e.g., `--log-config uvicorn_log_config.json` or `uvicorn.run(..., log_config={'format': '...'}`). affects: *
gotchaWhen integrating `asgi-correlation-id` with Sentry, ensure your `sentry-sdk` version is compatible. Version 4.3.3 of `asgi-correlation-id` specifically fixed deprecation warnings that could occur with `sentry-sdk` 2.x.fixUpdate `asgi-correlation-id` to version 4.3.3 or newer if you are using `sentry-sdk` 2.x to avoid potential deprecation warnings and ensure proper integration.
affects: <4.3.3 (when using sentry-sdk 2.x)
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'asgi-correlation-id'
The 'asgi-correlation-id' package is not installed in the Python environment.
fixInstall the package using pip: 'pip install asgi-correlation-id'.
ImportError: cannot import name 'CorrelationIdMiddleware' from 'asgi_correlation_id'
The 'CorrelationIdMiddleware' class is not found in the 'asgi_correlation_id' module, possibly due to an incorrect import statement.
fixEnsure the correct import statement: 'from asgi_correlation_id.middleware import CorrelationIdMiddleware'.
AttributeError: module 'asgi_correlation_id' has no attribute 'CorrelationIdMiddleware'
Attempting to access 'CorrelationIdMiddleware' directly from the 'asgi_correlation_id' module, which does not expose this attribute.
fixImport 'CorrelationIdMiddleware' from the 'middleware' submodule: 'from asgi_correlation_id.middleware import CorrelationIdMiddleware'.
TypeError: CorrelationIdMiddleware() takes no arguments
Incorrect instantiation of 'CorrelationIdMiddleware' without the required 'app' argument.
fixInstantiate 'CorrelationIdMiddleware' with the ASGI app: 'app = CorrelationIdMiddleware(app)'.
ValueError: Correlation ID header name must be a non-empty string
Providing an invalid or empty string as the 'header_name' parameter when initializing 'CorrelationIdMiddleware'.
fixEnsure 'header_name' is a non-empty string: 'app = CorrelationIdMiddleware(app, header_name="X-Request-ID")'.
Upgrade
Version history
5.0.1latest on PyPI · released Jun 9, 2026
Audit
Dependencies
packagingrequiredUsed for internal version comparisons, particularly in Sentry integration.
uvicornoptionalOptional dependency for Uvicorn-specific access logging setup.
sentry-sdkoptionalOptional dependency for Sentry integration to propagate correlation IDs.