Skip to main content

FastApi Request ID

Augments each request with unique request_id attribute and provides request id logging helpers.


Quickstart

pip install fastapi-request-id
import logging.config
from fastapi_request_id import (
    RequestContextMiddleware,
    BaseExceptionHandler,
    get_request_id,
    get_headers,
)
from fastapi import FastAPI, Request, Response
from fastapi.responses import JSONResponse
from httpx import Client


class CustomExceptionHandler(BaseExceptionHandler):

    @staticmethod
    def build_response(request: Request, exc: Exception) -> Response:
        return JSONResponse(status_code=200, content={
            'error': True,
            'request_id': get_request_id(),
        })


app = FastAPI()
app.add_middleware(RequestContextMiddleware)
app.add_exception_handler(Exception, CustomExceptionHandler())

LOGGING_CONFIG = {
    'version': 1,
    'disable_existing_loggers': True,
    'filters': {
        'RequestIdFilter': {
            '()': 'fastapi_request_id.logging.RequestIdFilter',
        },
    },
    'handlers': {
        'default': {
            'level': 'INFO',
            'class': 'logging.StreamHandler',
            "filters": [
                "RequestIdFilter"
            ]
        },
    },
    'loggers': {
        '': {
            'handlers': ['default'],
            'level': 'INFO',
            'propagate': False
        },
    }
}

logging.config.dictConfig(LOGGING_CONFIG)
logger = logging.getLogger()


@app.get('/raise')
def get_with_raise():
    raise Exception('Raised error')


@app.get('/')
def root():
    return {'request_id': get_request_id()}


@app.get('/request')
def request():
    headers = get_headers({
        'Authorization': "Bearer ...",
    })

    client = Client()
    response = client.get('http://localhost/request', headers=headers)
    return response.json()

Metadata

Release files for fastapi-request-id 1.1.2

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for fastapi-request-id 1.1.2
File Size Uploaded Provenance Actions
fastapi_request_id-1.1.2.tar.gz 2.4 kB Without provenance Details for fastapi_request_id-1.1.2.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for fastapi-request-id 1.1.2
File Interpreter ABI Platform Actions
fastapi_request_id-1.1.2-py3-none-any.whl Python 3 none any Details for fastapi_request_id-1.1.2-py3-none-any.whl

Total release size: 6.1 kB

Release files / fastapi_request_id-1.1.2.tar.gz

Download URL fastapi_request_id-1.1.2.tar.gz
Size 2.4 kB
Tags Source
SHA-256 checksum
How to use checksums
846adc6c4692191caff7f5711fefa7df580ac543507495ef32ed2770034a9e93
BLAKE2b-256 checksum
How to use checksums
547a8b9ca8a79ac443fed61e495d80e3edb2d7dbf19a0758cee06be0bff19280
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/1.4.2 CPython/3.11.2 Darwin/22.4.0

Release files / fastapi_request_id-1.1.2-py3-none-any.whl

Download URL fastapi_request_id-1.1.2-py3-none-any.whl
Size 3.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
1588b423371f34a975c200caf455c957ce7f0a43eabbce98551db4a7c96058cb
BLAKE2b-256 checksum
How to use checksums
21b9918b27a0da690c8e9f0beb74d55d56691ad19153ef8350109813fa8faccc
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/1.4.2 CPython/3.11.2 Darwin/22.4.0

Security for fastapi-request-id 1.1.2

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page