fastapi-custom-responses 0.2.0__tar.gz → 0.3.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: fastapi-custom-responses
3
- Version: 0.2.0
3
+ Version: 0.3.0
4
4
  Summary: Normalized response envelopes and error handling for FastAPI applications.
5
5
  License: MIT
6
6
  Author: Julien Kmec
@@ -32,7 +32,7 @@ Provides normalized response objects and error handling for FastAPI applications
32
32
  - One error envelope for every failure: validation, `HTTPException`, `ValueError`, and unhandled exceptions.
33
33
  - Pydantic validation errors rewritten as human-readable messages instead of raw error arrays.
34
34
  - A stable `code` naming the condition, typed as an enum.
35
- - `fastapi_responses` to build FastAPI's `responses` mapping, documenting your codes in OpenAPI.
35
+ - Native FastAPI response declarations for error codes, descriptions, examples, headers, media types and links.
36
36
  - Generic `Response[T]`, `SuccessResponse`, and `PaginatedResponse[T]` envelopes for success payloads.
37
37
  - `ErrorResponseModel` as both the error body the handlers emit and the schema documenting it.
38
38
  - `ErrorResponse.from_status_code` for an error carrying a status's standard HTTP phrase.
@@ -50,7 +50,8 @@ from fastapi_custom_responses import (
50
50
  DefaultErrorCode,
51
51
  ErrorResponse,
52
52
  Response,
53
- fastapi_responses,
53
+ ErrorResponseModel,
54
+ EXCEPTION_RESPONSES,
54
55
  )
55
56
  from fastapi import APIRouter, FastAPI
56
57
  from enum import StrEnum
@@ -63,6 +64,7 @@ app = FastAPI(
63
64
  description="My API",
64
65
  version="1.0.0",
65
66
  exception_handlers=EXCEPTION_HANDLERS,
67
+ responses=EXCEPTION_RESPONSES,
66
68
  )
67
69
 
68
70
  class Data(BaseModel):
@@ -74,11 +76,9 @@ class OrderErrorCode(StrEnum):
74
76
 
75
77
  @router.get(
76
78
  "/",
79
+ operation_id="read_example",
77
80
  response_model=Response[Data],
78
- responses=fastapi_responses({
79
- HTTPStatus.FORBIDDEN: OrderErrorCode,
80
- HTTPStatus.INTERNAL_SERVER_ERROR: DefaultErrorCode,
81
- }),
81
+ responses={HTTPStatus.FORBIDDEN: {"model": ErrorResponseModel[OrderErrorCode]}},
82
82
  )
83
83
  async def index() -> Response[Data]:
84
84
  """Index route."""
@@ -90,7 +90,7 @@ async def index() -> Response[Data]:
90
90
 
91
91
  @router.get(
92
92
  "/return-error",
93
- responses=fastapi_responses({HTTPStatus.FORBIDDEN: OrderErrorCode}),
93
+ responses={HTTPStatus.FORBIDDEN: {"model": ErrorResponseModel[OrderErrorCode]}},
94
94
  )
95
95
  async def error_route() -> Response[Data]:
96
96
  """Error route."""
@@ -100,6 +100,8 @@ async def error_route() -> Response[Data]:
100
100
  status_code=HTTPStatus.FORBIDDEN,
101
101
  code=OrderErrorCode.ORDER_LOCKED,
102
102
  )
103
+
104
+ app.include_router(router)
103
105
  ```
104
106
 
105
107
  ## Response Envelopes
@@ -124,9 +126,9 @@ Register the handlers when you create the app:
124
126
 
125
127
  ```py
126
128
  from fastapi import FastAPI
127
- from fastapi_custom_responses import EXCEPTION_HANDLERS
129
+ from fastapi_custom_responses import EXCEPTION_HANDLERS, EXCEPTION_RESPONSES
128
130
 
129
- app = FastAPI(exception_handlers=EXCEPTION_HANDLERS)
131
+ app = FastAPI(exception_handlers=EXCEPTION_HANDLERS, responses=EXCEPTION_RESPONSES)
130
132
  ```
131
133
 
132
134
  Every error then normalizes into one JSON shape:
@@ -266,37 +268,70 @@ raise ErrorResponse.from_status_code(HTTPStatus.FORBIDDEN, code=OrderErrorCode.O
266
268
 
267
269
  ## Documenting Responses
268
270
 
269
- `fastapi_responses` builds FastAPI's `responses` mapping. Give it an error code enum, a union of enums, `None` for the bare error envelope, or a success envelope:
271
+ Use FastAPI's native `response_model` for the main success response and `responses` for additional responses:
270
272
 
271
273
  ```py
272
- from fastapi_custom_responses import DefaultErrorCode, Response, SuccessResponse, fastapi_responses
274
+ from typing import Literal
275
+ from fastapi_custom_responses import ErrorResponseModel, Response
273
276
 
