fastapi-errors-plus 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,8 @@
1
+ """Universal library for documenting errors in FastAPI endpoints."""
2
+
3
+ from fastapi_errors_plus.errors import Errors
4
+ from fastapi_errors_plus.protocol import ErrorDTO
5
+
6
+ __all__ = ["Errors", "ErrorDTO"]
7
+ __version__ = "0.1.0"
8
+
@@ -0,0 +1,404 @@
1
+ """Main Errors class for documenting errors in FastAPI endpoints."""
2
+
3
+ from collections.abc import Mapping
4
+ from typing import Any, Dict, Iterator, Union
5
+
6
+ from fastapi import status
7
+
8
+ from fastapi_errors_plus.protocol import ErrorDTO
9
+
10
+
11
+ class Errors(Mapping):
12
+ """Universal class for documenting errors in FastAPI endpoints.
13
+
14
+ Works with any FastAPI project. Can accept:
15
+ - Standard HTTP statuses via boolean flags
16
+ - Dict in FastAPI responses format
17
+ - Objects implementing ErrorDTO protocol (for project compatibility)
18
+
19
+ Implements Mapping protocol, so can be used directly in FastAPI responses
20
+ parameter without calling ().
21
+
22
+ Example:
23
+ ```python
24
+ from fastapi import APIRouter
25
+ from fastapi_errors_plus import Errors
26
+
27
+ router = APIRouter()
28
+
29
+ @router.delete(
30
+ "/{id}",
31
+ responses=Errors(
32
+ unauthorized=True, # 401
33
+ forbidden=True, # 403
34
+ validation_error=True, # 422
35
+ {404: { # 404 via dict
36
+ "description": "Not found",
37
+ "content": {
38
+ "application/json": {
39
+ "example": {"detail": "Item not found"},
40
+ },
41
+ },
42
+ }},
43
+ ),
44
+ )
45
+ def delete_item(id: int):
46
+ pass
47
+ ```
48
+ """
49
+
50
+ def __init__(
51
+ self,
52
+ # Arbitrary errors (dict or ErrorDTO) - must come first
53
+ *errors: Union[Dict[int, Dict[str, Any]], ErrorDTO],
54
+ # Standard HTTP statuses (boolean flags)
55
+ unauthorized: bool = False, # 401
56
+ forbidden: bool = False, # 403
57
+ validation_error: bool = False, # 422
58
+ internal_server_error: bool = False, # 500
59
+ ) -> None:
60
+ """Initialize Errors instance.
61
+
62
+ Args:
63
+ *errors: Arbitrary errors as dict or ErrorDTO objects.
64
+ Dict should be in FastAPI responses format: {status_code: {...}}.
65
+ ErrorDTO objects must implement the ErrorDTO protocol.
66
+ unauthorized: Add 401 Unauthorized error. Defaults to False.
67
+ forbidden: Add 403 Forbidden error. Defaults to False.
68
+ validation_error: Add 422 Unprocessable Entity error. Defaults to False.
69
+ internal_server_error: Add 500 Internal Server Error. Defaults to False.
70
+
71
+ Example:
72
+ ```python
73
+ # Standard flags only
74
+ errors = Errors(unauthorized=True, forbidden=True)
75
+
76
+ # Dict errors
77
+ errors = Errors({404: {"description": "Not found", ...}})
78
+
79
+ # ErrorDTO
80
+ errors = Errors(MyErrorDTO())
81
+
82
+ # Mixed
83
+ errors = Errors(
84
+ {409: {...}},
85
+ MyErrorDTO(),
86
+ unauthorized=True,
87
+ )
88
+ ```
89
+ """
90
+ self._responses: Dict[int, Dict[str, Any]] = {}
91
+
92
+ # Add standard errors
93
+ if unauthorized:
94
+ self._add_standard_error(
95
+ status.HTTP_401_UNAUTHORIZED,
96
+ "Unauthorized",
97
+ {"detail": "Unauthorized"},
98
+ )
99
+ if forbidden:
100
+ self._add_standard_error(
101
+ status.HTTP_403_FORBIDDEN,
102
+ "Forbidden",
103
+ {"detail": "Forbidden"},
104
+ )
105
+ if validation_error:
106
+ self._add_standard_error(
107
+ status.HTTP_422_UNPROCESSABLE_ENTITY,
108
+ "Validation Error",
109
+ {"detail": "Validation error"},
110
+ )
111
+ if internal_server_error:
112
+ self._add_standard_error(
113
+ status.HTTP_500_INTERNAL_SERVER_ERROR,
114
+ "Internal Server Error",
115
+ {"detail": "Internal Server Error"},
116
+ )
117
+
118
+ # Add arbitrary errors
119
+ for error in errors:
120
+ if isinstance(error, dict):
121
+ # Universal dict in FastAPI format - merge instead of overwrite
122
+ self._add_dict_error(error)
123
+ else:
124
+ # Validate ErrorDTO protocol before processing
125
+ self._validate_error_dto(error)
126
+ # ErrorDTO (compatible with ApiErrorDTO via Protocol)
127
+ self._add_error_dto(error)
128
+
129
+ def _validate_error_dto(self, error: Any) -> None:
130
+ """Validate that error object implements ErrorDTO protocol.
131
+
132
+ Args:
133
+ error: Object to validate
134
+
135
+ Raises:
136
+ TypeError: If object doesn't implement ErrorDTO protocol
137
+
138
+ Example:
139
+ ```python
140
+ # Valid object
141
+ class MyError:
142
+ status_code = 404
143
+ message = "Not found"
144
+ def to_example(self): ...
145
+
146
+ errors = Errors()
147
+ errors._validate_error_dto(MyError()) # OK
148
+
149
+ # Invalid object
150
+ class BadError:
151
+ status_code = 404
152
+ # Missing message and to_example
153
+
154
+ errors._validate_error_dto(BadError()) # Raises TypeError
155
+ ```
156
+ """
157
+ required_attrs = ("status_code", "message")
158
+ required_methods = ("to_example",)
159
+
160
+ missing_attrs = [
161
+ attr for attr in required_attrs
162
+ if not hasattr(error, attr)
163
+ ]
164
+ missing_methods = [
165
+ method for method in required_methods
166
+ if not hasattr(error, method) or not callable(getattr(error, method, None))
167
+ ]
168
+
169
+ if missing_attrs or missing_methods:
170
+ missing = missing_attrs + missing_methods
171
+ raise TypeError(
172
+ f"ErrorDTO object must have {', '.join(required_attrs)} attributes "
173
+ f"and {', '.join(required_methods)}() method. "
174
+ f"Missing: {', '.join(missing)}. "
175
+ f"Got {type(error).__name__}"
176
+ )
177
+
178
+ def _add_standard_error(
179
+ self,
180
+ status_code: int,
181
+ description: str,
182
+ example: Dict[str, Any],
183
+ ) -> None:
184
+ """Add standard error.
185
+
186
+ If the status code already exists, merges the example with existing examples
187
+ using a unique key instead of overwriting.
188
+
189
+ Args:
190
+ status_code: HTTP status code (e.g., 401, 403, 422, 500)
191
+ description: Error description for OpenAPI
192
+ example: Example response body (e.g., {"detail": "Unauthorized"})
193
+ """
194
+ # Generate unique key for standard example
195
+ standard_keys = {
196
+ status.HTTP_401_UNAUTHORIZED: "StandardUnauthorized",
197
+ status.HTTP_403_FORBIDDEN: "StandardForbidden",
198
+ status.HTTP_422_UNPROCESSABLE_ENTITY: "StandardValidationError",
199
+ status.HTTP_500_INTERNAL_SERVER_ERROR: "StandardInternalServerError",
200
+ }
201
+ example_key = standard_keys.get(status_code, f"Standard{status_code}")
202
+
203
+ if status_code not in self._responses:
204
+ self._responses[status_code] = {
205
+ "description": description,
206
+ "content": {
207
+ "application/json": {
208
+ "example": example,
209
+ },
210
+ },
211
+ }
212
+ else:
213
+ # If already exists, add to examples without overwriting
214
+ # Safely access content/application/json with defaults
215
+ existing = self._responses[status_code]
216
+ existing_content = existing.setdefault("content", {})
217
+ content = existing_content.setdefault("application/json", {})
218
+
219
+ # Convert example to examples if needed
220
+ if "examples" not in content:
221
+ if "example" in content:
222
+ existing_example = content.pop("example")
223
+ content["examples"] = {
224
+ "default": {"value": existing_example},
225
+ }
226
+ else:
227
+ content["examples"] = {}
228
+
229
+ # Add new example with unique key (don't overwrite existing!)
230
+ content["examples"][example_key] = {"value": example}
231
+
232
+ # Don't overwrite description if it already exists
233
+ # Priority: dict > DTO > standard flags
234
+
235
+ def _add_dict_error(self, error_dict: Dict[int, Dict[str, Any]]) -> None:
236
+ """Add error from dict in FastAPI responses format.
237
+
238
+ Merges examples instead of overwriting the entire response entry.
239
+
240
+ Args:
241
+ error_dict: Dict in format {status_code: {"description": ..., "content": {...}}}
242
+ """
243
+ for status_code, response_data in error_dict.items():
244
+ if status_code not in self._responses:
245
+ # New status code - just add it
246
+ self._responses[status_code] = response_data
247
+ else:
248
+ # Status code already exists - merge
249
+ existing = self._responses[status_code]
250
+
251
+ # Merge description (dict takes priority)
252
+ if "description" in response_data:
253
+ existing["description"] = response_data["description"]
254
+
255
+ # Merge content
256
+ if "content" in response_data:
257
+ existing_content = existing.setdefault("content", {})
258
+ response_content = response_data["content"]
259
+
260
+ # Merge application/json
261
+ if "application/json" in response_content:
262
+ existing_json = existing_content.setdefault("application/json", {})
263
+ response_json = response_content["application/json"]
264
+
265
+ # Handle example/examples
266
+ if "examples" in response_json:
267
+ # Response has examples
268
+ if "examples" not in existing_json:
269
+ # Convert existing example to examples if needed
270
+ if "example" in existing_json:
271
+ existing_example = existing_json.pop("example")
272
+ existing_json["examples"] = {
273
+ "default": {"value": existing_example},
274
+ }
275
+ else:
276
+ existing_json["examples"] = {}
277
+
278
+ # Merge examples
279
+ existing_json["examples"].update(response_json["examples"])
280
+ elif "example" in response_json:
281
+ # Response has example - convert and merge
282
+ if "examples" not in existing_json:
283
+ # Convert existing example to examples if needed
284
+ if "example" in existing_json:
285
+ existing_example = existing_json.pop("example")
286
+ # Check if existing example is from a standard flag
287
+ # Standard flags use specific messages
288
+ standard_messages = {
289
+ "Unauthorized": "StandardUnauthorized",
290
+ "Forbidden": "StandardForbidden",
291
+ "Validation error": "StandardValidationError",
292
+ "Internal Server Error": "StandardInternalServerError",
293
+ }
294
+ existing_detail = existing_example.get("detail", "")
295
+ example_key = standard_messages.get(existing_detail, "default")
296
+ existing_json["examples"] = {
297
+ example_key: {"value": existing_example},
298
+ }
299
+ else:
300
+ existing_json["examples"] = {}
301
+
302
+ # Add new example - use "default" if available, otherwise unique key
303
+ if "default" not in existing_json["examples"]:
304
+ existing_json["examples"]["default"] = {"value": response_json["example"]}
305
+ else:
306
+ # If default exists, add with a unique key
307
+ existing_json["examples"]["CustomExample"] = {"value": response_json["example"]}
308
+
309
+ def _add_error_dto(self, error_dto: ErrorDTO) -> None:
310
+ """Add error from ErrorDTO (via Protocol).
311
+
312
+ If the status code already exists, merges examples with existing examples.
313
+
314
+ Args:
315
+ error_dto: Error object implementing ErrorDTO protocol.
316
+ Must have `status_code`, `message`, and `to_example()` method.
317
+
318
+ Example:
319
+ ```python
320
+ class MyError:
321
+ status_code = 404
322
+ message = "Not found"
323
+ def to_example(self):
324
+ return {"Not found": {"value": {"detail": "Not found"}}}
325
+
326
+ errors = Errors()
327
+ errors._add_error_dto(MyError())
328
+ ```
329
+ """
330
+ status_code = error_dto.status_code
331
+ examples = error_dto.to_example()
332
+
333
+ if status_code not in self._responses:
334
+ self._responses[status_code] = {
335
+ "description": error_dto.message,
336
+ "content": {
337
+ "application/json": {
338
+ "examples": examples,
339
+ },
340
+ },
341
+ }
342
+ else:
343
+ # Merge examples for the same status code
344
+ # Safely access content/application/json with defaults
345
+ existing = self._responses[status_code]
346
+ existing_content = existing.setdefault("content", {})
347
+ content_json = existing_content.setdefault("application/json", {})
348
+ existing_examples = content_json.get("examples", {})
349
+
350
+ if "example" in content_json:
351
+ # Convert example to examples with correct key for standard flags
352
+ existing_example = content_json.pop("example")
353
+ existing_detail = existing_example.get("detail", "")
354
+
355
+ # Check if existing example is from a standard flag
356
+ standard_messages = {
357
+ "Unauthorized": "StandardUnauthorized",
358
+ "Forbidden": "StandardForbidden",
359
+ "Validation error": "StandardValidationError",
360
+ "Internal Server Error": "StandardInternalServerError",
361
+ }
362
+ example_key = standard_messages.get(existing_detail, "default")
363
+
364
+ existing_examples = {
365
+ example_key: {
366
+ "value": existing_example,
367
+ },
368
+ }
369
+
370
+ # Merge new examples from ErrorDTO
371
+ existing_examples.update(examples)
372
+ content_json["examples"] = existing_examples
373
+
374
+ # Mapping protocol implementation
375
+ def __getitem__(self, key: int) -> Dict[str, Any]:
376
+ """Get response for status code.
377
+
378
+ Args:
379
+ key: HTTP status code (e.g., 401, 403, 404)
380
+
381
+ Returns:
382
+ Response dict in FastAPI format
383
+
384
+ Raises:
385
+ KeyError: If status code not found
386
+ """
387
+ return self._responses[key]
388
+
389
+ def __iter__(self) -> Iterator[int]:
390
+ """Iterate over status codes.
391
+
392
+ Returns:
393
+ Iterator over status codes
394
+ """
395
+ return iter(self._responses)
396
+
397
+ def __len__(self) -> int:
398
+ """Get number of status codes.
399
+
400
+ Returns:
401
+ Number of documented error status codes
402
+ """
403
+ return len(self._responses)
404
+
@@ -0,0 +1,49 @@
1
+ """Protocol for error DTOs compatible with fastapi-errors-plus."""
2
+
3
+ from typing import Any, Dict, Protocol
4
+
5
+
6
+ class ErrorDTO(Protocol):
7
+ """Protocol for error objects compatible with the library.
8
+
9
+ Any class implementing this protocol can be used with Errors().
10
+
11
+ Example:
12
+ ```python
13
+ class MyError:
14
+ status_code = 404
15
+ message = "Not found"
16
+
17
+ def to_example(self) -> Dict[str, Any]:
18
+ return {
19
+ "Not found": {
20
+ "value": {"detail": "Not found"},
21
+ },
22
+ }
23
+
24
+ errors = Errors(MyError())
25
+ ```
26
+ """
27
+ status_code: int
28
+ """HTTP status code for the error."""
29
+
30
+ message: str
31
+ """Error message description."""
32
+
33
+ def to_example(self) -> Dict[str, Any]:
34
+ """Generate example for OpenAPI.
35
+
36
+ Returns:
37
+ Dict in format: {"key": {"value": {"detail": "message"}}}
38
+
39
+ Example:
40
+ ```python
41
+ {
42
+ "Not found": {
43
+ "value": {"detail": "Not found"},
44
+ },
45
+ }
46
+ ```
47
+ """
48
+ ...
49
+
@@ -0,0 +1,547 @@
1
+ Metadata-Version: 2.4
2
+ Name: fastapi-errors-plus
3
+ Version: 0.1.0
4
+ Summary: Universal library for documenting errors in FastAPI endpoints
5
+ Author-email: Igor Selivanov <seligoroff@gmail.com>
6
+ License: MIT
7
+ Keywords: fastapi,errors,openapi,documentation
8
+ Classifier: Development Status :: 3 - Alpha
9
+ Classifier: Intended Audience :: Developers
10
+ Classifier: License :: OSI Approved :: MIT License
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3.8
13
+ Classifier: Programming Language :: Python :: 3.9
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Framework :: FastAPI
17
+ Requires-Python: >=3.8
18
+ Description-Content-Type: text/markdown
19
+ License-File: LICENSE
20
+ Requires-Dist: fastapi>=0.104.0
21
+ Provides-Extra: dev
22
+ Requires-Dist: pytest>=7.4.0; extra == "dev"
23
+ Requires-Dist: pytest-asyncio>=0.21.0; extra == "dev"
24
+ Requires-Dist: pytest-cov>=4.1.0; extra == "dev"
25
+ Dynamic: license-file
26
+
27
+ # fastapi-errors-plus
28
+
29
+ [![PyPI version](https://badge.fury.io/py/fastapi-errors-plus.svg)](https://pypi.org/project/fastapi-errors-plus/)
30
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
31
+ [![Python 3.8+](https://img.shields.io/badge/python-3.8+-blue.svg)](https://www.python.org/downloads/)
32
+ [![FastAPI](https://img.shields.io/badge/FastAPI-0.104%2B-009688.svg)](https://fastapi.tiangolo.com/)
33
+ [![Tests](https://img.shields.io/badge/tests-41%20passed-success.svg)](https://github.com/yourusername/fastapi-errors-plus)
34
+ [![Coverage](https://img.shields.io/badge/coverage-83%25-green.svg)](https://github.com/yourusername/fastapi-errors-plus)
35
+
36
+ Universal library for documenting errors in FastAPI endpoints.
37
+
38
+ > [Русская версия README](README.ru.md)
39
+
40
+ ## Philosophy
41
+
42
+ `fastapi-errors-plus` is designed to be **universal** and work with **any** FastAPI project without requiring project-specific infrastructure. The library uses standard Python types (dict, Protocol) and allows projects to adapt their existing error infrastructure to work with the library through structural typing.
43
+
44
+ **Key principles:**
45
+ - **Universality** — works with any FastAPI project
46
+ - **Transparency** — all documented errors are visible directly in the endpoint
47
+ - **Self-sufficiency** — no need to search other files to understand documented errors
48
+ - **Compatibility** — works with existing project infrastructure through Protocol
49
+
50
+ ## Installation
51
+
52
+ ```bash
53
+ pip install fastapi-errors-plus
54
+ ```
55
+
56
+ Or install from source:
57
+
58
+ ```bash
59
+ git clone https://github.com/yourusername/fastapi-errors-plus.git
60
+ cd fastapi-errors-plus
61
+ pip install -e .
62
+ ```
63
+
64
+ ## Quick Start
65
+
66
+ ### Basic Usage
67
+
68
+ ```python
69
+ from fastapi import APIRouter
70
+ from fastapi_errors_plus import Errors
71
+
72
+ router = APIRouter()
73
+
74
+ @router.delete(
75
+ "/{id}",
76
+ responses=Errors(
77
+ {404: { # 404 via dict
78
+ "description": "Not found",
79
+ "content": {
80
+ "application/json": {
81
+ "example": {"detail": "Item not found"},
82
+ },
83
+ },
84
+ }},
85
+ unauthorized=True, # 401 Unauthorized
86
+ forbidden=True, # 403 Forbidden
87
+ validation_error=True, # 422 Validation Error
88
+ ),
89
+ )
90
+ def delete_item(id: int):
91
+ """Delete an item."""
92
+ # ... your code ...
93
+ pass
94
+ ```
95
+
96
+ ## Features
97
+
98
+ ### 1. Standard HTTP Status Flags
99
+
100
+ Use boolean flags for common HTTP status codes:
101
+
102
+ - `unauthorized=True` → 401 Unauthorized
103
+ - `forbidden=True` → 403 Forbidden
104
+ - `validation_error=True` → 422 Unprocessable Entity
105
+ - `internal_server_error=True` → 500 Internal Server Error
106
+
107
+ ```python
108
+ @router.get(
109
+ "/protected",
110
+ responses=Errors(
111
+ unauthorized=True,
112
+ forbidden=True,
113
+ ),
114
+ )
115
+ def get_protected():
116
+ """Protected endpoint."""
117
+ pass
118
+ ```
119
+
120
+ ### 2. Dict-based Errors
121
+
122
+ Use standard FastAPI `responses` dict format for custom errors:
123
+
124
+ ```python
125
+ @router.post(
126
+ "/items",
127
+ responses=Errors(
128
+ {
129
+ 409: {
130
+ "description": "Conflict",
131
+ "content": {
132
+ "application/json": {
133
+ "example": {"detail": "Item already exists"},
134
+ },
135
+ },
136
+ },
137
+ }
138
+ ),
139
+ )
140
+ def create_item():
141
+ """Create an item."""
142
+ pass
143
+ ```
144
+
145
+ ### 3. ErrorDTO Protocol
146
+
147
+ Use objects implementing the `ErrorDTO` protocol for project compatibility:
148
+
149
+ ```python
150
+ from fastapi_errors_plus import Errors, ErrorDTO
151
+
152
+ class MyErrorDTO:
153
+ status_code = 404
154
+ message = "Not found"
155
+
156
+ def to_example(self):
157
+ return {
158
+ "Not found": {
159
+ "value": {"detail": "Not found"},
160
+ },
161
+ }
162
+
163
+ @router.get(
164
+ "/resource/{id}",
165
+ responses=Errors(
166
+ MyErrorDTO(),
167
+ ),
168
+ )
169
+ def get_resource(id: int):
170
+ """Get a resource."""
171
+ pass
172
+ ```
173
+
174
+ ### 4. Mixed Usage
175
+
176
+ Combine flags, dict, and ErrorDTO:
177
+
178
+ ```python
179
+ @router.post(
180
+ "/items/{id}",
181
+ responses=Errors(
182
+ {409: {
183
+ "description": "Conflict",
184
+ "content": {
185
+ "application/json": {
186
+ "example": {"detail": "Already exists"},
187
+ },
188
+ },
189
+ }},
190
+ MyErrorDTO(), # ErrorDTO
191
+ unauthorized=True, # Flag
192
+ forbidden=True, # Flag
193
+ ),
194
+ )
195
+ def create_item_mixed(id: int):
196
+ """Create an item with mixed error types."""
197
+ pass
198
+ ```
199
+
200
+ ### 5. Merging Examples
201
+
202
+ Multiple errors with the same status code are automatically merged:
203
+
204
+ ```python
205
+ @router.put(
206
+ "/items/{id}",
207
+ responses=Errors(
208
+ Error1(), # 404
209
+ Error2(), # 404
210
+ ),
211
+ )
212
+ def update_item(id: int):
213
+ """Update an item."""
214
+ pass
215
+ ```
216
+
217
+ The OpenAPI spec will contain both examples under the 404 status code.
218
+
219
+ ## ErrorDTO Protocol
220
+
221
+ The `ErrorDTO` protocol defines the interface for error objects compatible with the library:
222
+
223
+ ```python
224
+ from typing import Protocol, Dict, Any
225
+
226
+ class ErrorDTO(Protocol):
227
+ status_code: int
228
+ message: str
229
+
230
+ def to_example(self) -> Dict[str, Any]:
231
+ """Generate example for OpenAPI.
232
+
233
+ Returns:
234
+ Dict in format: {"key": {"value": {"detail": "message"}}}
235
+ """
236
+ ...
237
+ ```
238
+
239
+ Any class implementing this protocol (through structural typing) can be used with `Errors()`.
240
+
241
+ ## Compatibility with Existing Projects
242
+
243
+ If your project already has error DTOs (like `ApiErrorDTO`), they can work with `fastapi-errors-plus` if they implement the `ErrorDTO` protocol:
244
+
245
+ ```python
246
+ # Your existing ApiErrorDTO
247
+ @dataclass
248
+ class ApiErrorDTO:
249
+ status_code: int
250
+ message: str
251
+
252
+ def to_example(self) -> dict:
253
+ return {
254
+ self.message: {
255
+ "value": {"detail": self.message},
256
+ },
257
+ }
258
+
259
+ # Works directly with fastapi-errors-plus!
260
+ @router.delete(
261
+ "/{id}",
262
+ responses=Errors(
263
+ ApiErrorDTO(status_code=404, message="Not found"),
264
+ ),
265
+ )
266
+ def delete_item(id: int):
267
+ pass
268
+ ```
269
+
270
+ ## API Reference
271
+
272
+ ### `Errors`
273
+
274
+ Main class for documenting errors in FastAPI endpoints.
275
+
276
+ #### Constructor
277
+
278
+ ```python
279
+ Errors(
280
+ *errors: Union[Dict[int, Dict[str, Any]], ErrorDTO],
281
+ unauthorized: bool = False,
282
+ forbidden: bool = False,
283
+ validation_error: bool = False,
284
+ internal_server_error: bool = False,
285
+ )
286
+ ```
287
+
288
+ **Parameters:**
289
+ - `*errors`: Arbitrary errors as dict or ErrorDTO objects
290
+ - `unauthorized`: Add 401 Unauthorized error
291
+ - `forbidden`: Add 403 Forbidden error
292
+ - `validation_error`: Add 422 Unprocessable Entity error
293
+ - `internal_server_error`: Add 500 Internal Server Error
294
+
295
+ **Returns:**
296
+ - Callable object that returns `Dict[int, Dict[str, Any]]` in FastAPI responses format
297
+
298
+ #### Usage
299
+
300
+ ```python
301
+ # Call the instance to get responses dict
302
+ responses = Errors(unauthorized=True)
303
+ ```
304
+
305
+ ### `ErrorDTO`
306
+
307
+ Protocol for error objects compatible with the library.
308
+
309
+ **Required attributes:**
310
+ - `status_code: int` — HTTP status code
311
+ - `message: str` — Error message description
312
+
313
+ **Required methods:**
314
+ - `to_example() -> Dict[str, Any]` — Generate example for OpenAPI
315
+
316
+ ## Examples
317
+
318
+ ### Example 1: Standard FastAPI Project
319
+
320
+ ```python
321
+ from fastapi import APIRouter
322
+ from fastapi_errors_plus import Errors
323
+
324
+ router = APIRouter()
325
+
326
+ @router.delete(
327
+ "/{id}",
328
+ responses=Errors(
329
+ {404: {
330
+ "description": "Not found",
331
+ "content": {
332
+ "application/json": {
333
+ "example": {"detail": "Item not found"},
334
+ },
335
+ },
336
+ }},
337
+ unauthorized=True,
338
+ forbidden=True,
339
+ ),
340
+ )
341
+ def delete_item(id: int):
342
+ """Delete an item."""
343
+ pass
344
+ ```
345
+
346
+ ### Example 2: Project with ErrorDTO
347
+
348
+ ```python
349
+ from fastapi import APIRouter
350
+ from fastapi_errors_plus import Errors
351
+ from api.exceptions.dto import errors # Your project's error DTOs
352
+
353
+ router = APIRouter()
354
+
355
+ @router.delete(
356
+ "/{notificationId}",
357
+ responses=Errors(
358
+ unauthorized=True,
359
+ forbidden=True,
360
+ errors.notification_not_found_error, # Your ErrorDTO
361
+ ),
362
+ )
363
+ async def delete_notification(notification_id: int):
364
+ """Delete a notification."""
365
+ pass
366
+ ```
367
+
368
+ ### Example 3: Multiple Examples for Same Status
369
+
370
+ ```python
371
+ @router.delete(
372
+ "/{id}",
373
+ responses=Errors(
374
+ unauthorized=True, # Basic 401
375
+ {401: { # Override with multiple examples
376
+ "description": "Unauthorized",
377
+ "content": {
378
+ "application/json": {
379
+ "examples": {
380
+ "InvalidToken": {"value": {"detail": "Invalid token"}},
381
+ "SessionNotFound": {"value": {"detail": "Session not found"}},
382
+ },
383
+ },
384
+ },
385
+ }},
386
+ ),
387
+ )
388
+ def delete_item(id: int):
389
+ """Delete an item."""
390
+ pass
391
+ ```
392
+
393
+ ### Example 4: Clean Architecture Integration
394
+
395
+ This example shows how to use `fastapi-errors-plus` in a FastAPI project with Clean Architecture:
396
+
397
+ **Domain Layer** (`domain/errors.py`):
398
+ ```python
399
+ from typing import Protocol, Dict, Any
400
+
401
+ class DomainError(Protocol):
402
+ """Domain error protocol compatible with ErrorDTO."""
403
+ status_code: int
404
+ message: str
405
+
406
+ def to_example(self) -> Dict[str, Any]:
407
+ """Generate example for OpenAPI."""
408
+ ...
409
+
410
+ class ItemNotFoundError:
411
+ """Domain error for item not found."""
412
+ status_code = 404
413
+ message = "Item not found"
414
+
415
+ def to_example(self) -> Dict[str, Any]:
416
+ return {
417
+ "ItemNotFound": {
418
+ "value": {"detail": "Item not found"},
419
+ },
420
+ }
421
+
422
+ class ItemAlreadyExistsError:
423
+ """Domain error for item already exists."""
424
+ status_code = 409
425
+ message = "Item already exists"
426
+
427
+ def to_example(self) -> Dict[str, Any]:
428
+ return {
429
+ "ItemAlreadyExists": {
430
+ "value": {"detail": "Item already exists"},
431
+ },
432
+ }
433
+ ```
434
+
435
+ **Application Layer** (`application/use_cases.py`):
436
+ ```python
437
+ from domain.errors import ItemNotFoundError, ItemAlreadyExistsError
438
+
439
+ class CreateItemUseCase:
440
+ """Use case for creating an item."""
441
+
442
+ def execute(self, item_data: dict):
443
+ # Business logic here
444
+ if self._item_exists(item_data["id"]):
445
+ raise ItemAlreadyExistsError()
446
+ # ... create item ...
447
+ return item
448
+
449
+ class GetItemUseCase:
450
+ """Use case for getting an item."""
451
+
452
+ def execute(self, item_id: int):
453
+ item = self._repository.get(item_id)
454
+ if not item:
455
+ raise ItemNotFoundError()
456
+ return item
457
+ ```
458
+
459
+ **Infrastructure/Presentation Layer** (`api/routes/items.py`):
460
+ ```python
461
+ from fastapi import APIRouter, Depends, HTTPException, status
462
+ from fastapi_errors_plus import Errors
463
+ from domain.errors import ItemNotFoundError, ItemAlreadyExistsError
464
+ from application.use_cases import CreateItemUseCase, GetItemUseCase
465
+
466
+ router = APIRouter()
467
+
468
+ @router.post(
469
+ "/items",
470
+ status_code=status.HTTP_201_CREATED,
471
+ responses=Errors(
472
+ unauthorized=True, # From authentication dependency
473
+ forbidden=True, # From authorization dependency
474
+ validation_error=True, # From FastAPI validation
475
+ ItemAlreadyExistsError(), # Domain error
476
+ ),
477
+ )
478
+ async def create_item(
479
+ item_data: dict,
480
+ use_case: CreateItemUseCase = Depends(),
481
+ ):
482
+ """Create a new item."""
483
+ try:
484
+ item = use_case.execute(item_data)
485
+ return item
486
+ except ItemAlreadyExistsError as e:
487
+ raise HTTPException(
488
+ status_code=e.status_code,
489
+ detail=e.message,
490
+ )
491
+
492
+ @router.get(
493
+ "/items/{item_id}",
494
+ responses=Errors(
495
+ unauthorized=True,
496
+ forbidden=True,
497
+ ItemNotFoundError(), # Domain error
498
+ ),
499
+ )
500
+ async def get_item(
501
+ item_id: int,
502
+ use_case: GetItemUseCase = Depends(),
503
+ ):
504
+ """Get an item by ID."""
505
+ try:
506
+ item = use_case.execute(item_id)
507
+ return item
508
+ except ItemNotFoundError as e:
509
+ raise HTTPException(
510
+ status_code=e.status_code,
511
+ detail=e.message,
512
+ )
513
+ ```
514
+
515
+ **Benefits of this approach:**
516
+ - Domain errors are reusable across layers
517
+ - Errors are documented directly in the endpoint
518
+ - Clean separation of concerns
519
+ - Domain layer doesn't depend on FastAPI
520
+ - Easy to test domain errors independently
521
+
522
+ ## Limitations
523
+
524
+ The library improves **transparency of documented** errors. It does **not** solve the problem of finding **all real** errors in an endpoint, which requires analyzing the entire codebase (transaction scripts, `Depends` dependencies, database operations, etc.).
525
+
526
+ **What the library does:**
527
+ - Improves transparency of documented errors
528
+ - Simplifies syntax for documenting errors
529
+ - Makes errors visible directly in the endpoint
530
+
531
+ **What the library does not do:**
532
+ - Find all real errors in an endpoint automatically
533
+ - Analyze code to discover errors
534
+ - Guarantee completeness of error lists
535
+
536
+ ## Contributing
537
+
538
+ Contributions are welcome! Please feel free to submit a Pull Request.
539
+
540
+ ## License
541
+
542
+ MIT
543
+
544
+ ## Changelog
545
+
546
+ See [CHANGELOG.md](CHANGELOG.md) for detailed changelog.
547
+
@@ -0,0 +1,8 @@
1
+ fastapi_errors_plus/__init__.py,sha256=Dbn9fmqBoSa5yTF0d4gVvyoJ61pI3My3aZNMq8wsGGg,223
2
+ fastapi_errors_plus/errors.py,sha256=kvM2DeDYJ-pMREWmSslF0KgIWixERqj-Nt5oJ8IeSHc,16325
3
+ fastapi_errors_plus/protocol.py,sha256=mSb-nabNDz7tjbSboHOQJu6QGsUPZOivC-XztvYoHRA,1215
4
+ fastapi_errors_plus-0.1.0.dist-info/licenses/LICENSE,sha256=wKw57ZiHT4OAK3euOE2UxSzr3RN_AEarSxQV88xMBgA,1090
5
+ fastapi_errors_plus-0.1.0.dist-info/METADATA,sha256=wEThfjUfdMt4sUG6paPrTBE_gGVj5QVWbXg2oPe-26o,14039
6
+ fastapi_errors_plus-0.1.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
7
+ fastapi_errors_plus-0.1.0.dist-info/top_level.txt,sha256=vmHLF1-DQYB2quqrvdBA0g6rDtgOWQBrA1m-X_WyNk8,20
8
+ fastapi_errors_plus-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (80.9.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 fastapi-errors-plus contributors
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.
22
+
@@ -0,0 +1 @@
1
+ fastapi_errors_plus