fastapi-standard-responses 0.1.0__py3-none-any.whl
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.
- fastapi_response_handler/__init__.py +71 -0
- fastapi_response_handler/envelope.py +283 -0
- fastapi_response_handler/errors.py +413 -0
- fastapi_response_handler/exceptions.py +91 -0
- fastapi_response_handler/handlers.py +212 -0
- fastapi_response_handler/openapi.py +165 -0
- fastapi_response_handler/py.typed +0 -0
- fastapi_response_handler/pydantic_errors.py +295 -0
- fastapi_standard_responses-0.1.0.dist-info/METADATA +551 -0
- fastapi_standard_responses-0.1.0.dist-info/RECORD +12 -0
- fastapi_standard_responses-0.1.0.dist-info/WHEEL +4 -0
- fastapi_standard_responses-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
"""One error catalog and one response envelope for FastAPI + Pydantic v2.
|
|
2
|
+
|
|
3
|
+
Declare expected errors once, raise them from services (:class:`ApiError`) and
|
|
4
|
+
validators (:func:`pydantic_error`), return every response in one envelope, and
|
|
5
|
+
render the same errors into the OpenAPI docs.
|
|
6
|
+
|
|
7
|
+
Quick start::
|
|
8
|
+
|
|
9
|
+
from fastapi_response_handler import (
|
|
10
|
+
DYNAMIC_MESSAGE, ApiResponse, ErrorCatalog, install_error_handlers,
|
|
11
|
+
pydantic_error, responses_for, successes_for,
|
|
12
|
+
)
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
from .envelope import (
|
|
18
|
+
ApiErrorResponse,
|
|
19
|
+
ApiResponse,
|
|
20
|
+
ErrorItem,
|
|
21
|
+
ErrorResponse,
|
|
22
|
+
SuccessResponse,
|
|
23
|
+
status_description,
|
|
24
|
+
success_example,
|
|
25
|
+
success_response,
|
|
26
|
+
)
|
|
27
|
+
from .errors import DYNAMIC_MESSAGE, ErrorCatalog, ErrorDefinition, FieldErrors, FieldView
|
|
28
|
+
from .exceptions import ApiError
|
|
29
|
+
from .handlers import install_error_handlers
|
|
30
|
+
from .openapi import build_openapi_examples, responses_for, successes_for
|
|
31
|
+
from .pydantic_errors import (
|
|
32
|
+
PYDANTIC_TYPE_TO_CODE,
|
|
33
|
+
ResolvedError,
|
|
34
|
+
field_from_loc,
|
|
35
|
+
pydantic_error,
|
|
36
|
+
register_additional_errors,
|
|
37
|
+
resolve_validation_error,
|
|
38
|
+
resolve_validation_errors,
|
|
39
|
+
validation_status,
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
__version__ = "0.1.0"
|
|
43
|
+
|
|
44
|
+
__all__ = [
|
|
45
|
+
"DYNAMIC_MESSAGE",
|
|
46
|
+
"PYDANTIC_TYPE_TO_CODE",
|
|
47
|
+
"ApiError",
|
|
48
|
+
"ApiErrorResponse",
|
|
49
|
+
"ApiResponse",
|
|
50
|
+
"ErrorCatalog",
|
|
51
|
+
"ErrorDefinition",
|
|
52
|
+
"ErrorItem",
|
|
53
|
+
"ErrorResponse",
|
|
54
|
+
"FieldErrors",
|
|
55
|
+
"FieldView",
|
|
56
|
+
"ResolvedError",
|
|
57
|
+
"SuccessResponse",
|
|
58
|
+
"build_openapi_examples",
|
|
59
|
+
"field_from_loc",
|
|
60
|
+
"install_error_handlers",
|
|
61
|
+
"pydantic_error",
|
|
62
|
+
"register_additional_errors",
|
|
63
|
+
"resolve_validation_error",
|
|
64
|
+
"resolve_validation_errors",
|
|
65
|
+
"responses_for",
|
|
66
|
+
"status_description",
|
|
67
|
+
"success_example",
|
|
68
|
+
"success_response",
|
|
69
|
+
"successes_for",
|
|
70
|
+
"validation_status",
|
|
71
|
+
]
|
|
@@ -0,0 +1,283 @@
|
|
|
1
|
+
"""The single response envelope for success and error responses.
|
|
2
|
+
|
|
3
|
+
Success bodies use :class:`ApiResponse` (optionally subclassed to declare
|
|
4
|
+
documented defaults); error bodies use :class:`ApiErrorResponse` with one
|
|
5
|
+
:class:`ErrorItem` per ``(field, code)`` pair.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from collections.abc import Mapping
|
|
11
|
+
from http import HTTPStatus
|
|
12
|
+
from typing import Any, Generic, Literal, TypeVar
|
|
13
|
+
|
|
14
|
+
from pydantic import BaseModel, ConfigDict, Field
|
|
15
|
+
|
|
16
|
+
from .errors import ErrorDefinition
|
|
17
|
+
|
|
18
|
+
__all__ = [
|
|
19
|
+
"ApiErrorResponse",
|
|
20
|
+
"ApiResponse",
|
|
21
|
+
"ErrorItem",
|
|
22
|
+
"ErrorResponse",
|
|
23
|
+
"SuccessResponse",
|
|
24
|
+
"status_description",
|
|
25
|
+
"success_example",
|
|
26
|
+
"success_response",
|
|
27
|
+
]
|
|
28
|
+
|
|
29
|
+
T = TypeVar("T")
|
|
30
|
+
|
|
31
|
+
_STATUS_DESCRIPTIONS: dict[int, str] = {
|
|
32
|
+
400: "Bad Request",
|
|
33
|
+
401: "Unauthorized",
|
|
34
|
+
402: "Payment Required",
|
|
35
|
+
403: "Forbidden",
|
|
36
|
+
404: "Not Found",
|
|
37
|
+
405: "Method Not Allowed",
|
|
38
|
+
406: "Not Acceptable",
|
|
39
|
+
408: "Request Timeout",
|
|
40
|
+
409: "Conflict",
|
|
41
|
+
410: "Gone",
|
|
42
|
+
411: "Length Required",
|
|
43
|
+
412: "Precondition Failed",
|
|
44
|
+
413: "Payload Too Large",
|
|
45
|
+
415: "Unsupported Media Type",
|
|
46
|
+
418: "I'm a teapot",
|
|
47
|
+
422: "Validation failed",
|
|
48
|
+
423: "Locked",
|
|
49
|
+
425: "Too Early",
|
|
50
|
+
428: "Precondition Required",
|
|
51
|
+
429: "Too Many Requests",
|
|
52
|
+
431: "Request Header Fields Too Large",
|
|
53
|
+
500: "Internal Server Error",
|
|
54
|
+
501: "Not Implemented",
|
|
55
|
+
502: "Bad Gateway",
|
|
56
|
+
503: "Service Unavailable",
|
|
57
|
+
504: "Gateway Timeout",
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def status_description(status: int) -> str:
|
|
62
|
+
"""Return the documentation description for an HTTP status.
|
|
63
|
+
|
|
64
|
+
``422`` is documented as ``"Validation failed"``; other statuses fall back
|
|
65
|
+
to the standard reason phrase, or ``"HTTP <status>"`` for unknown codes.
|
|
66
|
+
"""
|
|
67
|
+
if status in _STATUS_DESCRIPTIONS:
|
|
68
|
+
return _STATUS_DESCRIPTIONS[status]
|
|
69
|
+
try:
|
|
70
|
+
return HTTPStatus(status).phrase
|
|
71
|
+
except ValueError:
|
|
72
|
+
return f"HTTP {status}"
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
class ErrorItem(BaseModel):
|
|
76
|
+
"""One error inside the envelope's ``errors`` array."""
|
|
77
|
+
|
|
78
|
+
model_config = ConfigDict(extra="forbid")
|
|
79
|
+
|
|
80
|
+
field: str | None = Field(default=None, description="Field the error belongs to.")
|
|
81
|
+
code: str = Field(description="Machine-readable error code.")
|
|
82
|
+
message: str = Field(description="Human-readable message.")
|
|
83
|
+
|
|
84
|
+
@classmethod
|
|
85
|
+
def from_definition(
|
|
86
|
+
cls,
|
|
87
|
+
field: str | None,
|
|
88
|
+
definition: ErrorDefinition,
|
|
89
|
+
message: str | None = None,
|
|
90
|
+
) -> ErrorItem:
|
|
91
|
+
"""Build an item from a catalog definition.
|
|
92
|
+
|
|
93
|
+
Args:
|
|
94
|
+
field: Field name reported to the client.
|
|
95
|
+
definition: Catalog definition supplying ``code`` and, for static
|
|
96
|
+
entries, ``message``.
|
|
97
|
+
message: Message to use when the definition is dynamic. Ignored for
|
|
98
|
+
static definitions, whose catalog text is authoritative.
|
|
99
|
+
|
|
100
|
+
Returns:
|
|
101
|
+
A validated :class:`ErrorItem`.
|
|
102
|
+
"""
|
|
103
|
+
if definition.is_dynamic:
|
|
104
|
+
text = message or (f"Invalid value for {field!r}." if field else "Invalid value.")
|
|
105
|
+
else:
|
|
106
|
+
text = definition.message
|
|
107
|
+
return cls(field=field, code=definition.code, message=text)
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
class ApiResponse(BaseModel, Generic[T]):
|
|
111
|
+
"""Success envelope: ``{"success": true, "status_code": ..., "message": ..., "data": ...}``.
|
|
112
|
+
|
|
113
|
+
Subclass it to declare documentation defaults that are also returned::
|
|
114
|
+
|
|
115
|
+
class UserRegisterSuccessResponse(ApiResponse[UserOut]):
|
|
116
|
+
status_code: int = 201
|
|
117
|
+
message: str = "Registration successful."
|
|
118
|
+
"""
|
|
119
|
+
|
|
120
|
+
success: bool = Field(default=True, description="Always true for success responses.")
|
|
121
|
+
status_code: int = Field(description="HTTP status code of the response.")
|
|
122
|
+
message: str = Field(description="Human-readable summary.")
|
|
123
|
+
data: T | None = Field(default=None, description="Response payload.")
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
class ApiErrorResponse(BaseModel):
|
|
127
|
+
"""Error envelope: ``{"success": false, "status_code": ..., "message": ..., "errors": [...]}``."""
|
|
128
|
+
|
|
129
|
+
success: Literal[False] = Field(
|
|
130
|
+
default=False,
|
|
131
|
+
description="Always false for error responses.",
|
|
132
|
+
)
|
|
133
|
+
status_code: int = Field(description="HTTP status code of the response.")
|
|
134
|
+
message: str = Field(description="Human-readable summary.")
|
|
135
|
+
errors: list[ErrorItem] = Field(
|
|
136
|
+
default_factory=list,
|
|
137
|
+
description="One item per (field, code) pair.",
|
|
138
|
+
)
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
SuccessResponse = ApiResponse
|
|
142
|
+
"""Alias kept for symmetry with :data:`ErrorResponse`."""
|
|
143
|
+
|
|
144
|
+
ErrorResponse = ApiErrorResponse
|
|
145
|
+
"""Alias kept for symmetry with :data:`SuccessResponse`."""
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def success_response(
|
|
149
|
+
data: Any = None,
|
|
150
|
+
*,
|
|
151
|
+
message: str = "Success",
|
|
152
|
+
status_code: int = 200,
|
|
153
|
+
) -> ApiResponse[Any]:
|
|
154
|
+
"""Build a validated success envelope.
|
|
155
|
+
|
|
156
|
+
Args:
|
|
157
|
+
data: Payload to place under ``data``.
|
|
158
|
+
message: Human-readable summary.
|
|
159
|
+
status_code: Status code to declare in the body (the route still sets
|
|
160
|
+
the real HTTP status).
|
|
161
|
+
"""
|
|
162
|
+
return ApiResponse[Any](data=data, message=message, status_code=status_code)
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def _declared_status(model: type[BaseModel]) -> int:
|
|
166
|
+
field = model.model_fields.get("status_code")
|
|
167
|
+
default = getattr(field, "default", None)
|
|
168
|
+
return default if isinstance(default, int) else 200
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def _resolve_ref(ref: str, defs: Mapping[str, Any]) -> Mapping[str, Any]:
|
|
172
|
+
name = ref.rsplit("/", 1)[-1]
|
|
173
|
+
resolved = defs.get(name)
|
|
174
|
+
return resolved if isinstance(resolved, Mapping) else {}
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def _example_from_schema(
|
|
178
|
+
schema: Mapping[str, Any],
|
|
179
|
+
defs: Mapping[str, Any],
|
|
180
|
+
depth: int = 0,
|
|
181
|
+
) -> Any:
|
|
182
|
+
"""Build a small, realistic example value from a JSON Schema fragment."""
|
|
183
|
+
if not schema or depth > 10:
|
|
184
|
+
return None
|
|
185
|
+
if "$ref" in schema:
|
|
186
|
+
return _example_from_schema(_resolve_ref(str(schema["$ref"]), defs), defs, depth + 1)
|
|
187
|
+
if "example" in schema:
|
|
188
|
+
return schema["example"]
|
|
189
|
+
examples = schema.get("examples")
|
|
190
|
+
if isinstance(examples, list) and examples:
|
|
191
|
+
return examples[0]
|
|
192
|
+
if "allOf" in schema:
|
|
193
|
+
merged: dict[str, Any] = {}
|
|
194
|
+
for branch in schema["allOf"] or []:
|
|
195
|
+
value = _example_from_schema(branch, defs, depth + 1)
|
|
196
|
+
if isinstance(value, dict):
|
|
197
|
+
merged.update(value)
|
|
198
|
+
return merged
|
|
199
|
+
for combinator in ("anyOf", "oneOf"):
|
|
200
|
+
if combinator in schema:
|
|
201
|
+
branches = [branch for branch in schema[combinator] or [] if isinstance(branch, Mapping)]
|
|
202
|
+
non_null = [branch for branch in branches if branch.get("type") != "null"]
|
|
203
|
+
chosen = (non_null or branches or [{}])[0]
|
|
204
|
+
return _example_from_schema(chosen, defs, depth + 1)
|
|
205
|
+
if "const" in schema:
|
|
206
|
+
return schema["const"]
|
|
207
|
+
enum = schema.get("enum")
|
|
208
|
+
if isinstance(enum, list) and enum:
|
|
209
|
+
return enum[0]
|
|
210
|
+
default = schema.get("default")
|
|
211
|
+
if default is not None:
|
|
212
|
+
return default
|
|
213
|
+
kind = schema.get("type")
|
|
214
|
+
if isinstance(kind, list):
|
|
215
|
+
kind = next((item for item in kind if item != "null"), "null")
|
|
216
|
+
if kind == "object" or "properties" in schema:
|
|
217
|
+
properties = schema.get("properties") or {}
|
|
218
|
+
return {
|
|
219
|
+
name: _example_from_schema(prop, defs, depth + 1)
|
|
220
|
+
for name, prop in properties.items()
|
|
221
|
+
if isinstance(prop, Mapping)
|
|
222
|
+
}
|
|
223
|
+
if kind == "array":
|
|
224
|
+
items = schema.get("items")
|
|
225
|
+
if not isinstance(items, Mapping):
|
|
226
|
+
return []
|
|
227
|
+
minimum = schema.get("minItems", 1)
|
|
228
|
+
count = max(1, min(int(minimum), 3)) if isinstance(minimum, int) else 1
|
|
229
|
+
return [_example_from_schema(items, defs, depth + 1) for _ in range(count)]
|
|
230
|
+
if kind == "string":
|
|
231
|
+
return _STRING_EXAMPLES.get(str(schema.get("format") or ""), "string")
|
|
232
|
+
if kind == "integer":
|
|
233
|
+
return 1 if schema.get("exclusiveMinimum") else 0
|
|
234
|
+
if kind == "number":
|
|
235
|
+
return 0.0 if schema.get("exclusiveMinimum") else 0
|
|
236
|
+
if kind == "boolean":
|
|
237
|
+
return True
|
|
238
|
+
return None
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
_STRING_EXAMPLES: dict[str, str] = {
|
|
242
|
+
"date": "2024-01-01",
|
|
243
|
+
"date-time": "2024-01-01T00:00:00Z",
|
|
244
|
+
"duration": "PT1H",
|
|
245
|
+
"email": "user@example.com",
|
|
246
|
+
"hostname": "example.com",
|
|
247
|
+
"ipv4": "127.0.0.1",
|
|
248
|
+
"ipv6": "::1",
|
|
249
|
+
"time": "12:00:00",
|
|
250
|
+
"uri": "https://example.com/resource",
|
|
251
|
+
"uuid": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def success_example(model: type[ApiResponse[Any]]) -> dict[int, dict[str, Any]]:
|
|
256
|
+
"""Build the FastAPI ``responses=`` entry for a declared success model.
|
|
257
|
+
|
|
258
|
+
The example body is generated from the model's JSON Schema, so defaults such
|
|
259
|
+
as ``status_code``/``message`` and the shape of ``data`` are documented from
|
|
260
|
+
the same declaration the route returns.
|
|
261
|
+
|
|
262
|
+
Args:
|
|
263
|
+
model: An :class:`ApiResponse` subclass (for example
|
|
264
|
+
``UserRegisterSuccessResponse``).
|
|
265
|
+
|
|
266
|
+
Returns:
|
|
267
|
+
``{status_code: {"model": model, "description": ..., "content":
|
|
268
|
+
{"application/json": {"example": ...}}}}``, ready to splat into
|
|
269
|
+
``responses=`` or to pass to :func:`successes_for`.
|
|
270
|
+
"""
|
|
271
|
+
status = _declared_status(model)
|
|
272
|
+
schema = model.model_json_schema()
|
|
273
|
+
defs = schema.get("$defs") or {}
|
|
274
|
+
example = _example_from_schema(schema, defs)
|
|
275
|
+
if isinstance(example, dict):
|
|
276
|
+
example["status_code"] = status
|
|
277
|
+
return {
|
|
278
|
+
status: {
|
|
279
|
+
"model": model,
|
|
280
|
+
"description": status_description(status),
|
|
281
|
+
"content": {"application/json": {"example": example}},
|
|
282
|
+
}
|
|
283
|
+
}
|