Skip to main content

No project description provided

Project description

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()

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

fastapi_request_id-1.1.2.tar.gz (2.4 kB view details)

Uploaded Source

Built Distribution

fastapi_request_id-1.1.2-py3-none-any.whl (3.7 kB view details)

Uploaded Python 3

File details

Details for the file fastapi_request_id-1.1.2.tar.gz.

File metadata

  • Download URL: fastapi_request_id-1.1.2.tar.gz
  • Upload date:
  • Size: 2.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.4.2 CPython/3.11.2 Darwin/22.4.0

File hashes

Hashes for fastapi_request_id-1.1.2.tar.gz
Algorithm Hash digest
SHA256 846adc6c4692191caff7f5711fefa7df580ac543507495ef32ed2770034a9e93
MD5 c7fdb577dabc602577da23683f7786fa
BLAKE2b-256 547a8b9ca8a79ac443fed61e495d80e3edb2d7dbf19a0758cee06be0bff19280

See more details on using hashes here.

File details

Details for the file fastapi_request_id-1.1.2-py3-none-any.whl.

File metadata

File hashes

Hashes for fastapi_request_id-1.1.2-py3-none-any.whl
Algorithm Hash digest
SHA256 1588b423371f34a975c200caf455c957ce7f0a43eabbce98551db4a7c96058cb
MD5 6525ad042bd52352a2d7acc0fed70d55
BLAKE2b-256 21b9918b27a0da690c8e9f0beb74d55d56691ad19153ef8350109813fa8faccc

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page