fastapi-standard-responses 0.1.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.
- fastapi_standard_responses-0.1.0/.gitignore +69 -0
- fastapi_standard_responses-0.1.0/CHANGELOG.md +18 -0
- fastapi_standard_responses-0.1.0/LICENSE +21 -0
- fastapi_standard_responses-0.1.0/PKG-INFO +551 -0
- fastapi_standard_responses-0.1.0/PROMPT.md +413 -0
- fastapi_standard_responses-0.1.0/README.md +524 -0
- fastapi_standard_responses-0.1.0/pyproject.toml +58 -0
- fastapi_standard_responses-0.1.0/src/fastapi_response_handler/__init__.py +71 -0
- fastapi_standard_responses-0.1.0/src/fastapi_response_handler/envelope.py +283 -0
- fastapi_standard_responses-0.1.0/src/fastapi_response_handler/errors.py +413 -0
- fastapi_standard_responses-0.1.0/src/fastapi_response_handler/exceptions.py +91 -0
- fastapi_standard_responses-0.1.0/src/fastapi_response_handler/handlers.py +212 -0
- fastapi_standard_responses-0.1.0/src/fastapi_response_handler/openapi.py +165 -0
- fastapi_standard_responses-0.1.0/src/fastapi_response_handler/py.typed +0 -0
- fastapi_standard_responses-0.1.0/src/fastapi_response_handler/pydantic_errors.py +295 -0
- fastapi_standard_responses-0.1.0/tests/conftest.py +145 -0
- fastapi_standard_responses-0.1.0/tests/test_envelope.py +191 -0
- fastapi_standard_responses-0.1.0/tests/test_errors.py +430 -0
- fastapi_standard_responses-0.1.0/tests/test_handlers.py +316 -0
- fastapi_standard_responses-0.1.0/tests/test_openapi_responses.py +194 -0
- fastapi_standard_responses-0.1.0/tests/test_pydantic_errors.py +269 -0
- fastapi_standard_responses-0.1.0/tests/test_registration_contract.py +445 -0
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
# Byte-compiled / optimized / C-extensions
|
|
2
|
+
__pycache__/
|
|
3
|
+
*.py[cod]
|
|
4
|
+
*$py.class
|
|
5
|
+
*.so
|
|
6
|
+
|
|
7
|
+
# Environments & Virtual Environments
|
|
8
|
+
.env
|
|
9
|
+
.venv/
|
|
10
|
+
env/
|
|
11
|
+
venv/
|
|
12
|
+
ENV/
|
|
13
|
+
env.bak/
|
|
14
|
+
venv.bak/
|
|
15
|
+
|
|
16
|
+
# Environment variables & secrets
|
|
17
|
+
.env*.local
|
|
18
|
+
.env.*
|
|
19
|
+
!.env.example
|
|
20
|
+
|
|
21
|
+
# Database & SQLite files
|
|
22
|
+
*.sqlite
|
|
23
|
+
*.sqlite3
|
|
24
|
+
*.db
|
|
25
|
+
|
|
26
|
+
# Alembic / Migrations
|
|
27
|
+
# (Keep versions/ tracked, ignore pycache and logs)
|
|
28
|
+
alembic/versions/__pycache__/
|
|
29
|
+
|
|
30
|
+
# Testing & Coverage
|
|
31
|
+
.pytest_cache/
|
|
32
|
+
.coverage
|
|
33
|
+
.coverage.*
|
|
34
|
+
htmlcov/
|
|
35
|
+
.hypothesis/
|
|
36
|
+
coverage.xml
|
|
37
|
+
*.cover
|
|
38
|
+
|
|
39
|
+
# Static / Upload directories (if storing local assets)
|
|
40
|
+
uploads/
|
|
41
|
+
media/
|
|
42
|
+
static_cache/
|
|
43
|
+
|
|
44
|
+
# Distribution / Packaging
|
|
45
|
+
dist/
|
|
46
|
+
build/
|
|
47
|
+
*.egg-info/
|
|
48
|
+
*.egg
|
|
49
|
+
|
|
50
|
+
# Linters, Type Checkers & Formatters
|
|
51
|
+
.mypy_cache/
|
|
52
|
+
.dmypy.json
|
|
53
|
+
dmypy.json
|
|
54
|
+
.ruff_cache/
|
|
55
|
+
.black
|
|
56
|
+
.flake8_cache/
|
|
57
|
+
|
|
58
|
+
# IDE & Editor files
|
|
59
|
+
.vscode/
|
|
60
|
+
.idea/
|
|
61
|
+
*.swp
|
|
62
|
+
*.swo
|
|
63
|
+
*~
|
|
64
|
+
.DS_Store
|
|
65
|
+
Thumbs.db
|
|
66
|
+
|
|
67
|
+
# Logs
|
|
68
|
+
*.log
|
|
69
|
+
logs/
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to this project are documented in this file.
|
|
4
|
+
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/)
|
|
5
|
+
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
6
|
+
|
|
7
|
+
## [0.1.0] - 2026-11-28
|
|
8
|
+
|
|
9
|
+
### Added
|
|
10
|
+
|
|
11
|
+
- `ErrorCatalog` with attribute/index access, validation, `merge`, `add`, `find` and `get`.
|
|
12
|
+
- `ErrorDefinition` with `DYNAMIC_MESSAGE` support, `format()`, `as_dict()` and `as_exception()`.
|
|
13
|
+
- `ApiResponse[T]`, `ApiErrorResponse`, `ErrorItem`, `success_response()` and `success_example()`.
|
|
14
|
+
- `ApiError` exception with `from_catalog()` and drop-in `HTTPException` semantics.
|
|
15
|
+
- `pydantic_error()`, `PYDANTIC_TYPE_TO_CODE`, `field_from_loc()`, `resolve_validation_error(s)()` and `validation_status()`.
|
|
16
|
+
- `responses_for()`, `successes_for()` and `build_openapi_examples()` to document every declared status.
|
|
17
|
+
- `install_error_handlers()` for `RequestValidationError`, `ApiError`, `HTTPException` and unhandled exceptions.
|
|
18
|
+
- Full test suite, including the registration reference scenario.
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 fastapi-response-handler authors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,551 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: fastapi-standard-responses
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: One error catalog and one response envelope for FastAPI + Pydantic v2, shared by runtime errors and the OpenAPI docs.
|
|
5
|
+
Author: fastapi-standard-responses authors
|
|
6
|
+
License: MIT
|
|
7
|
+
License-File: LICENSE
|
|
8
|
+
Keywords: errors,fastapi,openapi,pydantic,responses,swagger
|
|
9
|
+
Classifier: Development Status :: 4 - Beta
|
|
10
|
+
Classifier: Framework :: FastAPI
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Typing :: Typed
|
|
19
|
+
Requires-Python: >=3.10
|
|
20
|
+
Requires-Dist: fastapi>=0.100
|
|
21
|
+
Requires-Dist: pydantic>=2
|
|
22
|
+
Provides-Extra: dev
|
|
23
|
+
Requires-Dist: email-validator>=2; extra == 'dev'
|
|
24
|
+
Requires-Dist: httpx>=0.24; extra == 'dev'
|
|
25
|
+
Requires-Dist: pytest>=7; extra == 'dev'
|
|
26
|
+
Description-Content-Type: text/markdown
|
|
27
|
+
|
|
28
|
+
# fastapi-response-handler
|
|
29
|
+
|
|
30
|
+
Declare your API errors once, use them everywhere.
|
|
31
|
+
|
|
32
|
+
`fastapi-response-handler` gives a FastAPI app a single error catalog, the same
|
|
33
|
+
error shape on every response, zero-boilerplate validation errors, and OpenAPI
|
|
34
|
+
examples generated from the catalog, so the docs and the API can never drift
|
|
35
|
+
apart.
|
|
36
|
+
|
|
37
|
+
- **One envelope everywhere** — success and error responses share a predictable
|
|
38
|
+
shape.
|
|
39
|
+
- **Typed catalog** — each field exposes its errors as attributes and as a
|
|
40
|
+
mapping, validated at import time.
|
|
41
|
+
- **Pydantic integration** — raise the same catalog error from validators and
|
|
42
|
+
map request validation failures onto your own codes and messages.
|
|
43
|
+
- **OpenAPI that matches runtime** — `responses_for` and `successes_for` produce
|
|
44
|
+
per-code named examples.
|
|
45
|
+
- **No traceback leaks** — global handlers return a safe 500 envelope, with
|
|
46
|
+
tracebacks only when you ask for them.
|
|
47
|
+
|
|
48
|
+
Requires Python 3.10+ and FastAPI with Pydantic v2.
|
|
49
|
+
|
|
50
|
+
## Installation
|
|
51
|
+
|
|
52
|
+
```bash
|
|
53
|
+
# from a checkout of this repository
|
|
54
|
+
pip install -e ./PACKAGE
|
|
55
|
+
|
|
56
|
+
# once published
|
|
57
|
+
pip install fastapi-response-handler
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
## Quick start
|
|
61
|
+
|
|
62
|
+
### 1. Declare the catalog
|
|
63
|
+
|
|
64
|
+
```python
|
|
65
|
+
from fastapi_response_handler import DYNAMIC_MESSAGE, ErrorCatalog
|
|
66
|
+
|
|
67
|
+
catalog = ErrorCatalog(
|
|
68
|
+
[
|
|
69
|
+
{
|
|
70
|
+
"field": "name",
|
|
71
|
+
"errors": [
|
|
72
|
+
{"status": 422, "code": "missing", "message": "Name is required."},
|
|
73
|
+
{
|
|
74
|
+
"status": 422,
|
|
75
|
+
"code": "have_single_character",
|
|
76
|
+
"message": "Name should have at least one character.",
|
|
77
|
+
},
|
|
78
|
+
],
|
|
79
|
+
},
|
|
80
|
+
{
|
|
81
|
+
"field": "email",
|
|
82
|
+
"errors": [
|
|
83
|
+
{"status": 422, "code": "missing", "message": "Email is required."},
|
|
84
|
+
{"status": 422, "code": "value_error", "message": DYNAMIC_MESSAGE},
|
|
85
|
+
{
|
|
86
|
+
"status": 409,
|
|
87
|
+
"code": "email_already_exists",
|
|
88
|
+
"message": "User with this email is already registered.",
|
|
89
|
+
},
|
|
90
|
+
],
|
|
91
|
+
},
|
|
92
|
+
{
|
|
93
|
+
"field": "phone",
|
|
94
|
+
"errors": [
|
|
95
|
+
{"status": 422, "code": "missing", "message": "Phone is required."},
|
|
96
|
+
{
|
|
97
|
+
"status": 422,
|
|
98
|
+
"code": "indian_phone_error",
|
|
99
|
+
"message": "Enter a valid 10-digit Indian phone number.",
|
|
100
|
+
},
|
|
101
|
+
],
|
|
102
|
+
},
|
|
103
|
+
{
|
|
104
|
+
"field": "role",
|
|
105
|
+
"errors": [
|
|
106
|
+
{
|
|
107
|
+
"status": 422,
|
|
108
|
+
"code": "literal_error",
|
|
109
|
+
"message": "Role must be either 'Teacher' or 'Student'.",
|
|
110
|
+
}
|
|
111
|
+
],
|
|
112
|
+
},
|
|
113
|
+
]
|
|
114
|
+
)
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
Each definition needs a `status` (400–599), a non-empty `code`, and a `message`.
|
|
118
|
+
The catalog rejects duplicate `(field, code)` pairs when it is built.
|
|
119
|
+
|
|
120
|
+
Access definitions by attribute or by key:
|
|
121
|
+
|
|
122
|
+
```python
|
|
123
|
+
catalog.email.email_already_exists.status # 409
|
|
124
|
+
catalog["email"]["email_already_exists"].code # 'email_already_exists'
|
|
125
|
+
catalog.fields # ('name', 'email', 'phone', 'role')
|
|
126
|
+
catalog.find("indian_phone_error") # ErrorDefinition(...)
|
|
127
|
+
catalog.email.codes # ('missing', 'value_error', 'email_already_exists')
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
### 2. Raise catalog errors from routes
|
|
131
|
+
|
|
132
|
+
```python
|
|
133
|
+
from fastapi import FastAPI
|
|
134
|
+
from fastapi_response_handler import ApiError, install_error_handlers
|
|
135
|
+
|
|
136
|
+
app = FastAPI()
|
|
137
|
+
install_error_handlers(app, catalog=catalog)
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
@app.get("/users/{user_id}")
|
|
141
|
+
def get_user(user_id: str):
|
|
142
|
+
raise catalog.email.email_already_exists.as_exception()
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
`as_exception()` returns an `ApiError`, which is a `StarletteHTTPException`, so
|
|
146
|
+
FastAPI's machinery (including exception handlers) behaves normally:
|
|
147
|
+
|
|
148
|
+
```json
|
|
149
|
+
{
|
|
150
|
+
"success": false,
|
|
151
|
+
"status_code": 409,
|
|
152
|
+
"message": "User with this email is already registered.",
|
|
153
|
+
"errors": [
|
|
154
|
+
{
|
|
155
|
+
"field": "email",
|
|
156
|
+
"code": "email_already_exists",
|
|
157
|
+
"message": "User with this email is already registered."
|
|
158
|
+
}
|
|
159
|
+
]
|
|
160
|
+
}
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
You can also construct one directly, with optional headers and a field:
|
|
164
|
+
|
|
165
|
+
```python
|
|
166
|
+
raise ApiError(429, "Slow down.", code="rate_limited", field="email", headers={"Retry-After": "60"})
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
or look one up when only strings are available:
|
|
170
|
+
|
|
171
|
+
```python
|
|
172
|
+
raise ApiError.from_catalog(catalog, "email", "email_already_exists")
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
### 3. Use catalog errors inside Pydantic validators
|
|
176
|
+
|
|
177
|
+
`pydantic_error` returns a `PydanticCustomError` whose `type` is your catalog
|
|
178
|
+
code, so the global handler can render it like any other catalog error:
|
|
179
|
+
|
|
180
|
+
```python
|
|
181
|
+
import re
|
|
182
|
+
from pydantic import BaseModel, ConfigDict, field_validator
|
|
183
|
+
from fastapi_response_handler import pydantic_error
|
|
184
|
+
|
|
185
|
+
PHONE_PATTERN = re.compile(r"^[6-9]\d{9}$")
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
class UserRegister(BaseModel):
|
|
189
|
+
model_config = ConfigDict(extra="forbid")
|
|
190
|
+
|
|
191
|
+
name: str
|
|
192
|
+
email: str
|
|
193
|
+
phone: str
|
|
194
|
+
role: str
|
|
195
|
+
password: str
|
|
196
|
+
confirm_password: str
|
|
197
|
+
|
|
198
|
+
@field_validator("phone")
|
|
199
|
+
@classmethod
|
|
200
|
+
def validate_indian_phone(cls, value: str) -> str:
|
|
201
|
+
if not PHONE_PATTERN.fullmatch(value):
|
|
202
|
+
raise pydantic_error(catalog, "phone", "indian_phone_error")
|
|
203
|
+
return value
|
|
204
|
+
```
|
|
205
|
+
|
|
206
|
+
`DYNAMIC_MESSAGE` marks a definition whose text comes from the caller instead of
|
|
207
|
+
the catalog (for example Pydantic's own message). `pydantic_error` accepts an
|
|
208
|
+
explicit `message=` override, and placeholders such as `"Age must be greater
|
|
209
|
+
than {gt}."` are filled from extra keyword arguments.
|
|
210
|
+
|
|
211
|
+
### 4. Document both success and failure responses
|
|
212
|
+
|
|
213
|
+
```python
|
|
214
|
+
from fastapi_response_handler import ApiResponse, responses_for, successes_for
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
class UserOut(BaseModel):
|
|
218
|
+
id: str
|
|
219
|
+
name: str
|
|
220
|
+
email: str
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
class UserRegisterSuccessResponse(ApiResponse[UserOut]):
|
|
224
|
+
status_code: int = 201
|
|
225
|
+
message: str = "Registration successful, email verification link has been sent."
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
@app.post(
|
|
229
|
+
"/auth/register",
|
|
230
|
+
response_model=UserRegisterSuccessResponse,
|
|
231
|
+
status_code=201,
|
|
232
|
+
responses={
|
|
233
|
+
**successes_for(UserRegisterSuccessResponse),
|
|
234
|
+
**responses_for(catalog, "name", "email", "phone", "password"),
|
|
235
|
+
},
|
|
236
|
+
)
|
|
237
|
+
def register(payload: UserRegister) -> UserRegisterSuccessResponse:
|
|
238
|
+
user = UserOut(id="user-1", name=payload.name, email=payload.email)
|
|
239
|
+
return UserRegisterSuccessResponse(data=user)
|
|
240
|
+
```
|
|
241
|
+
|
|
242
|
+
`responses_for` groups the definitions of the named fields by status, attaches
|
|
243
|
+
the correct description (e.g. `409 Conflict`, `422 Validation failed`), and
|
|
244
|
+
labels every example with its catalog message:
|
|
245
|
+
|
|
246
|
+
```json
|
|
247
|
+
{
|
|
248
|
+
"422": {
|
|
249
|
+
"description": "Validation failed",
|
|
250
|
+
"content": {
|
|
251
|
+
"application/json": {
|
|
252
|
+
"examples": {
|
|
253
|
+
"Name is required.": {"summary": "Name is required.", "value": {"success": false, "...": "..."}},
|
|
254
|
+
"Enter a valid 10-digit Indian phone number.": {"summary": "Enter a valid 10-digit Indian phone number.", "value": {"...": "..."}}
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
```
|
|
261
|
+
|
|
262
|
+
Statuses are sorted numerically. Each example's map key is its catalog message,
|
|
263
|
+
which is exactly what Swagger UI renders in the example dropdown (`summary`
|
|
264
|
+
repeats it for clients that read that field). If two errors in the same status
|
|
265
|
+
share the same message, the code is appended
|
|
266
|
+
(`Age must be a whole number. (int_parsing)`) so every label stays distinct and
|
|
267
|
+
readable.
|
|
268
|
+
|
|
269
|
+
`successes_for` returns the success response schema plus an example generated
|
|
270
|
+
from the model's JSON Schema, so declared defaults are reflected in the docs.
|
|
271
|
+
Pass `message="..."` to `responses_for` to override the top-level envelope text
|
|
272
|
+
for every status.
|
|
273
|
+
|
|
274
|
+
### 5. Helpers for explicit responses
|
|
275
|
+
|
|
276
|
+
```python
|
|
277
|
+
from fastapi_response_handler import ApiErrorResponse, success_response
|
|
278
|
+
|
|
279
|
+
return success_response({"id": "user-1"}, message="Created.", status_code=201)
|
|
280
|
+
|
|
281
|
+
return ApiErrorResponse(
|
|
282
|
+
status_code=422,
|
|
283
|
+
message="Validation failed",
|
|
284
|
+
errors=[{"field": "email", "code": "missing", "message": "Email is required."}],
|
|
285
|
+
)
|
|
286
|
+
```
|
|
287
|
+
|
|
288
|
+
## What the handlers cover
|
|
289
|
+
|
|
290
|
+
`install_error_handlers(app, *, catalog=None, debug=False, logger=None)` registers
|
|
291
|
+
handlers for all of the following:
|
|
292
|
+
|
|
293
|
+
| Raised | Status | Envelope message |
|
|
294
|
+
| ---------------------------------------- | ------------------------- | ------------------------------------ |
|
|
295
|
+
| `RequestValidationError` | 422 by default, or the highest non-422 catalog status among the failing fields | status description (`"Validation failed"`) |
|
|
296
|
+
| `ApiError` | `error.status_code` | `error.message` |
|
|
297
|
+
| `StarletteHTTPException` | `exc.status_code` | `exc.detail` (dicts use `message`) |
|
|
298
|
+
| any other `Exception` | 500 | `"Internal server error."` |
|
|
299
|
+
|
|
300
|
+
Every error body has the same shape:
|
|
301
|
+
|
|
302
|
+
```json
|
|
303
|
+
{"success": false, "status_code": 422, "message": "...", "errors": [{"field": "email", "code": "missing", "message": "Email is required."}]}
|
|
304
|
+
```
|
|
305
|
+
|
|
306
|
+
Notes:
|
|
307
|
+
|
|
308
|
+
- Installation is idempotent; calling it twice leaves the first handlers in
|
|
309
|
+
place. Register a handler after installation if you need to override one.
|
|
310
|
+
- Validation failures keep Pydantic's order, drop duplicates, and use the
|
|
311
|
+
catalog message unless the definition is dynamic.
|
|
312
|
+
- Unhandled exceptions are logged at `ERROR` (with the traceback) but never leak
|
|
313
|
+
the traceback to clients. Pass `debug=True` to add a `debug` object with the
|
|
314
|
+
exception type and traceback to 500 responses.
|
|
315
|
+
- `logger` defaults to a package-level logger; pass your own for integration
|
|
316
|
+
with application logging.
|
|
317
|
+
|
|
318
|
+
## Reference table
|
|
319
|
+
|
|
320
|
+
Every public name is importable from `fastapi_response_handler`.
|
|
321
|
+
|
|
322
|
+
| Public name | Purpose | Signature |
|
|
323
|
+
| --- | --- | --- |
|
|
324
|
+
| `DYNAMIC_MESSAGE` | Sentinel marking a definition whose text comes from the caller. | `str` |
|
|
325
|
+
| `ErrorCatalog` | Validated, immutable catalog of field groups. | `ErrorCatalog(groups=())` |
|
|
326
|
+
| `FieldErrors` | Typed field group accepted by the catalog. | `FieldErrors(field, errors)` |
|
|
327
|
+
| `ErrorDefinition` | Frozen, hashable error definition. | `ErrorDefinition(status, code, message, field=None)` |
|
|
328
|
+
| `FieldView` | Field-scoped view returned by `catalog.<field>`. | `catalog.email.missing`, `catalog.email.get(code)`, `catalog.email[code]` |
|
|
329
|
+
| `ApiError` | `HTTPException`-style error raised by services. | `ApiError(status_code, message, *, code="api_error", field=None, headers=None)` |
|
|
330
|
+
| `ApiResponse[T]` | Generic success envelope; subclass it to declare defaults. | `ApiResponse[T](status_code, message, data=None, success=True)` |
|
|
331
|
+
| `ApiErrorResponse` | Error envelope. | `ApiErrorResponse(status_code, message, errors=[])` |
|
|
332
|
+
| `ErrorItem` | One `{field, code, message}` item in an error response. | `ErrorItem(field, code, message)`; `ErrorItem.from_definition(field, definition, message=None)` |
|
|
333
|
+
| `success_response` | Build a validated success envelope. | `success_response(data, message="Success", status_code=200)` |
|
|
334
|
+
| `success_example` | OpenAPI entry (schema + example) for a success class. | `success_example(model) -> {status_code: {...}}` |
|
|
335
|
+
| `status_description` | OpenAPI description for a status code. | `status_description(status)` |
|
|
336
|
+
| `pydantic_error` | Catalog error as a `PydanticCustomError` for validators. | `pydantic_error(catalog, field, code, **format_kwargs)` |
|
|
337
|
+
| `PYDANTIC_TYPE_TO_CODE` | Extensible map from Pydantic error type to code. | `dict[str, str]` |
|
|
338
|
+
| `field_from_loc` | Turn a Pydantic error location into a field name. | `field_from_loc(loc) -> str` |
|
|
339
|
+
| `register_additional_errors` | Add one definition, returning a new catalog. | `register_additional_errors(catalog, field, definition)` |
|
|
340
|
+
| `resolve_validation_error` | Resolve one Pydantic error against the catalog. | `resolve_validation_error(catalog, error) -> ResolvedError` |
|
|
341
|
+
| `resolve_validation_errors` | Resolve and deduplicate a list of Pydantic errors. | `resolve_validation_errors(catalog, errors) -> list[ResolvedError]` |
|
|
342
|
+
| `validation_status` | Pick the response status (highest non-422 wins). | `validation_status(resolved) -> int` |
|
|
343
|
+
| `ResolvedError` | Normalized field/code/message/status for one error. | `ResolvedError(field, code, message, status, definition=None)` |
|
|
344
|
+
| `responses_for` | FastAPI `responses=` mapping for catalog errors. | `responses_for(catalog, *fields, message=None)` |
|
|
345
|
+
| `successes_for` | FastAPI `responses=` mapping for success models. | `successes_for(*models)` |
|
|
346
|
+
| `build_openapi_examples` | Same as `responses_for`, without `model` keys. | `build_openapi_examples(catalog, *fields, message=None)` |
|
|
347
|
+
| `install_error_handlers` | Install the four global handlers. | `install_error_handlers(app, *, catalog=None, debug=False, logger=None)` |
|
|
348
|
+
| `SuccessResponse` / `ErrorResponse` | Aliases for `ApiResponse` / `ApiErrorResponse`. | — |
|
|
349
|
+
|
|
350
|
+
Catalog methods: `catalog.get(field, code, default=None)`, `find(code)`,
|
|
351
|
+
`fields`, `iter_groups()`, `merge(*others)`, `add(field, definition)`.
|
|
352
|
+
Import from the package root; the submodules are available for advanced use but
|
|
353
|
+
the root exports are the supported surface.
|
|
354
|
+
|
|
355
|
+
## Putting the scenario together
|
|
356
|
+
|
|
357
|
+
With the catalog defined above, the registration schema and route are the only
|
|
358
|
+
application code needed:
|
|
359
|
+
|
|
360
|
+
```python
|
|
361
|
+
import re
|
|
362
|
+
from typing import Literal
|
|
363
|
+
|
|
364
|
+
from fastapi import APIRouter, FastAPI
|
|
365
|
+
from pydantic import BaseModel, ConfigDict, EmailStr, field_validator, model_validator
|
|
366
|
+
|
|
367
|
+
from fastapi_response_handler import (
|
|
368
|
+
install_error_handlers,
|
|
369
|
+
pydantic_error,
|
|
370
|
+
responses_for,
|
|
371
|
+
successes_for,
|
|
372
|
+
)
|
|
373
|
+
|
|
374
|
+
PASSWORD_PATTERN = re.compile(r"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^A-Za-z0-9]).{8,}$")
|
|
375
|
+
|
|
376
|
+
|
|
377
|
+
class UserCreate(BaseModel):
|
|
378
|
+
model_config = ConfigDict(extra="forbid")
|
|
379
|
+
|
|
380
|
+
name: str
|
|
381
|
+
email: EmailStr
|
|
382
|
+
phone: str
|
|
383
|
+
role: Literal["Teacher", "Student"]
|
|
384
|
+
password: str
|
|
385
|
+
confirm_password: str
|
|
386
|
+
|
|
387
|
+
@field_validator("phone")
|
|
388
|
+
@classmethod
|
|
389
|
+
def validate_phone(cls, value: str) -> str:
|
|
390
|
+
if not re.fullmatch(r"[6-9]\d{9}", value):
|
|
391
|
+
raise pydantic_error(catalog, "phone", "indian_phone_error")
|
|
392
|
+
return value
|
|
393
|
+
|
|
394
|
+
@field_validator("password")
|
|
395
|
+
@classmethod
|
|
396
|
+
def validate_password(cls, value: str) -> str:
|
|
397
|
+
if not PASSWORD_PATTERN.fullmatch(value):
|
|
398
|
+
raise pydantic_error(catalog, "password", "invalid_password")
|
|
399
|
+
return value
|
|
400
|
+
|
|
401
|
+
@model_validator(mode="after")
|
|
402
|
+
def validate_confirm_password(self) -> "UserCreate":
|
|
403
|
+
if self.password != self.confirm_password:
|
|
404
|
+
raise pydantic_error(catalog, "confirm_password", "password_not_matched")
|
|
405
|
+
return self
|
|
406
|
+
|
|
407
|
+
|
|
408
|
+
router = APIRouter()
|
|
409
|
+
|
|
410
|
+
|
|
411
|
+
@router.post(
|
|
412
|
+
"/register",
|
|
413
|
+
status_code=201,
|
|
414
|
+
response_model=UserRegisterSuccessResponse,
|
|
415
|
+
responses={
|
|
416
|
+
**responses_for(
|
|
417
|
+
catalog,
|
|
418
|
+
"name", "email", "phone", "role", "password", "confirm_password",
|
|
419
|
+
),
|
|
420
|
+
**successes_for(UserRegisterSuccessResponse),
|
|
421
|
+
},
|
|
422
|
+
)
|
|
423
|
+
async def register_user(payload: UserCreate) -> UserRegisterSuccessResponse:
|
|
424
|
+
if await email_is_taken(payload.email):
|
|
425
|
+
raise catalog.email.email_already_exists.as_exception()
|
|
426
|
+
return UserRegisterSuccessResponse(data=await create_user(payload))
|
|
427
|
+
|
|
428
|
+
|
|
429
|
+
app = FastAPI()
|
|
430
|
+
app.include_router(router)
|
|
431
|
+
install_error_handlers(app, catalog=catalog)
|
|
432
|
+
```
|
|
433
|
+
|
|
434
|
+
With that, missing `email` and `phone` produce one `422` with two items
|
|
435
|
+
(`email`/`missing`, `phone`/`missing`), `role: "Admin"` produces
|
|
436
|
+
`literal_error`, an invalid phone produces `indian_phone_error`, a password
|
|
437
|
+
mismatch produces `password_not_matched`, a duplicate email produces `409`, and
|
|
438
|
+
an unhandled exception produces the generic `500` envelope. The full executable
|
|
439
|
+
version lives in `tests/test_registration_contract.py`.
|
|
440
|
+
|
|
441
|
+
## How it renders in /docs
|
|
442
|
+
|
|
443
|
+
FastAPI turns the `responses=` entries into one response block per status. Under
|
|
444
|
+
`/docs`, the register endpoint shows:
|
|
445
|
+
|
|
446
|
+
- a `201` response with the `UserRegisterSuccessResponse` schema and a filled
|
|
447
|
+
example body;
|
|
448
|
+
- a `409 Conflict` response with a dropdown containing the
|
|
449
|
+
`User with this email is already registered.` example;
|
|
450
|
+
- a `422 Validation failed` response with a dropdown containing one example per
|
|
451
|
+
declared code, labelled with its catalog message (`Name is required.`,
|
|
452
|
+
`Email is required.`, `Passwords do not match.`, …). Repeated messages gain
|
|
453
|
+
their code in parentheses.
|
|
454
|
+
|
|
455
|
+
The generated `/openapi.json` fragment for a conflict looks like:
|
|
456
|
+
|
|
457
|
+
```json
|
|
458
|
+
{
|
|
459
|
+
"409": {
|
|
460
|
+
"description": "Conflict",
|
|
461
|
+
"content": {
|
|
462
|
+
"application/json": {
|
|
463
|
+
"examples": {
|
|
464
|
+
"User with this email is already registered.": {
|
|
465
|
+
"summary": "User with this email is already registered.",
|
|
466
|
+
"value": {
|
|
467
|
+
"success": false,
|
|
468
|
+
"status_code": 409,
|
|
469
|
+
"message": "User with this email is already registered.",
|
|
470
|
+
"errors": [{
|
|
471
|
+
"field": "email",
|
|
472
|
+
"code": "email_already_exists",
|
|
473
|
+
"message": "User with this email is already registered."
|
|
474
|
+
}]
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
```
|
|
483
|
+
|
|
484
|
+
Reviewers see the real message text and real field names, not placeholder
|
|
485
|
+
schemas, because both come from the same catalog the handlers use.
|
|
486
|
+
|
|
487
|
+
## Recipes
|
|
488
|
+
|
|
489
|
+
**Add a new error.** Append a definition (or call `add` without mutating):
|
|
490
|
+
|
|
491
|
+
```python
|
|
492
|
+
catalog = catalog.add(
|
|
493
|
+
"email",
|
|
494
|
+
{"status": 422, "code": "disposable_email", "message": "Disposable emails are not allowed."},
|
|
495
|
+
)
|
|
496
|
+
```
|
|
497
|
+
|
|
498
|
+
**Share one error between a validator and a service.** Declare it once; the
|
|
499
|
+
service calls `as_exception()` and the validator calls `pydantic_error(...)`.
|
|
500
|
+
A non-422 status raised by a validator is preserved: the handler returns the
|
|
501
|
+
highest resolved status (409 beats 422).
|
|
502
|
+
|
|
503
|
+
**Customize the success envelope.** Subclass `ApiResponse` with a different
|
|
504
|
+
field set or defaults and use it as `response_model`; `successes_for` documents
|
|
505
|
+
it automatically. For a custom *error* envelope, register your own handler after
|
|
506
|
+
`install_error_handlers`; later registrations always win.
|
|
507
|
+
|
|
508
|
+
**Debug a 500 locally.** `install_error_handlers(app, debug=True)` adds
|
|
509
|
+
`debug: {"type", "traceback"}` to 500 bodies. Leave it off in production.
|
|
510
|
+
|
|
511
|
+
**Teach it a new Pydantic error type.** Extend the exported map before requests
|
|
512
|
+
arrive; the value becomes the catalog code looked up for that type:
|
|
513
|
+
|
|
514
|
+
```python
|
|
515
|
+
from fastapi_response_handler import PYDANTIC_TYPE_TO_CODE
|
|
516
|
+
PYDANTIC_TYPE_TO_CODE["my_custom_type"] = "my_custom_code"
|
|
517
|
+
```
|
|
518
|
+
|
|
519
|
+
**Use a different logger.** Pass `logger=my_logger` to route 5xx reports into
|
|
520
|
+
your application logger; 5xx records include the traceback via `exc_info`.
|
|
521
|
+
|
|
522
|
+
## Compatibility and limitations
|
|
523
|
+
|
|
524
|
+
- Python 3.10+, FastAPI, Pydantic v2. The test matrix is exercised on the
|
|
525
|
+
current FastAPI/Pydantic releases; behavior relies on public Starlette
|
|
526
|
+
exception-handler APIs.
|
|
527
|
+
- The package controls error and success *envelopes* it renders. It does not
|
|
528
|
+
wrap arbitrary response bodies you return from routes, and it does not replace
|
|
529
|
+
`response_model`; use `ApiResponse` subclasses for that.
|
|
530
|
+
- `StarletteHTTPException.detail` is passed through as `message`; when it is a
|
|
531
|
+
dict, its `message` key is used and the remaining payload is not included.
|
|
532
|
+
- 500 responses never include a traceback unless `debug=True`; the log record
|
|
533
|
+
always does.
|
|
534
|
+
- Examples are generated from JSON Schema, so unusual custom schemas may need an
|
|
535
|
+
explicit `json_schema_extra={"example": ...}`.
|
|
536
|
+
- Versioning follows semantic versioning at `0.1.x`; catalog declarations are
|
|
537
|
+
treated as application data, so additive changes are minor releases.
|
|
538
|
+
|
|
539
|
+
## Development
|
|
540
|
+
|
|
541
|
+
```bash
|
|
542
|
+
python -m venv .venv
|
|
543
|
+
.venv/bin/pip install -e ".[dev]"
|
|
544
|
+
.venv/bin/python -m pytest
|
|
545
|
+
```
|
|
546
|
+
|
|
547
|
+
The package is typed (`py.typed`) and targets Python 3.10+.
|
|
548
|
+
|
|
549
|
+
## License
|
|
550
|
+
|
|
551
|
+
MIT
|