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
Built Distribution
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
Algorithm | Hash digest | |
---|---|---|
SHA256 | 846adc6c4692191caff7f5711fefa7df580ac543507495ef32ed2770034a9e93 |
|
MD5 | c7fdb577dabc602577da23683f7786fa |
|
BLAKE2b-256 | 547a8b9ca8a79ac443fed61e495d80e3edb2d7dbf19a0758cee06be0bff19280 |
File details
Details for the file fastapi_request_id-1.1.2-py3-none-any.whl
.
File metadata
- Download URL: fastapi_request_id-1.1.2-py3-none-any.whl
- Upload date:
- Size: 3.7 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: poetry/1.4.2 CPython/3.11.2 Darwin/22.4.0
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 1588b423371f34a975c200caf455c957ce7f0a43eabbce98551db4a7c96058cb |
|
MD5 | 6525ad042bd52352a2d7acc0fed70d55 |
|
BLAKE2b-256 | 21b9918b27a0da690c8e9f0beb74d55d56691ad19153ef8350109813fa8faccc |