274
277
  @router.post(
275
278
  "/reports",
276
- responses=fastapi_responses({
277
- HTTPStatus.CREATED: Response[Report],
278
- HTTPStatus.ACCEPTED: SuccessResponse,
279
- HTTPStatus.BAD_REQUEST: DefaultErrorCode,
280
- HTTPStatus.FORBIDDEN: OrderErrorCode,
281
- HTTPStatus.NOT_FOUND: None,
282
- }),
279
+ status_code=HTTPStatus.CREATED,
280
+ response_model=Response[Data],
281
+ responses={
282
+ HTTPStatus.FORBIDDEN: {
283
+ "model": ErrorResponseModel[Literal[OrderErrorCode.ORDER_LOCKED]],
284
+ "description": "This order is locked",
285
+ "headers": {"Retry-After": {"schema": {"type": "integer"}}},
286
+ "content": {
287
+ "application/json": {
288
+ "examples": {"locked": {"value": {
289
+ "success": False,
290
+ "error": "This order is locked",
291
+ "code": "order_locked",
292
+ }}}
293
+ },
294
+ "text/plain": {"schema": {"type": "string"}},
295
+ },
296
+ "links": {"example": {"operationId": "read_example"}},
297
+ },
298
+ },
283
299
  )
300
+ async def reports() -> Response[Data]:
301
+ return Response(success=True, data=Data(example="hello"))
284
302
  ```
285
303
 
286
- Each error code enum becomes its own named schema in the OpenAPI document, so generated clients get a real union type per domain rather than a bare string:
304
+ An entire enum can be used as `ErrorResponseModel[OrderErrorCode]`. Union enum types to document
305
+ several domains, or use `Literal[OrderErrorCode.ORDER_LOCKED, DefaultErrorCode.INVALID_VALUE]` to
306
+ select individual members. Pydantic produces the selected-value schema and rejects other values
307
+ when that model validates a body. The `code` field remains optional and nullable.
287
308
 
288
- ```json
289
- "OrderErrorCode": { "type": "string", "enum": ["order_locked", "payment_declined"], "title": "OrderErrorCode" }
290
- ```
309
+ FastAPI accepts integer response codes, `HTTPStatus` values, status ranges such as `"4XX"`, and
310
+ `"default"`. Keep metadata and the model in the same response entry: replacing an entry with
311
+ `{403: {"description": "..."}}` also discards its model. Native response declarations preserve
312
+ these fields together without a separate conversion helper.
291
313
 
292
- `400` and `500` are answered by the library's own handlers, so document `DefaultErrorCode` there. Where a status carries your codes as well as theirs, union the two — `OrderErrorCode | DefaultErrorCode` — so the schema lists every value that status can emit.
314
+ `response_model` validates and serializes the main response. Additional `responses` declarations
315
+ only document alternatives; they do not validate a body returned by an exception handler or a
316
+ `Response` object. The handler remains responsible for emitting the documented code.
293
317
 
294
- FastAPI describes each entry with its status phrase. Entries needing `headers`, custom media types, or `links` are written directly and merge with the result:
318
+ ### Handler Documentation
319
+
320
+ Configure the matching native declarations alongside the handlers:
295
321
 
296
322
  ```py
297
- responses={**fastapi_responses({HTTPStatus.FORBIDDEN: OrderErrorCode}), HTTPStatus.NOT_MODIFIED: {"headers": {...}}}
323
+ app = FastAPI(exception_handlers=EXCEPTION_HANDLERS, responses=EXCEPTION_RESPONSES)
298
324
  ```
299
325
 
326
+ `EXCEPTION_RESPONSES` documents the handlers' `400` and `500` models and the general `4XX`/`5XX`
327
+ error envelopes. FastAPI's native `4XX` declaration suppresses its automatic standard `422`
328
+ validation response, matching this package's runtime `400` envelope. Explicitly declared `422`
329
+ responses are preserved. Register both mappings before adding routes; registering handlers alone
330
+ does not change FastAPI's OpenAPI document.
331
+
332
+ Route and router response declarations override matching application entries. When a route raises
333
+ its own codes at `400` or `500`, document the union of its codes and the handler codes there.
334
+
300
335
  ## Local Development
301
336
 
302
337
  Install the project with its development dependencies:
@@ -7,7 +7,7 @@ Provides normalized response objects and error handling for FastAPI applications
7
7
  - One error envelope for every failure: validation, `HTTPException`, `ValueError`, and unhandled exceptions.
8
8
  - Pydantic validation errors rewritten as human-readable messages instead of raw error arrays.
9
9
  - A stable `code` naming the condition, typed as an enum.
10
- - `fastapi_responses` to build FastAPI's `responses` mapping, documenting your codes in OpenAPI.
10
+ - Native FastAPI response declarations for error codes, descriptions, examples, headers, media types and links.
11
11
  - Generic `Response[T]`, `SuccessResponse`, and `PaginatedResponse[T]` envelopes for success payloads.
12
12
  - `ErrorResponseModel` as both the error body the handlers emit and the schema documenting it.
13
13
  - `ErrorResponse.from_status_code` for an error carrying a status's standard HTTP phrase.
@@ -25,7 +25,8 @@ from fastapi_custom_responses import (
25
25
  DefaultErrorCode,
26
26
  ErrorResponse,
27
27
  Response,
28
- fastapi_responses,
28
+ ErrorResponseModel,
29
+ EXCEPTION_RESPONSES,
29
30
  )
30
31
  from fastapi import APIRouter, FastAPI
31
32
  from enum import StrEnum
@@ -38,6 +39,7 @@ app = FastAPI(
38
39
  description="My API",
39
40
  version="1.0.0",
40
41
  exception_handlers=EXCEPTION_HANDLERS,
42
+ responses=EXCEPTION_RESPONSES,
41
43
  )
42
44
 
43
45
  class Data(BaseModel):
@@ -49,11 +51,9 @@ class OrderErrorCode(StrEnum):
49
51
 
50
52
  @router.get(
51
53
  "/",
54
+ operation_id="read_example",
52
55
  response_model=Response[Data],
53
- responses=fastapi_responses({
54
- HTTPStatus.FORBIDDEN: OrderErrorCode,
55
- HTTPStatus.INTERNAL_SERVER_ERROR: DefaultErrorCode,
56
- }),
56
+ responses={HTTPStatus.FORBIDDEN: {"model": ErrorResponseModel[OrderErrorCode]}},
57
57
  )
58
58
  async def index() -> Response[Data]:
59
59
  """Index route."""
@@ -65,7 +65,7 @@ async def index() -> Response[Data]:
65
65
 
66
66
  @router.get(
67
67
  "/return-error",
68
- responses=fastapi_responses({HTTPStatus.FORBIDDEN: OrderErrorCode}),
68
+ responses={HTTPStatus.FORBIDDEN: {"model": ErrorResponseModel[OrderErrorCode]}},
69
69
  )
70
70
  async def error_route() -> Response[Data]:
71
71
  """Error route."""
@@ -75,6 +75,8 @@ async def error_route() -> Response[Data]:
75
75
  status_code=HTTPStatus.FORBIDDEN,
76
76
  code=OrderErrorCode.ORDER_LOCKED,
77
77
  )
78
+
79
+ app.include_router(router)
78
80
  ```
