ddfastapi
FastAPI helpers: dddesign error handlers and ASGI middlewares for log properties, request logging and Sentry tags
Installation
Install the library using pip:
pip install ddfastapi
Development
The project runs entirely in Docker. Requires Docker and Fabric on the host:
fab build # build the dev image
fab tests # run pytest
fab linters # run ruff (with --fix), ty and complexipy
fab shell # IPython inside the container
fab bash # bash inside the container
This project was generated from dd-lib-stub;
run uvx copier update to pull in template updates.
Compatibility
Python 3.11 to 3.15. What changed in each release, breaking changes included, is in the GitHub releases.
Depends on fastapi>=0.138,<0.166, sentry-sdk>=2.12,<4, dddesign>=2.1.2,<3, ddutils>=0.4.0,<0.5.0 and
pydantic>=2.9,<3. The tests drive the applications over ASGI, no server and no HTTP client are needed.
| Package | What is in it |
|---|---|
ddfastapi.exception_handlers |
Handlers that answer dddesign errors, HTTPException and request validation errors in one shape, Errors |
ddfastapi.middlewares |
Pure ASGI middlewares: the scope of the log properties, the request and response log, Sentry tags |
ddfastapi.utils |
What the logging middleware is made of: UrlMaskResolver, format_body |
Exception handlers
Every error leaves the application as dddesign's Errors: a list of message, error_code, status_code and
field_name.
from fastapi import FastAPI
from fastapi.exceptions import RequestValidationError
from starlette.exceptions import HTTPException
from dddesign.structure.domains.errors import BaseError, CollectionError
from ddfastapi.exception_handlers import (
handle_base_error,
handle_collection_error,
handle_http_exception,
handle_request_validation_error,
)
app = FastAPI()
app.add_exception_handler(BaseError, handle_base_error)
app.add_exception_handler(CollectionError, handle_collection_error)
app.add_exception_handler(HTTPException, handle_http_exception)
app.add_exception_handler(RequestValidationError, handle_request_validation_error)
{"errors": [{"message": "Profile 7 is not found", "error_code": "profile_not_found_error", "status_code": 404, "field_name": null}]}
| Handler | Answers | Status |
|---|---|---|
handle_base_error |
A BaseError, as one error |
The error's status_code |
handle_collection_error |
A CollectionError, every error in it |
The status of the error when there is one, 400 for several |
handle_http_exception |
An HTTPException: its detail is the message |
The exception's status_code |
handle_request_validation_error |
A RequestValidationError, an error per invalid field |
400 |
- Register
handle_http_exceptionfor Starlette'sHTTPException, as above: FastAPI's own is its subclass, and the 404 and 405 the router raises are Starlette's. Registered forfastapi.HTTPExceptiononly, those two keep FastAPI's{"detail": ...}body. - A message that comes from outside, a
detailor a validation message, is taken literally:{name}in it is text, not a placeholder ofBaseError. Adetailthat is not a string is dumped to JSON. field_nameof a validation error is the location of the field without its source (body,query,path), joined with dots:prices.1.currency.
Middlewares
All three are pure ASGI middlewares, not BaseHTTPMiddleware, so the request runs in one task and context-bound
state (a ScopedRegistry, a database session) is the same in the middleware and in the endpoint. Anything but
HTTP (websocket, lifespan) passes through untouched.
from ddfastapi.middlewares import (
LogPropertiesManagerMiddleware,
RequestResponseLoggingMiddleware,
SentryTagsMiddleware,
)
# The last added runs first: the manager creates the properties, the tags and the log read them
app.add_middleware(RequestResponseLoggingMiddleware)
app.add_middleware(SentryTagsMiddleware, log_properties_registry=log_properties_registry)
app.add_middleware(LogPropertiesManagerMiddleware, log_properties_registry=log_properties_registry)
LogPropertiesManagerMiddleware
Log properties are what every log record of one request carries: a request id, the client's address, the time
since the request started. The application declares them as a model in a ScopedRegistry from
ddutils, scoped to one execution; the middleware enters the scope for the
duration of the request, so log_properties_registry.get() returns the same object anywhere inside it, and
removes it when the request is over, failed or not.
import time
import uuid
from typing import Any
from ddutils.scoped_registry import ScopedRegistry, execution_scope
from pydantic import BaseModel, Field
class Headers(BaseModel):
ip_address: str | None = Field(None, alias='x-forwarded-for')
domain: str | None = Field(None, alias='host')
class LogProperties(BaseModel):
request_id: str = Field(default_factory=lambda: uuid.uuid4().hex)
start_time: float = Field(default_factory=time.time, exclude=True)
headers: Headers | None = None
async def create_log_properties(**kwargs: Any) -> LogProperties:
return LogProperties.model_validate(kwargs)
log_properties_registry = ScopedRegistry[LogProperties](
create_func=create_log_properties,
scope_func=execution_scope('log_properties'),
)
The properties are created with headers, the request headers as a dict of lower-case names; what the model
takes from them is up to its fields. A log formatter reads log_properties_registry.get() and adds the fields to
the record.
SentryTagsMiddleware
Tags the Sentry scope of the request with the log properties: every field of the model as a tag, nested ones
flattened with dots (headers.domain), None left out. The registry must hold a pydantic model, anything else
raises TypeError on start. Place it inside LogPropertiesManagerMiddleware.
RequestResponseLoggingMiddleware
Logs two records per request, REQUEST before the application is called and RESPONSE after it answered, each
a dict, for a JSON formatter to write as is:
{'message': 'REQUEST POST /users/42/orders', 'log_type': 'REQUEST', 'http_method': 'POST',
'url_path': '/users/42/orders', 'url_mask': '/users/<user_id>/orders', 'masked_request': 'POST /users/<user_id>/orders',
'request_data': {'name': 'book', 'amount': 2}}
{'message': 'RESPONSE POST /users/42/orders', 'log_type': 'RESPONSE', ..., 'status_code': 201,
'response_data': {'order_id': 7}}
url_maskis the route the path belongs to, so records group by route and not by id. A path no route matches is logged as is.request_datais the body of a POST, PUT or PATCH request;response_datathe body of any response. A body is always logged as an object: the parsed JSON for a JSON body (a list underitems, a scalar underraw),{'content_type': ..., 'size': ...}for anything else, a file, a stream, broken JSON.max_body_log_size(1 MB by default) is the largest body logged parsed; a larger one is logged by its content type and size. A response past the limit is not kept in memory, only measured, so a long stream is safe. A request body is read whole before the application gets it: keep uploads of large files away from this middleware or behind a limit of the server.- A failure in the application is logged as a
RESPONSEwithstatus_code500 and the traceback, and raised on. OPTIONS requests are not logged.
app.add_middleware(RequestResponseLoggingMiddleware, max_body_log_size=64 * 1024)
Utils
UrlMaskResolver(app) is built once from the routes of the application, included routers too, and resolves a
path to the mask of its route without running the router:
from ddfastapi.utils.url_mask_resolver import UrlMaskResolver
resolver = UrlMaskResolver(app)
resolver.resolve('/api/v1/users/42/orders/7') # '/api/v1/users/<user_id>/orders/<order_id>'
resolver.resolve('/nowhere') # '/nowhere'
ddfastapi.utils.body_formatter.format_body(body, content_type, max_size=...) is the rule a body is logged by,
for a log record of your own.
Metadata
Release files for ddfastapi 0.0.1
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| ddfastapi-0.0.1.tar.gz | 11.8 kB | With provenance | Details for ddfastapi-0.0.1.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| ddfastapi-0.0.1-py3-none-any.whl | Python 3 | none | any | Details for ddfastapi-0.0.1-py3-none-any.whl |
Total release size: 28.1 kB
Release files / ddfastapi-0.0.1.tar.gz
| Download URL | ddfastapi-0.0.1.tar.gz |
|---|---|
| Size | 11.8 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
e16382d5947816812a1236ae28a5787a98f3bb88cec8c012746e855f2853bdbe
|
|
BLAKE2b-256 checksum How to use checksums |
1b68fc65fedadcd199982f44f5e96677be265fc3d6807d47e6551087edad7bb9
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
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.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 28, 2026.
Transparency logRelease files / ddfastapi-0.0.1-py3-none-any.whl
| Download URL | ddfastapi-0.0.1-py3-none-any.whl |
|---|---|
| Size | 16.4 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
b0022e32e3dc9a5f49369557a709f80257ae47597c6b91c3abf732c326f61175
|
|
BLAKE2b-256 checksum How to use checksums |
77bfc92f4b03ba71b44f94908ee983978e7da7f2741ad74e37886c9b2636fc26
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
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.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 28, 2026.
Transparency logSecurity for ddfastapi 0.0.1
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.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for ddfastapi-0.0.1.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 28, 2026.
Transparency logA 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.