Metadata-Version: 2.4
Name: ddfastapi
Version: 0.0.1
Summary: FastAPI helpers: dddesign error handlers and ASGI middlewares for log properties, request logging and Sentry tags
Keywords: python,ddfastapi,fastapi,starlette,asgi,middleware,logging,request logging,exception handlers,sentry,dddesign
Author: davyddd
License-Expression: MIT
License-File: LICENSE
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Programming Language :: Python :: 3.15
Classifier: Typing :: Typed
Requires-Dist: dddesign>=2.1.2,<3
Requires-Dist: ddutils>=0.4.0,<0.5.0
Requires-Dist: fastapi>=0.138,<0.166
Requires-Dist: pydantic>=2.9,<3
Requires-Dist: sentry-sdk>=2.12,<4
Requires-Python: >=3.11, <3.16
Project-URL: Repository, https://github.com/davyddd/ddfastapi
Description-Content-Type: text/markdown

# ddfastapi

[![pypi](https://img.shields.io/pypi/v/ddfastapi.svg)](https://pypi.python.org/pypi/ddfastapi)
[![downloads](https://static.pepy.tech/badge/ddfastapi/month)](https://pepy.tech/project/ddfastapi)
[![versions](https://img.shields.io/pypi/pyversions/ddfastapi.svg)](https://github.com/davyddd/ddfastapi)
[![codecov](https://codecov.io/gh/davyddd/ddfastapi/branch/main/graph/badge.svg)](https://app.codecov.io/github/davyddd/ddfastapi)
[![license](https://img.shields.io/github/license/davyddd/ddfastapi.svg)](https://github.com/davyddd/ddfastapi/blob/main/LICENSE)

FastAPI helpers: dddesign error handlers and ASGI middlewares for log properties, request logging and Sentry tags

## Installation

Install the library using pip:
```bash
pip install ddfastapi
```

## Development

The project runs entirely in Docker. Requires Docker and [Fabric](https://www.fabfile.org/) on the host:

```bash
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](https://github.com/davyddd/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](https://github.com/davyddd/ddfastapi/releases).

<!-- The sections below are the library's own; copier update leaves them alone -->

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](https://github.com/davyddd/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`.

```python
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)
```

```json
{"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_exception` for Starlette's `HTTPException`, as above: FastAPI's own is its subclass, and
  the 404 and 405 the router raises are Starlette's. Registered for `fastapi.HTTPException` only, those two keep
  FastAPI's `{"detail": ...}` body.
- A message that comes from outside, a `detail` or a validation message, is taken literally: `{name}` in it is
  text, not a placeholder of `BaseError`. A `detail` that is not a string is dumped to JSON.
- `field_name` of 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.

```python
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](https://github.com/davyddd/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.

```python
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:

```python
{'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_mask` is 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_data` is the body of a POST, PUT or PATCH request; `response_data` the body of any response. A body is
  always logged as an object: the parsed JSON for a JSON body (a list under `items`, a scalar under `raw`),
  `{'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 `RESPONSE` with `status_code` 500 and the traceback, and raised
  on. OPTIONS requests are not logged.

```python
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:

```python
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.
