fastapi-rfc9457 0.2.2__tar.gz → 0.2.4__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_rfc9457-0.2.2 → fastapi_rfc9457-0.2.4}/PKG-INFO +69 -42
- {fastapi_rfc9457-0.2.2 → fastapi_rfc9457-0.2.4}/README.md +67 -41
- {fastapi_rfc9457-0.2.2 → fastapi_rfc9457-0.2.4}/example/README.md +5 -5
- {fastapi_rfc9457-0.2.2 → fastapi_rfc9457-0.2.4}/pyproject.toml +5 -6
- {fastapi_rfc9457-0.2.2 → fastapi_rfc9457-0.2.4}/src/fastapi_rfc9457/__init__.py +6 -1
- {fastapi_rfc9457-0.2.2 → fastapi_rfc9457-0.2.4}/src/fastapi_rfc9457/_version.py +2 -2
- {fastapi_rfc9457-0.2.2 → fastapi_rfc9457-0.2.4}/src/fastapi_rfc9457/builtins.py +18 -6
- {fastapi_rfc9457-0.2.2 → fastapi_rfc9457-0.2.4}/src/fastapi_rfc9457/client.py +3 -3
- {fastapi_rfc9457-0.2.2 → fastapi_rfc9457-0.2.4}/src/fastapi_rfc9457/docs.py +7 -1
- {fastapi_rfc9457-0.2.2 → fastapi_rfc9457-0.2.4}/src/fastapi_rfc9457/handlers.py +17 -2
- {fastapi_rfc9457-0.2.2 → fastapi_rfc9457-0.2.4}/src/fastapi_rfc9457/integration.py +4 -12
- {fastapi_rfc9457-0.2.2 → fastapi_rfc9457-0.2.4}/src/fastapi_rfc9457/openapi.py +22 -4
- fastapi_rfc9457-0.2.4/src/fastapi_rfc9457/problem.py +344 -0
- {fastapi_rfc9457-0.2.2 → fastapi_rfc9457-0.2.4}/tests/static/valid_usage.py +35 -1
- fastapi_rfc9457-0.2.4/tests/test_abstract.py +81 -0
- fastapi_rfc9457-0.2.4/tests/test_lifespan.py +46 -0
- {fastapi_rfc9457-0.2.2 → fastapi_rfc9457-0.2.4}/tests/test_openapi.py +28 -0
- {fastapi_rfc9457-0.2.2 → fastapi_rfc9457-0.2.4}/tests/test_problem.py +63 -3
- {fastapi_rfc9457-0.2.2 → fastapi_rfc9457-0.2.4}/tests/test_public_api.py +3 -0
- fastapi_rfc9457-0.2.4/tests/test_response_headers.py +325 -0
- fastapi_rfc9457-0.2.2/src/fastapi_rfc9457/problem.py +0 -199
- fastapi_rfc9457-0.2.2/tests/test_lifespan.py +0 -44
- fastapi_rfc9457-0.2.2/tests/test_response_headers.py +0 -143
- {fastapi_rfc9457-0.2.2 → fastapi_rfc9457-0.2.4}/.gitignore +0 -0
- {fastapi_rfc9457-0.2.2 → fastapi_rfc9457-0.2.4}/LICENSE +0 -0
- {fastapi_rfc9457-0.2.2 → fastapi_rfc9457-0.2.4}/src/fastapi_rfc9457/models.py +0 -0
- {fastapi_rfc9457-0.2.2 → fastapi_rfc9457-0.2.4}/src/fastapi_rfc9457/py.typed +0 -0
- {fastapi_rfc9457-0.2.2 → fastapi_rfc9457-0.2.4}/src/fastapi_rfc9457/server.py +0 -0
- {fastapi_rfc9457-0.2.2 → fastapi_rfc9457-0.2.4}/src/fastapi_rfc9457/uris.py +0 -0
- {fastapi_rfc9457-0.2.2 → fastapi_rfc9457-0.2.4}/tests/conftest.py +0 -0
- {fastapi_rfc9457-0.2.2 → fastapi_rfc9457-0.2.4}/tests/static/expected_errors.py +0 -0
- {fastapi_rfc9457-0.2.2 → fastapi_rfc9457-0.2.4}/tests/test_builtins.py +0 -0
- {fastapi_rfc9457-0.2.2 → fastapi_rfc9457-0.2.4}/tests/test_client.py +0 -0
- {fastapi_rfc9457-0.2.2 → fastapi_rfc9457-0.2.4}/tests/test_client_install.py +0 -0
- {fastapi_rfc9457-0.2.2 → fastapi_rfc9457-0.2.4}/tests/test_docs.py +0 -0
- {fastapi_rfc9457-0.2.2 → fastapi_rfc9457-0.2.4}/tests/test_example.py +0 -0
- {fastapi_rfc9457-0.2.2 → fastapi_rfc9457-0.2.4}/tests/test_example_client.py +0 -0
- {fastapi_rfc9457-0.2.2 → fastapi_rfc9457-0.2.4}/tests/test_extension_fields_pep563.py +0 -0
- {fastapi_rfc9457-0.2.2 → fastapi_rfc9457-0.2.4}/tests/test_handlers.py +0 -0
- {fastapi_rfc9457-0.2.2 → fastapi_rfc9457-0.2.4}/tests/test_integration.py +0 -0
- {fastapi_rfc9457-0.2.2 → fastapi_rfc9457-0.2.4}/tests/test_models.py +0 -0
- {fastapi_rfc9457-0.2.2 → fastapi_rfc9457-0.2.4}/tests/test_static_typing.py +0 -0
- {fastapi_rfc9457-0.2.2 → fastapi_rfc9457-0.2.4}/tests/test_type_uri_resolution.py +0 -0
- {fastapi_rfc9457-0.2.2 → fastapi_rfc9457-0.2.4}/tests/test_yield_dependency.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: fastapi-rfc9457
|
|
3
|
-
Version: 0.2.
|
|
3
|
+
Version: 0.2.4
|
|
4
4
|
Summary: Typed, batteries-included RFC 9457 Problem Details for FastAPI & Pydantic v2.
|
|
5
5
|
Project-URL: Repository, https://github.com/PythonFZ/fastapi-rfc9457
|
|
6
6
|
Project-URL: Releases, https://github.com/PythonFZ/fastapi-rfc9457/releases
|
|
@@ -9,6 +9,7 @@ License-Expression: MIT
|
|
|
9
9
|
License-File: LICENSE
|
|
10
10
|
Requires-Python: >=3.11
|
|
11
11
|
Requires-Dist: pydantic>=2.13.4
|
|
12
|
+
Requires-Dist: typing-extensions>=4.15.0
|
|
12
13
|
Provides-Extra: server
|
|
13
14
|
Requires-Dist: fastapi>=0.137.2; extra == 'server'
|
|
14
15
|
Description-Content-Type: text/markdown
|
|
@@ -17,11 +18,9 @@ Description-Content-Type: text/markdown
|
|
|
17
18
|
|
|
18
19
|
[](https://pypi.org/project/fastapi-rfc9457/)
|
|
19
20
|
|
|
20
|
-
Typed, batteries-included [RFC 9457](https://www.rfc-editor.org/rfc/rfc9457.html)
|
|
21
|
-
"Problem Details for HTTP APIs" for FastAPI & Pydantic.
|
|
21
|
+
Typed, batteries-included [RFC 9457](https://www.rfc-editor.org/rfc/rfc9457.html) "Problem Details for HTTP APIs" for FastAPI & Pydantic.
|
|
22
22
|
|
|
23
|
-
Define an error once - it serializes as `application/problem+json`, documents
|
|
24
|
-
itself in OpenAPI, and parses back into a typed exception on the client.
|
|
23
|
+
Define an error once - it serializes as `application/problem+json`, documents itself in OpenAPI, and parses back into a typed exception on the client.
|
|
25
24
|
|
|
26
25
|
```python
|
|
27
26
|
from fastapi import FastAPI
|
|
@@ -32,20 +31,22 @@ from fastapi_rfc9457.server import add_problem_handlers, get_problem_docs_router
|
|
|
32
31
|
|
|
33
32
|
class OutOfCredit(Problem):
|
|
34
33
|
"""The account does not have enough credit."""
|
|
34
|
+
|
|
35
35
|
title = "Out of Credit"
|
|
36
36
|
status = 403
|
|
37
|
-
balance: int
|
|
37
|
+
balance: int # typed extension members, checked at the raise site
|
|
38
38
|
accounts: list[str]
|
|
39
39
|
|
|
40
40
|
|
|
41
41
|
class AccountSuspended(Problem):
|
|
42
42
|
"""The account is suspended and cannot be charged."""
|
|
43
|
+
|
|
43
44
|
title = "Account Suspended"
|
|
44
45
|
status = 403
|
|
45
46
|
|
|
46
47
|
|
|
47
48
|
app = FastAPI()
|
|
48
|
-
add_problem_handlers(app)
|
|
49
|
+
add_problem_handlers(app) # handlers + problem+json OpenAPI
|
|
49
50
|
app.include_router(get_problem_docs_router(), prefix="/problems") # dereferenceable type URIs
|
|
50
51
|
|
|
51
52
|
|
|
@@ -56,86 +57,110 @@ async def charge() -> dict:
|
|
|
56
57
|
|
|
57
58
|
## Accurate OpenAPI, for free
|
|
58
59
|
|
|
59
|
-
One route can declare several failure modes.
|
|
60
|
-
response; same-status problems become a `oneOf` union you flip through in
|
|
61
|
-
Swagger's **Examples** dropdown — all under `application/problem+json`.
|
|
60
|
+
One route can declare several failure modes.
|
|
61
|
+
Distinct statuses get their own response; same-status problems become a `oneOf` union you flip through in Swagger's **Examples** dropdown — all under `application/problem+json`.
|
|
62
62
|
|
|
63
63
|

|
|
64
64
|
|
|
65
|
-
|
|
66
|
-
|
|
67
65
|
## Dereferenceable `type` URIs
|
|
68
66
|
|
|
69
|
-
Mount the docs router and every problem `type` resolves to a live page listing
|
|
70
|
-
its typed extension members.
|
|
67
|
+
Mount the docs router and every problem `type` resolves to a live page listing its typed extension members.
|
|
71
68
|
|
|
72
|
-
The `type`
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
explicitly to emit a literal URI instead.
|
|
69
|
+
The `type` follows the docs-router mount: mount at `prefix="/problems"` and `OutOfCredit` emits and serves `/problems/out-of-credit`.
|
|
70
|
+
Change the prefix and bodies, OpenAPI, and doc pages move together.
|
|
71
|
+
Set `type` on the class to emit a literal URI.
|
|
76
72
|
|
|
77
73
|

|
|
78
74
|
|
|
79
75
|
## Response headers
|
|
80
76
|
|
|
81
|
-
A problem type declares the headers it sends in `headers` (name → OpenAPI description) and
|
|
82
|
-
|
|
77
|
+
A problem type declares the headers it sends in `headers` (name → OpenAPI description) and returns their values from `response_headers()`.
|
|
78
|
+
The built-ins send the headers RFC 9110 asks for:
|
|
83
79
|
|
|
84
80
|
```python
|
|
85
|
-
raise NotAuthenticated()
|
|
86
|
-
raise TooManyRequests(retry_after=30)
|
|
87
|
-
raise
|
|
81
|
+
raise NotAuthenticated() # WWW-Authenticate: Bearer
|
|
82
|
+
raise TooManyRequests(retry_after=30) # Retry-After: 30
|
|
83
|
+
raise ServiceUnavailable(retry_after=120) # Retry-After: 120
|
|
84
|
+
raise MethodNotAllowed(allow=["GET"]) # Allow: GET
|
|
85
|
+
|
|
88
86
|
|
|
89
87
|
class BasicAuthRequired(NotAuthenticated):
|
|
90
|
-
challenge = 'Basic realm="api"'
|
|
88
|
+
challenge = 'Basic realm="api"' # WWW-Authenticate: Basic realm="api"
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
A custom problem type declares its own headers:
|
|
92
|
+
|
|
93
|
+
```python
|
|
94
|
+
class Moved(Problem):
|
|
95
|
+
title, status = "Moved", 410
|
|
96
|
+
location: str
|
|
97
|
+
headers: ClassVar[Mapping[str, str]] = {"Location": "The new URL of the resource."}
|
|
98
|
+
|
|
99
|
+
def response_headers(self) -> Mapping[str, str]:
|
|
100
|
+
return {"Location": self.location}
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
Each class declares only its own `headers`, `response_headers()` and `header_examples()`; the library merges them with those of its bases, and sending an undeclared header emits `UndeclaredHeaderWarning`.
|
|
104
|
+
|
|
105
|
+
## Shared bases
|
|
106
|
+
|
|
107
|
+
A class missing `title` or `status` raises `TypeError` when defined; mark shared bases `abstract=True`:
|
|
108
|
+
|
|
109
|
+
```python
|
|
110
|
+
class Audited(Problem, abstract=True):
|
|
111
|
+
audit_id: str # every subclass carries it
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
class Throttled(RetryAfter): # built-in abstract base: retry_after + Retry-After
|
|
115
|
+
title, status = "Throttled", 429
|
|
91
116
|
```
|
|
92
117
|
|
|
93
118
|
## Typed exceptions on the client
|
|
94
119
|
|
|
95
|
-
Client-side, the package can parse
|
|
96
|
-
`application/problem+json` back into typed problems the server raised.
|
|
120
|
+
Client-side, the package can parse `application/problem+json` back into typed problems the server raised.
|
|
97
121
|
|
|
98
122
|
```python
|
|
99
|
-
import
|
|
123
|
+
import httpx2
|
|
100
124
|
from fastapi_rfc9457 import Problem, httpx_raise_hook
|
|
101
125
|
|
|
102
126
|
|
|
103
|
-
class OutOfCredit(Problem):
|
|
127
|
+
class OutOfCredit(Problem): # the type the server declares, shared or re-stated
|
|
104
128
|
title = "Out of Credit"
|
|
105
129
|
status = 403
|
|
106
130
|
balance: int
|
|
107
131
|
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
event_hooks={
|
|
111
|
-
|
|
112
|
-
}) as client:
|
|
132
|
+
|
|
133
|
+
with httpx2.Client(
|
|
134
|
+
base_url="http://localhost:8000", event_hooks={"response": [httpx_raise_hook()]}
|
|
135
|
+
) as client:
|
|
113
136
|
try:
|
|
114
137
|
client.get("/charge")
|
|
115
138
|
except OutOfCredit as exc:
|
|
116
|
-
print(exc.balance)
|
|
139
|
+
print(exc.balance) # extension members round-trip back as typed attributes
|
|
117
140
|
```
|
|
118
141
|
|
|
119
|
-
Prefer to parse explicitly? `parse_problem(response)` returns the typed `Problem`
|
|
120
|
-
(or a generic `ProblemDetail` for an unknown `type`), and `raise_for_problem(response)`
|
|
121
|
-
raises it.
|
|
142
|
+
Prefer to parse explicitly? `parse_problem(response)` returns the typed `Problem` (or a generic `ProblemDetail` for an unknown `type`), and `raise_for_problem(response)` raises it (`ProblemError` for an unknown `type`).
|
|
122
143
|
|
|
123
144
|
## Comparison with native FastAPI
|
|
124
|
-
|
|
145
|
+
|
|
146
|
+
The same endpoint written the way FastAPI's [Handling Errors](https://fastapi.tiangolo.com/tutorial/handling-errors/) tutorial shows:
|
|
125
147
|
|
|
126
148
|
```python
|
|
127
149
|
class OutOfCreditError(Exception):
|
|
128
150
|
def __init__(self, detail: str, balance: int) -> None:
|
|
129
151
|
self.detail, self.balance = detail, balance
|
|
130
152
|
|
|
153
|
+
|
|
131
154
|
@app.exception_handler(OutOfCreditError)
|
|
132
155
|
async def _(request: Request, exc: OutOfCreditError) -> JSONResponse:
|
|
133
156
|
return JSONResponse({"detail": exc.detail, "balance": exc.balance}, 403)
|
|
134
157
|
|
|
158
|
+
|
|
135
159
|
class OutOfCreditBody(BaseModel):
|
|
136
160
|
detail: str
|
|
137
161
|
balance: int
|
|
138
162
|
|
|
163
|
+
|
|
139
164
|
@app.get("/charge", responses={403: {"model": OutOfCreditBody}})
|
|
140
165
|
async def charge(token: str | None = None) -> dict:
|
|
141
166
|
if token is None:
|
|
@@ -148,11 +173,13 @@ async def charge(token: str | None = None) -> dict:
|
|
|
148
173
|
from fastapi_rfc9457 import NotAuthenticated, Problem # NotAuthenticated ships built in
|
|
149
174
|
from fastapi_rfc9457.server import problems
|
|
150
175
|
|
|
176
|
+
|
|
151
177
|
class OutOfCredit(Problem):
|
|
152
178
|
title = "Out of Credit"
|
|
153
179
|
status = 403
|
|
154
180
|
balance: int
|
|
155
181
|
|
|
182
|
+
|
|
156
183
|
@app.get("/charge", responses=problems(NotAuthenticated, OutOfCredit))
|
|
157
184
|
async def charge(token: str | None = None) -> dict:
|
|
158
185
|
if token is None:
|
|
@@ -187,10 +214,10 @@ uv add fastapi-rfc9457 # lean client: author + parse problems, Pydanti
|
|
|
187
214
|
cd example && uv run uvicorn main:app --reload # then open localhost:8000/docs
|
|
188
215
|
```
|
|
189
216
|
|
|
190
|
-
See [`example/`](./example) for the full
|
|
191
|
-
[`example/client.py`](./example/client.py) for the httpx hook (`uv add fastapi-rfc9457 httpx`)
|
|
192
|
-
that raises those problems back as typed exceptions on the consumer side.
|
|
217
|
+
See [`example/`](./example) for the full app and [`example/client.py`](./example/client.py) for a client using it.
|
|
193
218
|
|
|
194
219
|
## Notes
|
|
195
220
|
|
|
196
|
-
-
|
|
221
|
+
- Every error answers with `application/problem+json`: raised problems, `HTTPException`, request validation (422), and unhandled exceptions (500).
|
|
222
|
+
- 500 bodies include the exception message by default.
|
|
223
|
+
Pass `add_problem_handlers(app, strip_debug=True)` in production to redact it and the offending input on 422s.
|
|
@@ -2,11 +2,9 @@
|
|
|
2
2
|
|
|
3
3
|
[](https://pypi.org/project/fastapi-rfc9457/)
|
|
4
4
|
|
|
5
|
-
Typed, batteries-included [RFC 9457](https://www.rfc-editor.org/rfc/rfc9457.html)
|
|
6
|
-
"Problem Details for HTTP APIs" for FastAPI & Pydantic.
|
|
5
|
+
Typed, batteries-included [RFC 9457](https://www.rfc-editor.org/rfc/rfc9457.html) "Problem Details for HTTP APIs" for FastAPI & Pydantic.
|
|
7
6
|
|
|
8
|
-
Define an error once - it serializes as `application/problem+json`, documents
|
|
9
|
-
itself in OpenAPI, and parses back into a typed exception on the client.
|
|
7
|
+
Define an error once - it serializes as `application/problem+json`, documents itself in OpenAPI, and parses back into a typed exception on the client.
|
|
10
8
|
|
|
11
9
|
```python
|
|
12
10
|
from fastapi import FastAPI
|
|
@@ -17,20 +15,22 @@ from fastapi_rfc9457.server import add_problem_handlers, get_problem_docs_router
|
|
|
17
15
|
|
|
18
16
|
class OutOfCredit(Problem):
|
|
19
17
|
"""The account does not have enough credit."""
|
|
18
|
+
|
|
20
19
|
title = "Out of Credit"
|
|
21
20
|
status = 403
|
|
22
|
-
balance: int
|
|
21
|
+
balance: int # typed extension members, checked at the raise site
|
|
23
22
|
accounts: list[str]
|
|
24
23
|
|
|
25
24
|
|
|
26
25
|
class AccountSuspended(Problem):
|
|
27
26
|
"""The account is suspended and cannot be charged."""
|
|
27
|
+
|
|
28
28
|
title = "Account Suspended"
|
|
29
29
|
status = 403
|
|
30
30
|
|
|
31
31
|
|
|
32
32
|
app = FastAPI()
|
|
33
|
-
add_problem_handlers(app)
|
|
33
|
+
add_problem_handlers(app) # handlers + problem+json OpenAPI
|
|
34
34
|
app.include_router(get_problem_docs_router(), prefix="/problems") # dereferenceable type URIs
|
|
35
35
|
|
|
36
36
|
|
|
@@ -41,86 +41,110 @@ async def charge() -> dict:
|
|
|
41
41
|
|
|
42
42
|
## Accurate OpenAPI, for free
|
|
43
43
|
|
|
44
|
-
One route can declare several failure modes.
|
|
45
|
-
response; same-status problems become a `oneOf` union you flip through in
|
|
46
|
-
Swagger's **Examples** dropdown — all under `application/problem+json`.
|
|
44
|
+
One route can declare several failure modes.
|
|
45
|
+
Distinct statuses get their own response; same-status problems become a `oneOf` union you flip through in Swagger's **Examples** dropdown — all under `application/problem+json`.
|
|
47
46
|
|
|
48
47
|

|
|
49
48
|
|
|
50
|
-
|
|
51
|
-
|
|
52
49
|
## Dereferenceable `type` URIs
|
|
53
50
|
|
|
54
|
-
Mount the docs router and every problem `type` resolves to a live page listing
|
|
55
|
-
its typed extension members.
|
|
51
|
+
Mount the docs router and every problem `type` resolves to a live page listing its typed extension members.
|
|
56
52
|
|
|
57
|
-
The `type`
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
explicitly to emit a literal URI instead.
|
|
53
|
+
The `type` follows the docs-router mount: mount at `prefix="/problems"` and `OutOfCredit` emits and serves `/problems/out-of-credit`.
|
|
54
|
+
Change the prefix and bodies, OpenAPI, and doc pages move together.
|
|
55
|
+
Set `type` on the class to emit a literal URI.
|
|
61
56
|
|
|
62
57
|

|
|
63
58
|
|
|
64
59
|
## Response headers
|
|
65
60
|
|
|
66
|
-
A problem type declares the headers it sends in `headers` (name → OpenAPI description) and
|
|
67
|
-
|
|
61
|
+
A problem type declares the headers it sends in `headers` (name → OpenAPI description) and returns their values from `response_headers()`.
|
|
62
|
+
The built-ins send the headers RFC 9110 asks for:
|
|
68
63
|
|
|
69
64
|
```python
|
|
70
|
-
raise NotAuthenticated()
|
|
71
|
-
raise TooManyRequests(retry_after=30)
|
|
72
|
-
raise
|
|
65
|
+
raise NotAuthenticated() # WWW-Authenticate: Bearer
|
|
66
|
+
raise TooManyRequests(retry_after=30) # Retry-After: 30
|
|
67
|
+
raise ServiceUnavailable(retry_after=120) # Retry-After: 120
|
|
68
|
+
raise MethodNotAllowed(allow=["GET"]) # Allow: GET
|
|
69
|
+
|
|
73
70
|
|
|
74
71
|
class BasicAuthRequired(NotAuthenticated):
|
|
75
|
-
challenge = 'Basic realm="api"'
|
|
72
|
+
challenge = 'Basic realm="api"' # WWW-Authenticate: Basic realm="api"
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
A custom problem type declares its own headers:
|
|
76
|
+
|
|
77
|
+
```python
|
|
78
|
+
class Moved(Problem):
|
|
79
|
+
title, status = "Moved", 410
|
|
80
|
+
location: str
|
|
81
|
+
headers: ClassVar[Mapping[str, str]] = {"Location": "The new URL of the resource."}
|
|
82
|
+
|
|
83
|
+
def response_headers(self) -> Mapping[str, str]:
|
|
84
|
+
return {"Location": self.location}
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
Each class declares only its own `headers`, `response_headers()` and `header_examples()`; the library merges them with those of its bases, and sending an undeclared header emits `UndeclaredHeaderWarning`.
|
|
88
|
+
|
|
89
|
+
## Shared bases
|
|
90
|
+
|
|
91
|
+
A class missing `title` or `status` raises `TypeError` when defined; mark shared bases `abstract=True`:
|
|
92
|
+
|
|
93
|
+
```python
|
|
94
|
+
class Audited(Problem, abstract=True):
|
|
95
|
+
audit_id: str # every subclass carries it
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
class Throttled(RetryAfter): # built-in abstract base: retry_after + Retry-After
|
|
99
|
+
title, status = "Throttled", 429
|
|
76
100
|
```
|
|
77
101
|
|
|
78
102
|
## Typed exceptions on the client
|
|
79
103
|
|
|
80
|
-
Client-side, the package can parse
|
|
81
|
-
`application/problem+json` back into typed problems the server raised.
|
|
104
|
+
Client-side, the package can parse `application/problem+json` back into typed problems the server raised.
|
|
82
105
|
|
|
83
106
|
```python
|
|
84
|
-
import
|
|
107
|
+
import httpx2
|
|
85
108
|
from fastapi_rfc9457 import Problem, httpx_raise_hook
|
|
86
109
|
|
|
87
110
|
|
|
88
|
-
class OutOfCredit(Problem):
|
|
111
|
+
class OutOfCredit(Problem): # the type the server declares, shared or re-stated
|
|
89
112
|
title = "Out of Credit"
|
|
90
113
|
status = 403
|
|
91
114
|
balance: int
|
|
92
115
|
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
event_hooks={
|
|
96
|
-
|
|
97
|
-
}) as client:
|
|
116
|
+
|
|
117
|
+
with httpx2.Client(
|
|
118
|
+
base_url="http://localhost:8000", event_hooks={"response": [httpx_raise_hook()]}
|
|
119
|
+
) as client:
|
|
98
120
|
try:
|
|
99
121
|
client.get("/charge")
|
|
100
122
|
except OutOfCredit as exc:
|
|
101
|
-
print(exc.balance)
|
|
123
|
+
print(exc.balance) # extension members round-trip back as typed attributes
|
|
102
124
|
```
|
|
103
125
|
|
|
104
|
-
Prefer to parse explicitly? `parse_problem(response)` returns the typed `Problem`
|
|
105
|
-
(or a generic `ProblemDetail` for an unknown `type`), and `raise_for_problem(response)`
|
|
106
|
-
raises it.
|
|
126
|
+
Prefer to parse explicitly? `parse_problem(response)` returns the typed `Problem` (or a generic `ProblemDetail` for an unknown `type`), and `raise_for_problem(response)` raises it (`ProblemError` for an unknown `type`).
|
|
107
127
|
|
|
108
128
|
## Comparison with native FastAPI
|
|
109
|
-
|
|
129
|
+
|
|
130
|
+
The same endpoint written the way FastAPI's [Handling Errors](https://fastapi.tiangolo.com/tutorial/handling-errors/) tutorial shows:
|
|
110
131
|
|
|
111
132
|
```python
|
|
112
133
|
class OutOfCreditError(Exception):
|
|
113
134
|
def __init__(self, detail: str, balance: int) -> None:
|
|
114
135
|
self.detail, self.balance = detail, balance
|
|
115
136
|
|
|
137
|
+
|
|
116
138
|
@app.exception_handler(OutOfCreditError)
|
|
117
139
|
async def _(request: Request, exc: OutOfCreditError) -> JSONResponse:
|
|
118
140
|
return JSONResponse({"detail": exc.detail, "balance": exc.balance}, 403)
|
|
119
141
|
|
|
142
|
+
|
|
120
143
|
class OutOfCreditBody(BaseModel):
|
|
121
144
|
detail: str
|
|
122
145
|
balance: int
|
|
123
146
|
|
|
147
|
+
|
|
124
148
|
@app.get("/charge", responses={403: {"model": OutOfCreditBody}})
|
|
125
149
|
async def charge(token: str | None = None) -> dict:
|
|
126
150
|
if token is None:
|
|
@@ -133,11 +157,13 @@ async def charge(token: str | None = None) -> dict:
|
|
|
133
157
|
from fastapi_rfc9457 import NotAuthenticated, Problem # NotAuthenticated ships built in
|
|
134
158
|
from fastapi_rfc9457.server import problems
|
|
135
159
|
|
|
160
|
+
|
|
136
161
|
class OutOfCredit(Problem):
|
|
137
162
|
title = "Out of Credit"
|
|
138
163
|
status = 403
|
|
139
164
|
balance: int
|
|
140
165
|
|
|
166
|
+
|
|
141
167
|
@app.get("/charge", responses=problems(NotAuthenticated, OutOfCredit))
|
|
142
168
|
async def charge(token: str | None = None) -> dict:
|
|
143
169
|
if token is None:
|
|
@@ -172,10 +198,10 @@ uv add fastapi-rfc9457 # lean client: author + parse problems, Pydanti
|
|
|
172
198
|
cd example && uv run uvicorn main:app --reload # then open localhost:8000/docs
|
|
173
199
|
```
|
|
174
200
|
|
|
175
|
-
See [`example/`](./example) for the full
|
|
176
|
-
[`example/client.py`](./example/client.py) for the httpx hook (`uv add fastapi-rfc9457 httpx`)
|
|
177
|
-
that raises those problems back as typed exceptions on the consumer side.
|
|
201
|
+
See [`example/`](./example) for the full app and [`example/client.py`](./example/client.py) for a client using it.
|
|
178
202
|
|
|
179
203
|
## Notes
|
|
180
204
|
|
|
181
|
-
-
|
|
205
|
+
- Every error answers with `application/problem+json`: raised problems, `HTTPException`, request validation (422), and unhandled exceptions (500).
|
|
206
|
+
- 500 bodies include the exception message by default.
|
|
207
|
+
Pass `add_problem_handlers(app, strip_debug=True)` in production to redact it and the offending input on 422s.
|
|
@@ -15,9 +15,9 @@ curl -s localhost:8000/problems/out-of-credit # dereferenced type-doc page
|
|
|
15
15
|
`/charge` declares three problems via `problems(...)`: a 401 and a same-status
|
|
16
16
|
403 `oneOf` union (`OutOfCredit` / `AccountSuspended`) — see them in `/docs`.
|
|
17
17
|
|
|
18
|
-
## Consuming it with the
|
|
18
|
+
## Consuming it with the httpx2 hook
|
|
19
19
|
|
|
20
|
-
`fastapi-rfc9457` ships an
|
|
20
|
+
`fastapi-rfc9457` ships an httpx2 event hook that turns every
|
|
21
21
|
`application/problem+json` reply back into the same typed exception the server
|
|
22
22
|
raised. [`client.py`](./client.py) is a runnable consumer of the server above.
|
|
23
23
|
|
|
@@ -25,7 +25,7 @@ With the demo server running (above), in another shell from this `example/`
|
|
|
25
25
|
directory:
|
|
26
26
|
|
|
27
27
|
```bash
|
|
28
|
-
uv add fastapi-rfc9457
|
|
28
|
+
uv add fastapi-rfc9457 httpx2 # the lean client + your HTTP client
|
|
29
29
|
uv run client.py # connects to http://localhost:8000
|
|
30
30
|
```
|
|
31
31
|
|
|
@@ -38,8 +38,8 @@ OutOfCredit -> balance=30, accounts=['/accounts/12']
|
|
|
38
38
|
NotAuthenticated -> Log in to charge this account.
|
|
39
39
|
```
|
|
40
40
|
|
|
41
|
-
The hook is synchronous (`response.read()`), so it wires onto `
|
|
42
|
-
`
|
|
41
|
+
The hook is synchronous (`response.read()`), so it wires onto `httpx2.Client`;
|
|
42
|
+
`httpx2.AsyncClient` is not supported today.
|
|
43
43
|
|
|
44
44
|
## Notes
|
|
45
45
|
|
|
@@ -10,7 +10,10 @@ requires-python = ">=3.11"
|
|
|
10
10
|
dynamic = ["version"]
|
|
11
11
|
license = "MIT"
|
|
12
12
|
authors = [{ name = "Fabian Zills" }]
|
|
13
|
-
dependencies = [
|
|
13
|
+
dependencies = [
|
|
14
|
+
"pydantic>=2.13.4",
|
|
15
|
+
"typing-extensions>=4.15.0",
|
|
16
|
+
]
|
|
14
17
|
|
|
15
18
|
[project.urls]
|
|
16
19
|
Repository = "https://github.com/PythonFZ/fastapi-rfc9457"
|
|
@@ -23,12 +26,12 @@ server = ["fastapi>=0.137.2"]
|
|
|
23
26
|
dev = [
|
|
24
27
|
"pytest>=8.0",
|
|
25
28
|
"pytest-asyncio>=0.24",
|
|
26
|
-
"httpx>=0.27",
|
|
27
29
|
"pyright>=1.1.390",
|
|
28
30
|
"ruff>=0.8",
|
|
29
31
|
"pre-commit>=4.0",
|
|
30
32
|
"uvicorn>=0.49.0",
|
|
31
33
|
"fastapi>=0.137.2",
|
|
34
|
+
"httpx2>=2.13.1",
|
|
32
35
|
]
|
|
33
36
|
|
|
34
37
|
[tool.hatch.version]
|
|
@@ -48,10 +51,6 @@ include = ["src/", "tests/", "README.md", "pyproject.toml", "LICENSE"]
|
|
|
48
51
|
asyncio_mode = "auto"
|
|
49
52
|
testpaths = ["tests"]
|
|
50
53
|
pythonpath = ["."]
|
|
51
|
-
filterwarnings = [
|
|
52
|
-
# Starlette's TestClient now prefers httpx2; the httpx warning is expected.
|
|
53
|
-
"ignore::DeprecationWarning",
|
|
54
|
-
]
|
|
55
54
|
|
|
56
55
|
[tool.ruff]
|
|
57
56
|
line-length = 100
|
|
@@ -13,13 +13,15 @@ from .builtins import (
|
|
|
13
13
|
MethodNotAllowed,
|
|
14
14
|
NotAuthenticated,
|
|
15
15
|
NotFound,
|
|
16
|
+
RetryAfter,
|
|
17
|
+
ServiceUnavailable,
|
|
16
18
|
TooManyRequests,
|
|
17
19
|
UnprocessableContent,
|
|
18
20
|
ValidationProblem,
|
|
19
21
|
)
|
|
20
22
|
from .client import httpx_raise_hook, parse_problem, raise_for_problem
|
|
21
23
|
from .models import PROBLEM_MEDIA_TYPE, ProblemDetail
|
|
22
|
-
from .problem import Problem, ProblemError
|
|
24
|
+
from .problem import Problem, ProblemError, UndeclaredHeaderWarning
|
|
23
25
|
|
|
24
26
|
try:
|
|
25
27
|
__version__ = version("fastapi-rfc9457")
|
|
@@ -39,7 +41,10 @@ __all__ = [
|
|
|
39
41
|
"Problem",
|
|
40
42
|
"ProblemDetail",
|
|
41
43
|
"ProblemError",
|
|
44
|
+
"RetryAfter",
|
|
45
|
+
"ServiceUnavailable",
|
|
42
46
|
"TooManyRequests",
|
|
47
|
+
"UndeclaredHeaderWarning",
|
|
43
48
|
"UnprocessableContent",
|
|
44
49
|
"ValidationProblem",
|
|
45
50
|
"__version__",
|
|
@@ -18,7 +18,7 @@ version_tuple: tuple[int | str, ...]
|
|
|
18
18
|
commit_id: str | None
|
|
19
19
|
__commit_id__: str | None
|
|
20
20
|
|
|
21
|
-
__version__ = version = '0.2.
|
|
22
|
-
__version_tuple__ = version_tuple = (0, 2,
|
|
21
|
+
__version__ = version = '0.2.4'
|
|
22
|
+
__version_tuple__ = version_tuple = (0, 2, 4)
|
|
23
23
|
|
|
24
24
|
__commit_id__ = commit_id = None
|
|
@@ -5,7 +5,7 @@ from __future__ import annotations
|
|
|
5
5
|
from collections.abc import Mapping
|
|
6
6
|
from typing import Any, ClassVar
|
|
7
7
|
|
|
8
|
-
from pydantic import BaseModel
|
|
8
|
+
from pydantic import BaseModel, NonNegativeInt
|
|
9
9
|
|
|
10
10
|
from .problem import Problem
|
|
11
11
|
|
|
@@ -82,22 +82,27 @@ class UnprocessableContent(Problem):
|
|
|
82
82
|
status = 422
|
|
83
83
|
|
|
84
84
|
|
|
85
|
-
class
|
|
86
|
-
"""
|
|
85
|
+
class RetryAfter(Problem, abstract=True):
|
|
86
|
+
"""Base for problems that tell the client when to retry (RFC 9110 §10.2.3)."""
|
|
87
87
|
|
|
88
|
-
title = "Too Many Requests"
|
|
89
|
-
status = 429
|
|
90
88
|
headers: ClassVar[Mapping[str, str]] = {
|
|
91
89
|
"Retry-After": "Seconds to wait before retrying (RFC 9110 §10.2.3)."
|
|
92
90
|
}
|
|
93
91
|
#: Seconds the client waits before retrying; sent as ``Retry-After`` when set.
|
|
94
|
-
retry_after:
|
|
92
|
+
retry_after: NonNegativeInt | None = None
|
|
95
93
|
|
|
96
94
|
def response_headers(self) -> Mapping[str, str]:
|
|
97
95
|
"""Send ``retry_after`` as ``Retry-After`` when set."""
|
|
98
96
|
return {} if self.retry_after is None else {"Retry-After": str(self.retry_after)}
|
|
99
97
|
|
|
100
98
|
|
|
99
|
+
class TooManyRequests(RetryAfter):
|
|
100
|
+
"""You have sent too many requests in a given amount of time."""
|
|
101
|
+
|
|
102
|
+
title = "Too Many Requests"
|
|
103
|
+
status = 429
|
|
104
|
+
|
|
105
|
+
|
|
101
106
|
class InternalServerError(Problem):
|
|
102
107
|
"""The server encountered an unexpected condition."""
|
|
103
108
|
|
|
@@ -105,6 +110,13 @@ class InternalServerError(Problem):
|
|
|
105
110
|
status = 500
|
|
106
111
|
|
|
107
112
|
|
|
113
|
+
class ServiceUnavailable(RetryAfter):
|
|
114
|
+
"""The server is temporarily unable to handle the request."""
|
|
115
|
+
|
|
116
|
+
title = "Service Unavailable"
|
|
117
|
+
status = 503
|
|
118
|
+
|
|
119
|
+
|
|
108
120
|
class InvalidParam(BaseModel):
|
|
109
121
|
"""One field-level validation failure (RFC 9457 extension member).
|
|
110
122
|
|
|
@@ -15,7 +15,7 @@ def _coerce(source: Any) -> dict[str, Any]:
|
|
|
15
15
|
return source
|
|
16
16
|
if isinstance(source, (bytes, bytearray, str)):
|
|
17
17
|
return json.loads(source)
|
|
18
|
-
if hasattr(source, "json"): #
|
|
18
|
+
if hasattr(source, "json"): # httpx2.Response / requests.Response
|
|
19
19
|
return source.json()
|
|
20
20
|
raise TypeError(f"Cannot parse a problem from {type(source)!r}")
|
|
21
21
|
|
|
@@ -70,12 +70,12 @@ def raise_for_problem(response: Any) -> None:
|
|
|
70
70
|
|
|
71
71
|
|
|
72
72
|
def httpx_raise_hook():
|
|
73
|
-
"""Return an
|
|
73
|
+
"""Return an httpx2 ``response`` event hook that auto-raises on problem responses.
|
|
74
74
|
|
|
75
75
|
Returns
|
|
76
76
|
-------
|
|
77
77
|
Callable
|
|
78
|
-
Use as ``
|
|
78
|
+
Use as ``httpx2.Client(event_hooks={"response": [httpx_raise_hook()]})``.
|
|
79
79
|
"""
|
|
80
80
|
|
|
81
81
|
def hook(response: Any) -> None:
|
|
@@ -11,7 +11,7 @@ from starlette.responses import Response
|
|
|
11
11
|
|
|
12
12
|
from .builtins import InternalServerError, ValidationProblem
|
|
13
13
|
from .openapi import route_problem_types
|
|
14
|
-
from .problem import Problem, extension_fields
|
|
14
|
+
from .problem import Problem, extension_fields, require_concrete
|
|
15
15
|
from .uris import DOC_ROUTE, doc_route_name, resolve_type_uri, slug_of
|
|
16
16
|
|
|
17
17
|
_HTML = """<!doctype html><meta charset="utf-8">
|
|
@@ -98,6 +98,11 @@ def get_problem_docs_router(*types: type[Problem]) -> APIRouter:
|
|
|
98
98
|
APIRouter
|
|
99
99
|
Mount it yourself with ``app.include_router(..., prefix=..., tags=...)``;
|
|
100
100
|
point your ``type`` URIs at the chosen prefix.
|
|
101
|
+
|
|
102
|
+
Raises
|
|
103
|
+
------
|
|
104
|
+
TypeError
|
|
105
|
+
If an explicitly passed type is abstract.
|
|
101
106
|
"""
|
|
102
107
|
router = APIRouter()
|
|
103
108
|
|
|
@@ -122,6 +127,7 @@ def get_problem_docs_router(*types: type[Problem]) -> APIRouter:
|
|
|
122
127
|
return router
|
|
123
128
|
|
|
124
129
|
for cls in types:
|
|
130
|
+
require_concrete(cls)
|
|
125
131
|
slug = slug_of(cls)
|
|
126
132
|
|
|
127
133
|
def make_endpoint(problem_cls: type[Problem]):
|