fastapi-rfc9457 0.2.2__tar.gz → 0.2.3__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.3}/PKG-INFO +52 -34
- {fastapi_rfc9457-0.2.2 → fastapi_rfc9457-0.2.3}/README.md +50 -33
- {fastapi_rfc9457-0.2.2 → fastapi_rfc9457-0.2.3}/example/README.md +5 -5
- {fastapi_rfc9457-0.2.2 → fastapi_rfc9457-0.2.3}/pyproject.toml +5 -6
- {fastapi_rfc9457-0.2.2 → fastapi_rfc9457-0.2.3}/src/fastapi_rfc9457/__init__.py +6 -1
- {fastapi_rfc9457-0.2.2 → fastapi_rfc9457-0.2.3}/src/fastapi_rfc9457/_version.py +2 -2
- {fastapi_rfc9457-0.2.2 → fastapi_rfc9457-0.2.3}/src/fastapi_rfc9457/builtins.py +18 -6
- {fastapi_rfc9457-0.2.2 → fastapi_rfc9457-0.2.3}/src/fastapi_rfc9457/client.py +3 -3
- {fastapi_rfc9457-0.2.2 → fastapi_rfc9457-0.2.3}/src/fastapi_rfc9457/docs.py +7 -1
- {fastapi_rfc9457-0.2.2 → fastapi_rfc9457-0.2.3}/src/fastapi_rfc9457/handlers.py +17 -2
- {fastapi_rfc9457-0.2.2 → fastapi_rfc9457-0.2.3}/src/fastapi_rfc9457/integration.py +4 -12
- {fastapi_rfc9457-0.2.2 → fastapi_rfc9457-0.2.3}/src/fastapi_rfc9457/openapi.py +20 -2
- {fastapi_rfc9457-0.2.2 → fastapi_rfc9457-0.2.3}/src/fastapi_rfc9457/problem.py +111 -10
- {fastapi_rfc9457-0.2.2 → fastapi_rfc9457-0.2.3}/tests/static/valid_usage.py +35 -1
- fastapi_rfc9457-0.2.3/tests/test_abstract.py +81 -0
- fastapi_rfc9457-0.2.3/tests/test_lifespan.py +46 -0
- {fastapi_rfc9457-0.2.2 → fastapi_rfc9457-0.2.3}/tests/test_public_api.py +3 -0
- fastapi_rfc9457-0.2.3/tests/test_response_headers.py +325 -0
- 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.3}/.gitignore +0 -0
- {fastapi_rfc9457-0.2.2 → fastapi_rfc9457-0.2.3}/LICENSE +0 -0
- {fastapi_rfc9457-0.2.2 → fastapi_rfc9457-0.2.3}/src/fastapi_rfc9457/models.py +0 -0
- {fastapi_rfc9457-0.2.2 → fastapi_rfc9457-0.2.3}/src/fastapi_rfc9457/py.typed +0 -0
- {fastapi_rfc9457-0.2.2 → fastapi_rfc9457-0.2.3}/src/fastapi_rfc9457/server.py +0 -0
- {fastapi_rfc9457-0.2.2 → fastapi_rfc9457-0.2.3}/src/fastapi_rfc9457/uris.py +0 -0
- {fastapi_rfc9457-0.2.2 → fastapi_rfc9457-0.2.3}/tests/conftest.py +0 -0
- {fastapi_rfc9457-0.2.2 → fastapi_rfc9457-0.2.3}/tests/static/expected_errors.py +0 -0
- {fastapi_rfc9457-0.2.2 → fastapi_rfc9457-0.2.3}/tests/test_builtins.py +0 -0
- {fastapi_rfc9457-0.2.2 → fastapi_rfc9457-0.2.3}/tests/test_client.py +0 -0
- {fastapi_rfc9457-0.2.2 → fastapi_rfc9457-0.2.3}/tests/test_client_install.py +0 -0
- {fastapi_rfc9457-0.2.2 → fastapi_rfc9457-0.2.3}/tests/test_docs.py +0 -0
- {fastapi_rfc9457-0.2.2 → fastapi_rfc9457-0.2.3}/tests/test_example.py +0 -0
- {fastapi_rfc9457-0.2.2 → fastapi_rfc9457-0.2.3}/tests/test_example_client.py +0 -0
- {fastapi_rfc9457-0.2.2 → fastapi_rfc9457-0.2.3}/tests/test_extension_fields_pep563.py +0 -0
- {fastapi_rfc9457-0.2.2 → fastapi_rfc9457-0.2.3}/tests/test_handlers.py +0 -0
- {fastapi_rfc9457-0.2.2 → fastapi_rfc9457-0.2.3}/tests/test_integration.py +0 -0
- {fastapi_rfc9457-0.2.2 → fastapi_rfc9457-0.2.3}/tests/test_models.py +0 -0
- {fastapi_rfc9457-0.2.2 → fastapi_rfc9457-0.2.3}/tests/test_openapi.py +0 -0
- {fastapi_rfc9457-0.2.2 → fastapi_rfc9457-0.2.3}/tests/test_problem.py +0 -0
- {fastapi_rfc9457-0.2.2 → fastapi_rfc9457-0.2.3}/tests/test_static_typing.py +0 -0
- {fastapi_rfc9457-0.2.2 → fastapi_rfc9457-0.2.3}/tests/test_type_uri_resolution.py +0 -0
- {fastapi_rfc9457-0.2.2 → fastapi_rfc9457-0.2.3}/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.3
|
|
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
|
|
@@ -56,47 +55,67 @@ async def charge() -> dict:
|
|
|
56
55
|
|
|
57
56
|
## Accurate OpenAPI, for free
|
|
58
57
|
|
|
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`.
|
|
58
|
+
One route can declare several failure modes.
|
|
59
|
+
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
60
|
|
|
63
61
|

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

|
|
78
72
|
|
|
79
73
|
## Response headers
|
|
80
74
|
|
|
81
|
-
A problem type declares the headers it sends in `headers` (name → OpenAPI description) and
|
|
82
|
-
|
|
75
|
+
A problem type declares the headers it sends in `headers` (name → OpenAPI description) and returns their values from `response_headers()`.
|
|
76
|
+
The built-ins send the headers RFC 9110 asks for:
|
|
83
77
|
|
|
84
78
|
```python
|
|
85
|
-
raise NotAuthenticated()
|
|
86
|
-
raise TooManyRequests(retry_after=30)
|
|
87
|
-
raise
|
|
79
|
+
raise NotAuthenticated() # WWW-Authenticate: Bearer
|
|
80
|
+
raise TooManyRequests(retry_after=30) # Retry-After: 30
|
|
81
|
+
raise ServiceUnavailable(retry_after=120) # Retry-After: 120
|
|
82
|
+
raise MethodNotAllowed(allow=["GET"]) # Allow: GET
|
|
88
83
|
|
|
89
84
|
class BasicAuthRequired(NotAuthenticated):
|
|
90
|
-
challenge = 'Basic realm="api"'
|
|
85
|
+
challenge = 'Basic realm="api"' # WWW-Authenticate: Basic realm="api"
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
A custom problem type declares its own headers:
|
|
89
|
+
|
|
90
|
+
```python
|
|
91
|
+
class Moved(Problem):
|
|
92
|
+
title, status = "Moved", 410
|
|
93
|
+
location: str
|
|
94
|
+
headers: ClassVar[Mapping[str, str]] = {"Location": "The new URL of the resource."}
|
|
95
|
+
|
|
96
|
+
def response_headers(self) -> Mapping[str, str]:
|
|
97
|
+
return {"Location": self.location}
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
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`.
|
|
101
|
+
|
|
102
|
+
## Shared bases
|
|
103
|
+
|
|
104
|
+
A class missing `title` or `status` raises `TypeError` when defined; mark shared bases `abstract=True`:
|
|
105
|
+
|
|
106
|
+
```python
|
|
107
|
+
class Audited(Problem, abstract=True):
|
|
108
|
+
audit_id: str # every subclass carries it
|
|
109
|
+
class Throttled(RetryAfter): # built-in abstract base: retry_after + Retry-After
|
|
110
|
+
title, status = "Throttled", 429
|
|
91
111
|
```
|
|
92
112
|
|
|
93
113
|
## Typed exceptions on the client
|
|
94
114
|
|
|
95
|
-
Client-side, the package can parse
|
|
96
|
-
`application/problem+json` back into typed problems the server raised.
|
|
115
|
+
Client-side, the package can parse `application/problem+json` back into typed problems the server raised.
|
|
97
116
|
|
|
98
117
|
```python
|
|
99
|
-
import
|
|
118
|
+
import httpx2
|
|
100
119
|
from fastapi_rfc9457 import Problem, httpx_raise_hook
|
|
101
120
|
|
|
102
121
|
|
|
@@ -105,7 +124,7 @@ class OutOfCredit(Problem): # the type the server declares, shared or re-st
|
|
|
105
124
|
status = 403
|
|
106
125
|
balance: int
|
|
107
126
|
|
|
108
|
-
with
|
|
127
|
+
with httpx2.Client(
|
|
109
128
|
base_url="http://localhost:8000",
|
|
110
129
|
event_hooks={
|
|
111
130
|
"response": [httpx_raise_hook()]
|
|
@@ -116,12 +135,11 @@ with httpx.Client(
|
|
|
116
135
|
print(exc.balance) # extension members round-trip back as typed attributes
|
|
117
136
|
```
|
|
118
137
|
|
|
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.
|
|
138
|
+
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
139
|
|
|
123
140
|
## Comparison with native FastAPI
|
|
124
|
-
|
|
141
|
+
|
|
142
|
+
The same endpoint written the way FastAPI's [Handling Errors](https://fastapi.tiangolo.com/tutorial/handling-errors/) tutorial shows:
|
|
125
143
|
|
|
126
144
|
```python
|
|
127
145
|
class OutOfCreditError(Exception):
|
|
@@ -187,10 +205,10 @@ uv add fastapi-rfc9457 # lean client: author + parse problems, Pydanti
|
|
|
187
205
|
cd example && uv run uvicorn main:app --reload # then open localhost:8000/docs
|
|
188
206
|
```
|
|
189
207
|
|
|
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.
|
|
208
|
+
See [`example/`](./example) for the full app and [`example/client.py`](./example/client.py) for a client using it.
|
|
193
209
|
|
|
194
210
|
## Notes
|
|
195
211
|
|
|
196
|
-
-
|
|
212
|
+
- Every error answers with `application/problem+json`: raised problems, `HTTPException`, request validation (422), and unhandled exceptions (500).
|
|
213
|
+
- 500 bodies include the exception message by default.
|
|
214
|
+
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
|
|
@@ -41,47 +39,67 @@ async def charge() -> dict:
|
|
|
41
39
|
|
|
42
40
|
## Accurate OpenAPI, for free
|
|
43
41
|
|
|
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`.
|
|
42
|
+
One route can declare several failure modes.
|
|
43
|
+
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
44
|
|
|
48
45
|

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

|
|
63
56
|
|
|
64
57
|
## Response headers
|
|
65
58
|
|
|
66
|
-
A problem type declares the headers it sends in `headers` (name → OpenAPI description) and
|
|
67
|
-
|
|
59
|
+
A problem type declares the headers it sends in `headers` (name → OpenAPI description) and returns their values from `response_headers()`.
|
|
60
|
+
The built-ins send the headers RFC 9110 asks for:
|
|
68
61
|
|
|
69
62
|
```python
|
|
70
|
-
raise NotAuthenticated()
|
|
71
|
-
raise TooManyRequests(retry_after=30)
|
|
72
|
-
raise
|
|
63
|
+
raise NotAuthenticated() # WWW-Authenticate: Bearer
|
|
64
|
+
raise TooManyRequests(retry_after=30) # Retry-After: 30
|
|
65
|
+
raise ServiceUnavailable(retry_after=120) # Retry-After: 120
|
|
66
|
+
raise MethodNotAllowed(allow=["GET"]) # Allow: GET
|
|
73
67
|
|
|
74
68
|
class BasicAuthRequired(NotAuthenticated):
|
|
75
|
-
challenge = 'Basic realm="api"'
|
|
69
|
+
challenge = 'Basic realm="api"' # WWW-Authenticate: Basic realm="api"
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
A custom problem type declares its own headers:
|
|
73
|
+
|
|
74
|
+
```python
|
|
75
|
+
class Moved(Problem):
|
|
76
|
+
title, status = "Moved", 410
|
|
77
|
+
location: str
|
|
78
|
+
headers: ClassVar[Mapping[str, str]] = {"Location": "The new URL of the resource."}
|
|
79
|
+
|
|
80
|
+
def response_headers(self) -> Mapping[str, str]:
|
|
81
|
+
return {"Location": self.location}
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
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`.
|
|
85
|
+
|
|
86
|
+
## Shared bases
|
|
87
|
+
|
|
88
|
+
A class missing `title` or `status` raises `TypeError` when defined; mark shared bases `abstract=True`:
|
|
89
|
+
|
|
90
|
+
```python
|
|
91
|
+
class Audited(Problem, abstract=True):
|
|
92
|
+
audit_id: str # every subclass carries it
|
|
93
|
+
class Throttled(RetryAfter): # built-in abstract base: retry_after + Retry-After
|
|
94
|
+
title, status = "Throttled", 429
|
|
76
95
|
```
|
|
77
96
|
|
|
78
97
|
## Typed exceptions on the client
|
|
79
98
|
|
|
80
|
-
Client-side, the package can parse
|
|
81
|
-
`application/problem+json` back into typed problems the server raised.
|
|
99
|
+
Client-side, the package can parse `application/problem+json` back into typed problems the server raised.
|
|
82
100
|
|
|
83
101
|
```python
|
|
84
|
-
import
|
|
102
|
+
import httpx2
|
|
85
103
|
from fastapi_rfc9457 import Problem, httpx_raise_hook
|
|
86
104
|
|
|
87
105
|
|
|
@@ -90,7 +108,7 @@ class OutOfCredit(Problem): # the type the server declares, shared or re-st
|
|
|
90
108
|
status = 403
|
|
91
109
|
balance: int
|
|
92
110
|
|
|
93
|
-
with
|
|
111
|
+
with httpx2.Client(
|
|
94
112
|
base_url="http://localhost:8000",
|
|
95
113
|
event_hooks={
|
|
96
114
|
"response": [httpx_raise_hook()]
|
|
@@ -101,12 +119,11 @@ with httpx.Client(
|
|
|
101
119
|
print(exc.balance) # extension members round-trip back as typed attributes
|
|
102
120
|
```
|
|
103
121
|
|
|
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.
|
|
122
|
+
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
123
|
|
|
108
124
|
## Comparison with native FastAPI
|
|
109
|
-
|
|
125
|
+
|
|
126
|
+
The same endpoint written the way FastAPI's [Handling Errors](https://fastapi.tiangolo.com/tutorial/handling-errors/) tutorial shows:
|
|
110
127
|
|
|
111
128
|
```python
|
|
112
129
|
class OutOfCreditError(Exception):
|
|
@@ -172,10 +189,10 @@ uv add fastapi-rfc9457 # lean client: author + parse problems, Pydanti
|
|
|
172
189
|
cd example && uv run uvicorn main:app --reload # then open localhost:8000/docs
|
|
173
190
|
```
|
|
174
191
|
|
|
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.
|
|
192
|
+
See [`example/`](./example) for the full app and [`example/client.py`](./example/client.py) for a client using it.
|
|
178
193
|
|
|
179
194
|
## Notes
|
|
180
195
|
|
|
181
|
-
-
|
|
196
|
+
- Every error answers with `application/problem+json`: raised problems, `HTTPException`, request validation (422), and unhandled exceptions (500).
|
|
197
|
+
- 500 bodies include the exception message by default.
|
|
198
|
+
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.3'
|
|
22
|
+
__version_tuple__ = version_tuple = (0, 2, 3)
|
|
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]):
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
|
+
import warnings
|
|
5
6
|
from collections.abc import Awaitable, Callable, Mapping
|
|
6
7
|
from http import HTTPStatus
|
|
7
8
|
from typing import cast
|
|
@@ -14,7 +15,7 @@ from starlette.responses import Response
|
|
|
14
15
|
|
|
15
16
|
from .builtins import InternalServerError, InvalidParam, ValidationProblem
|
|
16
17
|
from .models import PROBLEM_MEDIA_TYPE, ProblemDetail
|
|
17
|
-
from .problem import Problem, extension_fields
|
|
18
|
+
from .problem import Problem, UndeclaredHeaderWarning, extension_fields, sent_headers
|
|
18
19
|
from .uris import resolve_type_uri
|
|
19
20
|
|
|
20
21
|
Handler = Callable[[Request, Exception], Awaitable[Response]]
|
|
@@ -58,6 +59,18 @@ def _respond(detail: ProblemDetail, headers: Mapping[str, str] | None = None) ->
|
|
|
58
59
|
)
|
|
59
60
|
|
|
60
61
|
|
|
62
|
+
def _warn_undeclared_headers(cls: type[Problem], headers: Mapping[str, str]) -> None:
|
|
63
|
+
declared = {name.lower() for name in cls.headers}
|
|
64
|
+
for name in headers:
|
|
65
|
+
if name.lower() not in declared:
|
|
66
|
+
warnings.warn(
|
|
67
|
+
f"{cls.__name__} sends {name!r}, which is missing from "
|
|
68
|
+
f"{cls.__name__}.headers; declare it there to document it in OpenAPI.",
|
|
69
|
+
UndeclaredHeaderWarning,
|
|
70
|
+
stacklevel=2,
|
|
71
|
+
)
|
|
72
|
+
|
|
73
|
+
|
|
61
74
|
def make_handlers(*, strip_debug: bool, instance_from_request: bool) -> dict[type, Handler]:
|
|
62
75
|
"""Build the exception-type -> handler mapping for ``add_exception_handler``.
|
|
63
76
|
|
|
@@ -80,7 +93,9 @@ def make_handlers(*, strip_debug: bool, instance_from_request: bool) -> dict[typ
|
|
|
80
93
|
async def problem_handler(request: Request, exc: Problem) -> Response:
|
|
81
94
|
type_uri = resolve_type_uri(request.app, type(exc))
|
|
82
95
|
wire = build_wire(exc, instance=_instance(request), type_uri=type_uri)
|
|
83
|
-
|
|
96
|
+
headers = sent_headers(exc)
|
|
97
|
+
_warn_undeclared_headers(type(exc), headers)
|
|
98
|
+
return _respond(wire, headers)
|
|
84
99
|
|
|
85
100
|
async def validation_handler(request: Request, exc: RequestValidationError) -> Response:
|
|
86
101
|
params: list[InvalidParam] = []
|
|
@@ -7,10 +7,10 @@ from collections.abc import AsyncIterator
|
|
|
7
7
|
from contextlib import asynccontextmanager
|
|
8
8
|
|
|
9
9
|
from fastapi import FastAPI
|
|
10
|
+
from typing_extensions import deprecated
|
|
10
11
|
|
|
11
12
|
from .handlers import make_handlers
|
|
12
13
|
from .openapi import register_problem_components
|
|
13
|
-
from .problem import iter_problem_types
|
|
14
14
|
|
|
15
15
|
_INSTALLED_FLAG = "_fastapi_rfc9457_installed"
|
|
16
16
|
|
|
@@ -51,26 +51,18 @@ def add_problem_handlers(
|
|
|
51
51
|
setattr(app.state, _INSTALLED_FLAG, True)
|
|
52
52
|
|
|
53
53
|
|
|
54
|
+
@deprecated("Problem types are validated when defined; drop problem_details_lifespan.")
|
|
54
55
|
@asynccontextmanager
|
|
55
56
|
async def problem_details_lifespan(app: FastAPI) -> AsyncIterator[None]:
|
|
56
|
-
"""
|
|
57
|
-
|
|
58
|
-
Nest this inside your own lifespan (user lifespan outer, ours inner). It
|
|
59
|
-
fails fast if any defined problem type is missing ``title`` or ``status``.
|
|
60
|
-
Duplicate type URIs are rejected later, when the OpenAPI schema is built.
|
|
57
|
+
"""Deprecated no-op lifespan; problem types are validated when defined.
|
|
61
58
|
|
|
62
59
|
Parameters
|
|
63
60
|
----------
|
|
64
61
|
app : FastAPI
|
|
65
|
-
The application
|
|
62
|
+
The application.
|
|
66
63
|
|
|
67
64
|
Yields
|
|
68
65
|
------
|
|
69
66
|
None
|
|
70
67
|
"""
|
|
71
|
-
for cls in iter_problem_types():
|
|
72
|
-
if not getattr(cls, "title", None):
|
|
73
|
-
raise RuntimeError(f"Problem type {cls.__name__} ({cls.type!r}) is missing a title")
|
|
74
|
-
if not getattr(cls, "status", None):
|
|
75
|
-
raise RuntimeError(f"Problem type {cls.__name__} ({cls.type!r}) is missing a status")
|
|
76
68
|
yield
|
|
@@ -25,7 +25,7 @@ from pydantic import BaseModel, ConfigDict, create_model
|
|
|
25
25
|
|
|
26
26
|
from .builtins import ValidationProblem
|
|
27
27
|
from .models import PROBLEM_MEDIA_TYPE, ProblemDetail
|
|
28
|
-
from .problem import Problem, extension_fields
|
|
28
|
+
from .problem import Problem, example_headers, extension_fields, require_concrete
|
|
29
29
|
from .uris import resolve_type_uri
|
|
30
30
|
|
|
31
31
|
_REF_TEMPLATE = "#/components/schemas/{model}"
|
|
@@ -110,9 +110,17 @@ def problems(*types_: type[Problem]) -> dict[int | str, dict[str, Any]]:
|
|
|
110
110
|
-------
|
|
111
111
|
dict[int | str, dict[str, Any]]
|
|
112
112
|
A ``responses=`` mapping keyed by status code.
|
|
113
|
+
|
|
114
|
+
Raises
|
|
115
|
+
------
|
|
116
|
+
TypeError
|
|
117
|
+
If a type is abstract.
|
|
118
|
+
ValueError
|
|
119
|
+
If a type's ``header_examples()`` names a header missing from its ``headers``.
|
|
113
120
|
"""
|
|
114
121
|
grouped: dict[int, list[type[Problem]]] = {}
|
|
115
122
|
for problem_type in types_:
|
|
123
|
+
require_concrete(problem_type)
|
|
116
124
|
grouped.setdefault(problem_type.status, []).append(problem_type)
|
|
117
125
|
|
|
118
126
|
responses: dict[int | str, dict[str, Any]] = {}
|
|
@@ -140,13 +148,23 @@ def _header_objects(group: list[type[Problem]]) -> dict[str, dict[str, Any]]:
|
|
|
140
148
|
dict[str, dict[str, Any]]
|
|
141
149
|
Header name -> Header Object. One example value is set as ``example``;
|
|
142
150
|
several distinct values are listed under ``examples``, keyed by class name.
|
|
151
|
+
|
|
152
|
+
Raises
|
|
153
|
+
------
|
|
154
|
+
ValueError
|
|
155
|
+
If a type's ``header_examples()`` names a header missing from its ``headers``.
|
|
143
156
|
"""
|
|
144
157
|
objects: dict[str, dict[str, Any]] = {}
|
|
145
158
|
examples: dict[str, dict[str, str]] = {}
|
|
146
159
|
for problem_type in group:
|
|
147
160
|
for name, description in problem_type.headers.items():
|
|
148
161
|
objects.setdefault(name, {"description": description, "schema": {"type": "string"}})
|
|
149
|
-
for name, value in problem_type
|
|
162
|
+
for name, value in example_headers(problem_type).items():
|
|
163
|
+
if name not in problem_type.headers:
|
|
164
|
+
raise ValueError(
|
|
165
|
+
f"{problem_type.__name__} gives an example for {name!r}, which is "
|
|
166
|
+
f"missing from {problem_type.__name__}.headers."
|
|
167
|
+
)
|
|
150
168
|
examples.setdefault(name, {})[problem_type.__name__] = value
|
|
151
169
|
for name, by_class in examples.items():
|
|
152
170
|
if len(set(by_class.values())) == 1:
|