fastapi-validation-override 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,5 @@
1
+ from .overrider import override_validation_error
2
+
3
+ __version__ = "0.1.0"
4
+
5
+ __all__ = ["override_validation_error"]
@@ -0,0 +1,86 @@
1
+ from typing import Any
2
+
3
+ from fastapi import FastAPI, Request
4
+ from fastapi.encoders import jsonable_encoder
5
+ from fastapi.exceptions import RequestValidationError
6
+ from fastapi.responses import JSONResponse
7
+
8
+ _HTTP_METHODS = {"get", "put", "post", "delete", "options", "head", "patch", "trace"}
9
+
10
+
11
+ def override_validation_error(app: FastAPI, status_code: int = 400, handle_exceptions: bool = True) -> None:
12
+ """
13
+ Override FastAPI's default 422 validation error response with a custom status code.
14
+
15
+ Cache management is intentionally delegated to the original `app.openapi` so that
16
+ any custom OpenAPI function already set by the developer is fully preserved.
17
+
18
+ :param app: The FastAPI application instance to patch.
19
+ :param status_code: The HTTP status code to use instead of 422. Defaults to 400.
20
+ :param handle_exceptions: If True, registers an exception handler that returns the custom
21
+ status code at runtime. Set to False to patch only the OpenAPI schema and
22
+ handle the exception yourself.
23
+ """
24
+ if status_code == 422:
25
+ return
26
+
27
+ # Guard against duplicate handlers and infinite recursion on repeated calls.
28
+ if getattr(app.state, "_validation_overridden", False):
29
+ return
30
+
31
+ if handle_exceptions:
32
+
33
+ @app.exception_handler(RequestValidationError)
34
+ async def custom_validation_exception_handler(_request: Request, exc: RequestValidationError) -> JSONResponse:
35
+ return JSONResponse(
36
+ status_code=status_code,
37
+ content={"detail": jsonable_encoder(exc.errors())},
38
+ )
39
+
40
+ target_code = str(status_code)
41
+ original_openapi = app.openapi
42
+
43
+ def custom_openapi() -> dict[str, Any]:
44
+ schema = original_openapi()
45
+
46
+ for _path, path_item in schema.get("paths", {}).items():
47
+ for _method, operation in path_item.items():
48
+ if _method not in _HTTP_METHODS:
49
+ # path_item may contain non-operation keys: summary, description, servers, parameters
50
+ continue
51
+
52
+ responses = operation.get("responses", {})
53
+
54
+ if "422" in responses:
55
+ response_422 = responses["422"]
56
+ content_422 = response_422.get("content", {}).get("application/json", {})
57
+ schema_422 = content_422.get("schema", {})
58
+ ref = schema_422.get("$ref", "")
59
+
60
+ if ref.endswith("HTTPValidationError"):
61
+ if target_code in responses:
62
+ existing_response = responses[target_code]
63
+ existing_content = existing_response.setdefault("content", {}).setdefault(
64
+ "application/json", {}
65
+ )
66
+ existing_schema = existing_content.setdefault("schema", {})
67
+
68
+ if "anyOf" in existing_schema:
69
+ existing_schema["anyOf"].append(schema_422)
70
+ elif existing_schema:
71
+ existing_content["schema"] = {"anyOf": [existing_schema, schema_422]}
72
+ else:
73
+ existing_content["schema"] = schema_422
74
+
75
+ old_desc = existing_response.get("description", "Error")
76
+ existing_response["description"] = f"{old_desc} / Validation Error"
77
+
78
+ del responses["422"]
79
+ else:
80
+ responses[target_code] = responses.pop("422")
81
+
82
+ app.openapi_schema = schema
83
+ return app.openapi_schema
84
+
85
+ app.openapi = custom_openapi # type: ignore[method-assign] # ty: ignore[invalid-assignment]
86
+ app.state._validation_overridden = True
File without changes
@@ -0,0 +1,255 @@
1
+ Metadata-Version: 2.4
2
+ Name: fastapi-validation-override
3
+ Version: 0.1.0
4
+ Summary: Override FastAPI's 422 with any HTTP status code — at runtime and in the OpenAPI schema.
5
+ Project-URL: Homepage, https://github.com/mat81black/fastapi-validation-override
6
+ Project-URL: Repository, https://github.com/mat81black/fastapi-validation-override
7
+ Project-URL: Issues, https://github.com/mat81black/fastapi-validation-override/issues
8
+ Author-email: Matteo Nieddu <mat81black@gmail.com>
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Classifier: Development Status :: 5 - Production/Stable
12
+ Classifier: Environment :: Web Environment
13
+ Classifier: Framework :: FastAPI
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: License :: OSI Approved :: MIT License
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Programming Language :: Python :: 3 :: Only
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Programming Language :: Python :: 3.13
22
+ Classifier: Programming Language :: Python :: 3.14
23
+ Classifier: Topic :: Internet :: WWW/HTTP
24
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
25
+ Classifier: Typing :: Typed
26
+ Requires-Python: >=3.10
27
+ Requires-Dist: fastapi>=0.120.0
28
+ Description-Content-Type: text/markdown
29
+
30
+ # FastAPI Validation Override
31
+
32
+ [![PyPI](https://img.shields.io/pypi/v/fastapi-validation-override)](https://pypi.org/project/fastapi-validation-override/)
33
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
34
+ [![Python](https://img.shields.io/pypi/pyversions/fastapi-validation-override)](https://pypi.org/project/fastapi-validation-override/)
35
+
36
+ Override FastAPI's default **422 Unprocessable Entity** validation error with any HTTP status code — both at runtime and in the OpenAPI schema.
37
+
38
+ Call `override_validation_error(app)` once after defining your routes. Validation errors will return the chosen status code with the standard `{"detail": [...]}` body.
39
+
40
+ ---
41
+
42
+ ## Features
43
+
44
+ - **Runtime + schema** — patches both the exception handler and the OpenAPI schema in one call
45
+ - **Any status code** — use 400, 409, or any other code instead of 422
46
+ - **Schema-aware merge** — if a route already declares a response at the target code, the validation error schema is merged using `anyOf`
47
+ - **Custom OpenAPI preserved** — any `app.openapi` function already defined is called first; the patch is applied on top
48
+ - **Custom exception handler** — set `handle_exceptions=False` to patch only the schema and handle the exception independently
49
+ - **Idempotent calls** — safe to invoke multiple times on the same app instance
50
+
51
+ ---
52
+
53
+ ## Requirements
54
+
55
+ - Python ≥ 3.10
56
+ - FastAPI ≥ 0.120.0
57
+
58
+ ---
59
+
60
+ ## Installation
61
+
62
+ ```bash
63
+ pip install fastapi-validation-override
64
+ # or
65
+ uv add fastapi-validation-override
66
+ ```
67
+
68
+ ---
69
+
70
+ ## Quick start
71
+
72
+ ```python
73
+ from fastapi import FastAPI
74
+ from pydantic import BaseModel
75
+
76
+ from fastapi_validation_override import override_validation_error
77
+
78
+ app = FastAPI()
79
+
80
+
81
+ class Item(BaseModel):
82
+ name: str
83
+ price: float
84
+
85
+
86
+ @app.post("/items")
87
+ async def create_item(item: Item) -> dict[str, object]:
88
+ return item.model_dump()
89
+
90
+
91
+ override_validation_error(app)
92
+ # POST /items with missing fields -> 400 Bad Request {"detail": [...]}
93
+ ```
94
+
95
+ The `422` entry in the Swagger UI is replaced by `400` automatically.
96
+
97
+ ---
98
+
99
+ ## `override_validation_error` reference
100
+
101
+ ```python
102
+ override_validation_error(app, status_code=400, handle_exceptions=True)
103
+ ```
104
+
105
+ | Parameter | Type | Default | Description |
106
+ |---|---|---|---|
107
+ | `app` | `FastAPI` | required | The FastAPI application instance to patch |
108
+ | `status_code` | `int` | `400` | HTTP status code to use instead of 422 |
109
+ | `handle_exceptions` | `bool` | `True` | If `True`, registers an exception handler that returns the custom status code at runtime. Set to `False` to patch only the OpenAPI schema and handle the exception independently |
110
+
111
+ Calling with `status_code=422` is a no-op — the default FastAPI behaviour is preserved unchanged.
112
+
113
+ ---
114
+
115
+ ## Advanced options
116
+
117
+ ### Custom status code
118
+
119
+ ```python
120
+ override_validation_error(app, status_code=409)
121
+ # Validation errors -> 409 Conflict
122
+ ```
123
+
124
+ ### Custom exception handler
125
+
126
+ Set `handle_exceptions=False` to define a custom response body or add logic on validation errors. The OpenAPI schema is still patched to reflect the correct status code.
127
+
128
+ ```python
129
+ from fastapi import FastAPI, Request
130
+ from fastapi.exceptions import RequestValidationError
131
+ from fastapi.responses import JSONResponse
132
+
133
+ from fastapi_validation_override import override_validation_error
134
+
135
+ app = FastAPI()
136
+
137
+
138
+ @app.exception_handler(RequestValidationError)
139
+ async def custom_handler(request: Request, exc: RequestValidationError) -> JSONResponse:
140
+ return JSONResponse(
141
+ status_code=400,
142
+ content={
143
+ "message": "Validation failed",
144
+ "errors": exc.errors(),
145
+ },
146
+ )
147
+
148
+
149
+ override_validation_error(app, status_code=400, handle_exceptions=False)
150
+ ```
151
+
152
+ ### Preserving a custom `app.openapi`
153
+
154
+ If `app.openapi` has been replaced with a custom function, `override_validation_error` wraps it — the custom function is called first and the patch is applied to its output.
155
+
156
+ ```python
157
+ from typing import Any
158
+
159
+ from fastapi import FastAPI
160
+ from fastapi.openapi.utils import get_openapi
161
+
162
+ from fastapi_validation_override import override_validation_error
163
+
164
+ app = FastAPI()
165
+
166
+
167
+ def custom_openapi() -> dict[str, Any]:
168
+ if app.openapi_schema:
169
+ return app.openapi_schema
170
+ schema = get_openapi(title="My API", version="1.0.0", routes=app.routes)
171
+ schema["info"]["x-logo"] = {"url": "https://example.com/logo.png"}
172
+ app.openapi_schema = schema
173
+ return schema
174
+
175
+
176
+ app.openapi = custom_openapi # type: ignore[method-assign] # ty: ignore[invalid-assignment]
177
+
178
+ override_validation_error(app)
179
+ # x-logo is preserved; 422 is replaced by 400 in the schema
180
+ ```
181
+
182
+ ### Existing response at target code
183
+
184
+ When a route already declares a response at the target status code, the validation error schema is merged into it using `anyOf` — neither schema is lost.
185
+
186
+ ```python
187
+ from fastapi import FastAPI
188
+ from pydantic import BaseModel
189
+
190
+ from fastapi_validation_override import override_validation_error
191
+
192
+ app = FastAPI()
193
+
194
+
195
+ class OutOfStockError(BaseModel):
196
+ message: str
197
+ item_name: str
198
+
199
+
200
+ class Item(BaseModel):
201
+ name: str
202
+ price: float
203
+
204
+
205
+ @app.post("/items", responses={400: {"model": OutOfStockError, "description": "Out of stock"}})
206
+ async def create_item(item: Item) -> dict[str, object]:
207
+ return item.model_dump()
208
+
209
+
210
+ override_validation_error(app)
211
+ # responses.400.content.application/json.schema -> anyOf: [OutOfStockError, HTTPValidationError]
212
+ ```
213
+
214
+ ### Usage with `APIRouter`
215
+
216
+ `override_validation_error` applies to the whole application, regardless of how routes are organized.
217
+
218
+ ```python
219
+ from fastapi import APIRouter, FastAPI
220
+ from pydantic import BaseModel
221
+
222
+ from fastapi_validation_override import override_validation_error
223
+
224
+ app = FastAPI()
225
+ items_router = APIRouter(prefix="/items", tags=["items"])
226
+ users_router = APIRouter(prefix="/users", tags=["users"])
227
+
228
+ # ... define routes on each router ...
229
+
230
+ app.include_router(items_router)
231
+ app.include_router(users_router)
232
+
233
+ override_validation_error(app)
234
+ ```
235
+
236
+ ---
237
+
238
+ ## Examples
239
+
240
+ Runnable examples are available in the [`examples/`](examples/) directory:
241
+
242
+ | File | What it shows |
243
+ |---|---|
244
+ | [`basic.py`](examples/basic.py) | Minimal setup with the default 400 status code |
245
+ | [`custom_status_code.py`](examples/custom_status_code.py) | Using a custom status code (409) |
246
+ | [`handle_exceptions_false.py`](examples/handle_exceptions_false.py) | Custom exception handler with schema-only patch |
247
+ | [`custom_openapi.py`](examples/custom_openapi.py) | Preserving a custom `app.openapi` function |
248
+ | [`existing_response_at_target_code.py`](examples/existing_response_at_target_code.py) | `anyOf` merge when the target code is already declared |
249
+ | [`with_apirouter.py`](examples/with_apirouter.py) | Usage with multiple `APIRouter` instances |
250
+
251
+ ---
252
+
253
+ ## License
254
+
255
+ [MIT](LICENSE)
@@ -0,0 +1,7 @@
1
+ fastapi_validation_override/__init__.py,sha256=cmNlW-kkcg-bDlnYhJ5X_zgpEJwDlgFFbKL4kuXsJNg,113
2
+ fastapi_validation_override/overrider.py,sha256=HCeCQAFoHslulHNQrDiOVeoZDaYvNTHgFQr8DpHfKPc,3817
3
+ fastapi_validation_override/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
+ fastapi_validation_override-0.1.0.dist-info/METADATA,sha256=z9M8IICCfdxCV7fjrHWIbeW_d6oCh_jRTriitqNgD24,8082
5
+ fastapi_validation_override-0.1.0.dist-info/WHEEL,sha256=mffPy8wBnZQn2VnJUU5jE99KsxaSfiyMHV9Yt0aLVxs,87
6
+ fastapi_validation_override-0.1.0.dist-info/licenses/LICENSE,sha256=Tsif_IFIW5f-xYSy1KlhAy7v_oNEU4lP2cEnSQbMdE4,1086
7
+ fastapi_validation_override-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.30.1
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2018 Sebastián Ramírez
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
13
+ all 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
21
+ THE SOFTWARE.