79
81
 
80
82
  ## Response Envelopes
@@ -99,9 +101,9 @@ Register the handlers when you create the app:
99
101
 
100
102
  ```py
101
103
  from fastapi import FastAPI
102
- from fastapi_custom_responses import EXCEPTION_HANDLERS
104
+ from fastapi_custom_responses import EXCEPTION_HANDLERS, EXCEPTION_RESPONSES
103
105
 
104
- app = FastAPI(exception_handlers=EXCEPTION_HANDLERS)
106
+ app = FastAPI(exception_handlers=EXCEPTION_HANDLERS, responses=EXCEPTION_RESPONSES)
105
107
  ```
106
108
 
107
109
  Every error then normalizes into one JSON shape:
@@ -241,37 +243,70 @@ raise ErrorResponse.from_status_code(HTTPStatus.FORBIDDEN, code=OrderErrorCode.O
241
243
 
242
244
  ## Documenting Responses
243
245
 
244
- `fastapi_responses` builds FastAPI's `responses` mapping. Give it an error code enum, a union of enums, `None` for the bare error envelope, or a success envelope:
246
+ Use FastAPI's native `response_model` for the main success response and `responses` for additional responses:
245
247
 
246
248
  ```py
247
- from fastapi_custom_responses import DefaultErrorCode, Response, SuccessResponse, fastapi_responses
249
+ from typing import Literal
250
+ from fastapi_custom_responses import ErrorResponseModel, Response
248
251
 
249
252
  @router.post(
250
253
  "/reports",
251
- responses=fastapi_responses({
252
- HTTPStatus.CREATED: Response[Report],
253
- HTTPStatus.ACCEPTED: SuccessResponse,
254
- HTTPStatus.BAD_REQUEST: DefaultErrorCode,
255
- HTTPStatus.FORBIDDEN: OrderErrorCode,
256
- HTTPStatus.NOT_FOUND: None,
257
- }),
254
+ status_code=HTTPStatus.CREATED,
255
+ response_model=Response[Data],
256
+ responses={
257
+ HTTPStatus.FORBIDDEN: {
258
+ "model": ErrorResponseModel[Literal[OrderErrorCode.ORDER_LOCKED]],
259
+ "description": "This order is locked",
260
+ "headers": {"Retry-After": {"schema": {"type": "integer"}}},
261
+ "content": {
262
+ "application/json": {
263
+ "examples": {"locked": {"value": {
264
+ "success": False,
265
+ "error": "This order is locked",
266
+ "code": "order_locked",
267
+ }}}
268
+ },
269
+ "text/plain": {"schema": {"type": "string"}},
270
+ },
271
+ "links": {"example": {"operationId": "read_example"}},
272
+ },
273
+ },
258
274
  )
275
+ async def reports() -> Response[Data]:
276
+ return Response(success=True, data=Data(example="hello"))
259
277
  ```
260
278
 
261
- Each error code enum becomes its own named schema in the OpenAPI document, so generated clients get a real union type per domain rather than a bare string:
279
+ An entire enum can be used as `ErrorResponseModel[OrderErrorCode]`. Union enum types to document
280
+ several domains, or use `Literal[OrderErrorCode.ORDER_LOCKED, DefaultErrorCode.INVALID_VALUE]` to
281
+ select individual members. Pydantic produces the selected-value schema and rejects other values
282
+ when that model validates a body. The `code` field remains optional and nullable.
262
283
 
263
- ```json
264
- "OrderErrorCode": { "type": "string", "enum": ["order_locked", "payment_declined"], "title": "OrderErrorCode" }
265
- ```
284
+ FastAPI accepts integer response codes, `HTTPStatus` values, status ranges such as `"4XX"`, and
285
+ `"default"`. Keep metadata and the model in the same response entry: replacing an entry with
286
+ `{403: {"description": "..."}}` also discards its model. Native response declarations preserve
287
+ these fields together without a separate conversion helper.
266
288
 
267
- `400` and `500` are answered by the library's own handlers, so document `DefaultErrorCode` there. Where a status carries your codes as well as theirs, union the two — `OrderErrorCode | DefaultErrorCode` — so the schema lists every value that status can emit.
289
+ `response_model` validates and serializes the main response. Additional `responses` declarations
290
+ only document alternatives; they do not validate a body returned by an exception handler or a
291
+ `Response` object. The handler remains responsible for emitting the documented code.
268
292
 
269
- FastAPI describes each entry with its status phrase. Entries needing `headers`, custom media types, or `links` are written directly and merge with the result:
293
+ ### Handler Documentation
294
+
295
+ Configure the matching native declarations alongside the handlers:
270
296
 
271
297
  ```py
272
- responses={**fastapi_responses({HTTPStatus.FORBIDDEN: OrderErrorCode}), HTTPStatus.NOT_MODIFIED: {"headers": {...}}}
298
+ app = FastAPI(exception_handlers=EXCEPTION_HANDLERS, responses=EXCEPTION_RESPONSES)
273
299
  ```
274
300
 
301
+ `EXCEPTION_RESPONSES` documents the handlers' `400` and `500` models and the general `4XX`/`5XX`
302
+ error envelopes. FastAPI's native `4XX` declaration suppresses its automatic standard `422`
303
+ validation response, matching this package's runtime `400` envelope. Explicitly declared `422`
304
+ responses are preserved. Register both mappings before adding routes; registering handlers alone
305
+ does not change FastAPI's OpenAPI document.
306
+
307
+ Route and router response declarations override matching application entries. When a route raises
308
+ its own codes at `400` or `500`, document the union of its codes and the handler codes there.
309
+
275
310
  ## Local Development
276
311
 
277
312
  Install the project with its development dependencies:
@@ -1,13 +1,12 @@
1
1
  from .errors import (
2
2
  EXCEPTION_HANDLERS,
3
- DefaultErrorCode,
3
+ EXCEPTION_RESPONSES,
4
4
  ErrorResponse,
5
- ErrorResponseModel,
6
- fastapi_responses,
7
5
  )
8
- from .responses import PaginatedResponse, PaginationMeta, Response, SuccessResponse
6
+ from .models.errors import DefaultErrorCode, ErrorResponseModel
7
+ from .models.responses import PaginatedResponse, PaginationMeta, Response, SuccessResponse
9
8
 
10
- __all__ = [
9
+ __all__: list[str] = [
11
10
  "EXCEPTION_HANDLERS",
12
11
  "DefaultErrorCode",
13
12
  "ErrorResponse",
@@ -16,5 +15,5 @@ __all__ = [
16
15
  "PaginationMeta",
17
16
  "Response",
18
17
  "SuccessResponse",
19
- "fastapi_responses",
18
+ "EXCEPTION_RESPONSES",
20
19
  ]
@@ -0,0 +1,220 @@
1
+ import logging
2
+ from collections.abc import Callable, Mapping
3
+ from enum import StrEnum
4
+ from http import HTTPStatus
5
+ from typing import Final, Literal, Self
6
+
7
+ from fastapi import Request
8
+ from fastapi.exceptions import RequestValidationError
9
+ from fastapi.responses import JSONResponse
10
+ from pydantic import BaseModel, ValidationError
11
+ from pydantic_core import ErrorDetails
12
+ from starlette.exceptions import HTTPException
13
+
14
+ from fastapi_custom_responses.models.errors import (
15
+ ConstraintRule,
16
+ DefaultErrorCode,
17
+ ErrorResponseModel,
18
+ )
19
+
20
+ logger: logging.Logger = logging.getLogger(__name__)
21
+
22
+ SIMPLE_TYPE_MESSAGES: Final[dict[str, str]] = {
23
+ "missing": "is required",
24
+ "string_type": "must be a string",
25
+ "int_type": "must be a valid integer",
26
+ "int_parsing": "must be a valid integer",
27
+ "float_type": "must be a valid number",
28
+ "float_parsing": "must be a valid number",
29
+ "bool_type": "must be a boolean",
30
+ "bool_parsing": "must be a boolean",
31
+ "uuid_type": "must be a valid UUID",
32
+ "uuid_parsing": "must be a valid UUID",
33
+ }
34
+
35
+
36
+ CONSTRAINT_RULES: Final[dict[str, ConstraintRule]] = {
37
+ "string_too_short": ConstraintRule(
38
+ ctx_key="min_length", template="must be at least {value} characters", fallback="is too short"
39
+ ),
40
+ "string_too_long": ConstraintRule(
41
+ ctx_key="max_length", template="must be at most {value} characters", fallback="is too long"
42
+ ),
43
+ "too_short": ConstraintRule(
44
+ ctx_key="min_length",
45
+ template="must have at least {value} {unit}",
46
+ fallback="has too few items",
47
+ ),
48
+ "too_long": ConstraintRule(
49
+ ctx_key="max_length",
50
+ template="must have at most {value} {unit}",
51
+ fallback="has too many items",
52
+ ),
53
+ "greater_than": ConstraintRule(
54
+ ctx_key="gt", template="must be greater than {value}", fallback="has an invalid value"
55
+ ),
56
+ "greater_than_equal": ConstraintRule(
57
+ ctx_key="ge", template="must be at least {value}", fallback="has an invalid value"
58
+ ),
59
+ "less_than": ConstraintRule(
60
+ ctx_key="lt", template="must be less than {value}", fallback="has an invalid value"
61
+ ),
62
+ "less_than_equal": ConstraintRule(
63
+ ctx_key="le", template="must be at most {value}", fallback="has an invalid value"
64
+ ),
65
+ "enum": ConstraintRule(
66
+ ctx_key="expected", template="must be one of: {value}", fallback="has an invalid value"
67
+ ),
68
+ }
69
+
70
+
71
+ EXCEPTION_RESPONSES: Final[dict[int | str, dict[Literal["model"], type[BaseModel]]]] = {
72
+ "4XX": {"model": ErrorResponseModel},
73
+ "5XX": {"model": ErrorResponseModel},
74
+ HTTPStatus.BAD_REQUEST: {
75
+ "model": ErrorResponseModel[
76
+ Literal[DefaultErrorCode.VALIDATION_ERROR, DefaultErrorCode.INVALID_VALUE]
77
+ ]
78
+ },
79
+ HTTPStatus.INTERNAL_SERVER_ERROR: {"model": ErrorResponseModel[Literal[DefaultErrorCode.INTERNAL_ERROR]]},
80
+ }
81
+
82
+
83
+ class ErrorResponse(Exception):
84
+ """Normalized application error."""
85
+
86
+ def __init__(
87
+ self,
88
+ error: str,
89
+ status_code: HTTPStatus = HTTPStatus.BAD_REQUEST,
90
+ *,
91
+ code: StrEnum | None = None,
92
+ ) -> None:
93
+ """Application error fields."""
94
+
95
+ self.error = error
96
+ self.status_code = status_code
97
+ self.code = code
98
+
99
+ super().__init__(error)
100
+
101
+ @classmethod
102
+ def from_status_code(cls, status_code: HTTPStatus, *, code: StrEnum | None = None) -> Self:
103
+ """Application error with a standard status phrase."""
104
+
105
+ return cls(error=status_code.phrase, status_code=status_code, code=code)
106
+
107
+
108
+ def format_field_location(loc: tuple[int | str, ...]) -> str:
109
+ """Validation field location."""
110
+
111
+ field_loc = loc[1:] if loc and loc[0] in ("body", "query", "path", "header") else loc
112
+ field_parts = [str(part) for part in field_loc]
113
+
114
+ if not field_parts:
115
+ return str(loc[-1]) if loc else "field"
116
+
117
+ return ".".join(field_parts)
118
+
119
+
120
+ def format_single_error(error: ErrorDetails) -> str:
121
+ """Validation error message."""
122
+
123
+ field = format_field_location(error["loc"])
124
+ error_type = error["type"]
125
+ msg = error["msg"]
126
+ ctx = error.get("ctx", {})
127
+
128
+ if error_type in SIMPLE_TYPE_MESSAGES:
129
+ return f"Field '{field}' {SIMPLE_TYPE_MESSAGES[error_type]}"
130
+
131
+ rule = CONSTRAINT_RULES.get(error_type)
132
+
133
+ if rule is not None:
134
+ return rule.format_error(field, ctx)
135
+
136
+ match error_type:
137
+ case "value_error":
138
+ # Pydantic prefixes with "Value error, " -- strip it
139
+ return msg.removeprefix("Value error, ")
140
+ case "json_invalid":
141
+ return "Invalid JSON in request body"
142
+ case _:
143
+ if msg:
144
+ return f"Field '{field}': {msg}"
145
+
146
+ return f"Field '{field}' is invalid"
147
+
148
+
149
+ def format_validation_errors(exc: RequestValidationError) -> str:
150
+ """Combined validation errors."""
151
+
152
+ errors = exc.errors()
153
+
154
+ if not errors:
155
+ return HTTPStatus.BAD_REQUEST.phrase
156
+
157
+ return ". ".join(format_single_error(error) for error in errors)
158
+
159
+
160
+ def error_json_response(
161
+ status_code: int, error: str, code: str | None, headers: Mapping[str, str] | None = None
162
+ ) -> JSONResponse:
163
+ """Normalized error JSON response."""
164
+
165
+ response = ErrorResponseModel(success=False, error=error, code=code)
166
+
167
+ content = response.model_dump(mode="json", exclude_none=True)
168
+
169
+ return JSONResponse(status_code=status_code, content=content, headers=headers)
170
+
171
+
172
+ def exception_handler(_: Request, exc: Exception) -> JSONResponse:
173
+ """FastAPI exception callback."""
174
+
175
+ status_code: int = HTTPStatus.INTERNAL_SERVER_ERROR
176
+ error = HTTPStatus.INTERNAL_SERVER_ERROR.phrase
177
+ code: str | None = DefaultErrorCode.INTERNAL_ERROR
178
+ headers: Mapping[str, str] | None = None
179
+
180
+ match exc:
181
+ case RequestValidationError():
182
+ logger.warning("Validation error: %s", exc.errors())
183
+
184
+ status_code = HTTPStatus.BAD_REQUEST
185
+ error = format_validation_errors(exc)
186
+ code = DefaultErrorCode.VALIDATION_ERROR
187
+ case ErrorResponse():
188
+ logger.info("ErrorResponse: %s - %s", exc.status_code, exc.error)
189
+
190
+ status_code = exc.status_code
191
+ error = exc.error
192
+ code = exc.code
193
+ case HTTPException():
194
+ status_code = exc.status_code
195
+ error = str(exc.detail)
196
+ code = None
197
+ headers = exc.headers
198
+ case ValueError() if not isinstance(exc, ValidationError):
199
+ logger.exception(exc)
200
+
201
+ status_code = HTTPStatus.BAD_REQUEST
202
+ error = str(exc)
203
+ code = DefaultErrorCode.INVALID_VALUE
204
+ case _:
205
+ logger.exception(exc)
206
+
207
+ return error_json_response(status_code, error, code, headers=headers)
208
+
209
+
210
+ EXCEPTION_HANDLERS: Final[dict[type[Exception], Callable[[Request, Exception], JSONResponse]]] = {
211
+ exception_type: exception_handler
212
+ for exception_type in (
213
+ HTTPException,
214
+ RequestValidationError,
215
+ ValidationError,
216
+ ValueError,
217
+ ErrorResponse,
218
+ Exception,
219
+ )
220
+ }
@@ -0,0 +1,44 @@
1
+ from collections.abc import Mapping
2
+ from enum import StrEnum
3
+ from typing import Literal
4
+
5
+ from pydantic import BaseModel
6
+
7
+
8
+ class DefaultErrorCode(StrEnum):
9
+ """Codes for the conditions the library's own handlers detect."""
10
+
11
+ VALIDATION_ERROR = "validation_error"
12
+ INVALID_VALUE = "invalid_value"
13
+ INTERNAL_ERROR = "internal_error"
14
+
15
+
16
+ class ErrorResponseModel[CodeT: str](BaseModel):
17
+ """Error response envelope."""
18
+
19
+ success: Literal[False]
20
+ error: str
21
+ code: CodeT | None = None
22
+
23
+
24
+ class ConstraintRule(BaseModel):
25
+ """Constraint message rule."""
26
+
27
+ ctx_key: str
28
+ template: str
29
+ fallback: str
30
+
31
+ def format_error(self, field: str, ctx: Mapping[str, object]) -> str:
32
+ """Human-readable constraint violation."""
33
+
34
+ value = ctx.get(self.ctx_key)
35
+
36
+ if value is None:
37
+ return f"Field '{field}' {self.fallback}"
38
+
39
+ if isinstance(value, float) and value.is_integer():
40
+ value = int(value)
41
+
42
+ unit = "item" if value == 1 else "items"
43
+
44
+ return f"Field '{field}' {self.template.format(value=value, unit=unit)}"
@@ -31,7 +31,7 @@ class PaginatedResponse[T](Response[list[T]]):
31
31
 
32
32
  @classmethod
33
33
  def build_page(cls, items: list[T], *, offset: int, limit: int, total: int) -> Self:
34
- """Build a paginated response from a page of items and the bounds it was read with."""
34
+ """Paginated response with its page bounds."""
35
35
 
36
36
  return cls(
37
37
  success=True,
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "fastapi-custom-responses"
3
- version = "0.2.0"
3
+ version = "0.3.0"
4
4
  description = "Normalized response envelopes and error handling for FastAPI applications."
5
5
  authors = [
6
6
  { name = "Julien Kmec", email = "me@julien.dev" },
@@ -1,261 +0,0 @@
1
- import logging
2
- from collections.abc import Callable, Mapping
3
- from enum import StrEnum
4
- from http import HTTPStatus
5
- from types import UnionType
6
- from typing import Any, Final, Literal, Self
7
-
8
- from fastapi import Request
9
- from fastapi.exceptions import RequestValidationError, StarletteHTTPException
10
- from fastapi.responses import JSONResponse
11
- from pydantic import BaseModel, ValidationError
12
-
13
- logger = logging.getLogger(__name__)
14
-
15
- SIMPLE_TYPE_MESSAGES: Final[dict[str, str]] = {
16
- "missing": "is required",
17
- "string_type": "must be a string",
18
- "int_type": "must be a valid integer",
19
- "int_parsing": "must be a valid integer",
20
- "float_type": "must be a valid number",
21
- "float_parsing": "must be a valid number",
22
- "bool_type": "must be a boolean",
23
- "bool_parsing": "must be a boolean",
24
- "uuid_type": "must be a valid UUID",
25
- "uuid_parsing": "must be a valid UUID",
26
- }
27
-
28
- type ResponseSpec = type[StrEnum] | type[BaseModel] | UnionType | None
29
-
30
-
31
- class DefaultErrorCode(StrEnum):
32
- """Codes for the conditions the library's own handlers detect."""
33
-
34
- VALIDATION_ERROR = "validation_error"
35
- INVALID_VALUE = "invalid_value"
36
- INTERNAL_ERROR = "internal_error"
37
-
38
-
39
- class ErrorResponseModel[CodeT: str](BaseModel):
40
- """Body every error response carries, and the schema documenting it in OpenAPI."""
41
-
42
- success: Literal[False]
43
- error: str
44
- code: CodeT | None = None
45
-
46
-
47
- class ErrorResponse(Exception):
48
- """Exception carrying the message, status code, and code to render as an error response."""
49
-
50
- def __init__(
51
- self,
52
- error: str,
53
- status_code: HTTPStatus = HTTPStatus.BAD_REQUEST,
54
- *,
55
- code: StrEnum | None = None,
56
- ) -> None:
57
- """Initialize error response with message, status code, and error code."""
58
-
59
- self.error = error
60
- self.status_code = status_code
61
- self.code = code
62
-
63
- super().__init__(error)
64
-
65
- @classmethod
66
- def from_status_code(cls, status_code: HTTPStatus, *, code: StrEnum | None = None) -> Self:
67
- """Create an error response carrying the standard phrase for a status code."""
68
-
69
- return cls(error=status_code.phrase, status_code=status_code, code=code)
70
-
71
-
72
- def format_field_location(loc: tuple[int | str, ...]) -> str:
73
- """Extract the field name from a validation error location tuple."""
74
-
75
- field_parts = [str(part) for part in loc if part not in ("body", "query", "path", "header")]
76
-
77
- if not field_parts:
78
- return str(loc[-1]) if loc else "field"
79
-
80
- return ".".join(field_parts)
81
-
82
-
83
- def format_constraint_value(value: int | float | str) -> str:
84
- """Format a constraint value for display, stripping unnecessary '.0' from whole floats."""
85
-
86
- if isinstance(value, float) and value.is_integer():
87
- return str(int(value))
88
-
89
- return str(value)
90
-
91
-
92
- class ConstraintRule(BaseModel):
93
- """Maps a Pydantic constraint error type to its `ctx` key, message template, and fallback."""
94
-
95
- ctx_key: str
96
- template: str
97
- fallback: str
98
-
99
-
100
- CONSTRAINT_RULES: Final[dict[str, ConstraintRule]] = {
101
- "string_too_short": ConstraintRule(
102
- ctx_key="min_length", template="must be at least {value} characters", fallback="is too short"
103
- ),
104
- "string_too_long": ConstraintRule(
105
- ctx_key="max_length", template="must be at most {value} characters", fallback="is too long"
106
- ),
107
- "too_short": ConstraintRule(
108
- ctx_key="min_length",
109
- template="must have at least {value} {unit}",
110
- fallback="has too few items",
111
- ),
112
- "too_long": ConstraintRule(
113
- ctx_key="max_length",
114
- template="must have at most {value} {unit}",
115
- fallback="has too many items",
116
- ),
117
- "greater_than": ConstraintRule(
118
- ctx_key="gt", template="must be greater than {value}", fallback="has an invalid value"
119
- ),
120
- "greater_than_equal": ConstraintRule(
121
- ctx_key="ge", template="must be at least {value}", fallback="has an invalid value"
122
- ),
123
- "less_than": ConstraintRule(
124
- ctx_key="lt", template="must be less than {value}", fallback="has an invalid value"
125
- ),
126
- "less_than_equal": ConstraintRule(
127
- ctx_key="le", template="must be at most {value}", fallback="has an invalid value"
128
- ),
129
- "enum": ConstraintRule(
130
- ctx_key="expected", template="must be one of: {value}", fallback="has an invalid value"
131
- ),
132
- }
133
-
134
-
135
- def format_constraint_error(field: str, ctx: dict[str, Any], rule: ConstraintRule) -> str:
136
- """Format a constraint violation from its rule, falling back when the bound is absent from ctx."""
137
-
138
- value = ctx.get(rule.ctx_key)
139
- if value is None:
140
- return f"Field '{field}' {rule.fallback}"
141
-
142
- unit = "item" if value == 1 else "items"
143
-
144
- return f"Field '{field}' {rule.template.format(value=format_constraint_value(value), unit=unit)}"
145
-
146
-
147
- def format_single_error(error: dict[str, Any]) -> str:
148
- """Format a single Pydantic validation error into a human-readable message."""
149
-
150
- field = format_field_location(error.get("loc", ()))
151
- error_type = error.get("type", "")
152
- msg = error.get("msg", "")
153
- ctx = error.get("ctx", {})
154
-
155
- if error_type in SIMPLE_TYPE_MESSAGES:
156
- return f"Field '{field}' {SIMPLE_TYPE_MESSAGES[error_type]}"
157
-
158
- rule = CONSTRAINT_RULES.get(error_type)
159
- if rule is not None:
160
- return format_constraint_error(field, ctx, rule)
161
-
162
- match error_type:
163
- case "value_error":
164
- # Pydantic prefixes with "Value error, " -- strip it
165
- return msg.removeprefix("Value error, ")
166
- case "json_invalid":
167
- return "Invalid JSON in request body"
168
- case _:
169
- if msg:
170
- return f"Field '{field}': {msg}"
171
-
172
- return f"Field '{field}' is invalid"
173
-
174
-
175
- def format_validation_errors(exc: RequestValidationError) -> str:
176
- """Format all validation errors into a single human-readable message."""
177
-
178
- errors = exc.errors()
179
-
180
- if not errors:
181
- return HTTPStatus.BAD_REQUEST.phrase
182
-
183
- return ". ".join(format_single_error(error) for error in errors)
184
-
185
-
186
- def error_json_response(
187
- status_code: int, error: str, code: str | None, headers: Mapping[str, str] | None = None
188
- ) -> JSONResponse:
189
- """Build the standard `{success: false, error: ..., code: ...}` response, carrying any given headers."""
190
-
191
- response = ErrorResponseModel(success=False, error=error, code=code)
192
- content = response.model_dump(mode="json", exclude_none=True)
193
-
194
- return JSONResponse(status_code=status_code, content=content, headers=headers)
195
-
196
-
197
- def validation_exception_handler(_: Request, exc: RequestValidationError) -> JSONResponse:
198
- """Handle validation errors from pydantic models with human-readable messages."""
199
-
200
- logger.warning("Validation error: %s", exc.errors())
201
-
202
- return error_json_response(
203
- HTTPStatus.BAD_REQUEST, format_validation_errors(exc), DefaultErrorCode.VALIDATION_ERROR
204
- )
205
-
206
-
207
- def value_error_handler(_: Request, exc: ValueError) -> JSONResponse:
208
- """Handle a value the application rejected, reporting it as a bad request."""
209
-
210
- logger.exception(exc)
211
-
212
- return error_json_response(HTTPStatus.BAD_REQUEST, str(exc), DefaultErrorCode.INVALID_VALUE)
213
-
214
-
215
- def error_response_handler(_: Request, exc: ErrorResponse) -> JSONResponse:
216
- """Render an error the application raised deliberately, carrying the code it named."""
217
-
218
- logger.info("ErrorResponse: %s - %s", exc.status_code, exc.error)
219
-
220
- return error_json_response(exc.status_code, exc.error, exc.code)
221
-
222
-
223
- def general_exception_handler(_: Request, exc: Exception) -> JSONResponse:
224
- """Report a fault the application did not handle, keeping its detail out of the body."""
225
-
226
- logger.exception(exc)
227
-
228
- status_code = HTTPStatus.INTERNAL_SERVER_ERROR
229
-
230
- return error_json_response(status_code, status_code.phrase, DefaultErrorCode.INTERNAL_ERROR)
231
-
232
-
233
- def http_exception_handler(_: Request, exc: StarletteHTTPException) -> JSONResponse:
234
- """Convert an HTTP exception, including one the router raises, to the error envelope."""
235
-
236
- return error_json_response(exc.status_code, str(exc.detail), None, headers=exc.headers)
237
-
238
-
239
- def documented_model(spec: ResponseSpec) -> type[BaseModel]:
240
- """Return the model documenting one response: the given model, or the error envelope."""
241
-
242
- if isinstance(spec, type) and issubclass(spec, BaseModel):
243
- return spec
244
-
245
- return ErrorResponseModel if spec is None else ErrorResponseModel[spec]
246
-
247
-
248
- def fastapi_responses(specs: dict[HTTPStatus, ResponseSpec]) -> dict[int | str, dict[str, Any]]:
249
- """Build FastAPI's `responses` mapping from status codes and their models or error codes."""
250
-
251
- return {status_code: {"model": documented_model(spec)} for status_code, spec in specs.items()}
252
-
253
-
254
- EXCEPTION_HANDLERS: dict[type[Exception], Callable[[Request, Exception], JSONResponse]] = {
255
- StarletteHTTPException: http_exception_handler,
256
- RequestValidationError: validation_exception_handler,
257
- ValidationError: general_exception_handler,
258
- ValueError: value_error_handler,
259
- ErrorResponse: error_response_handler,
260
- Exception: general_exception_handler,
261
- }