fastapi-errors-plus 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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,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
+