fastapi-custom-responses 0.0.11__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,2 @@
1
+ from .errors import EXCEPTION_HANDLERS, ErrorResponse, ErrorResponseModel
2
+ from .responses import PaginatedResponse, PaginationMeta, Response
@@ -0,0 +1,120 @@
1
+ import logging
2
+ from http import HTTPStatus
3
+ from typing import Callable
4
+
5
+ from fastapi import Request, status
6
+ from fastapi.exceptions import RequestValidationError
7
+ from fastapi.responses import JSONResponse
8
+ from pydantic import BaseModel
9
+
10
+ from fastapi_custom_responses.responses import Response
11
+
12
+ logger = logging.getLogger(__name__)
13
+
14
+ ERROR_MESSAGES: dict[int, str] = {
15
+ HTTPStatus.UNAUTHORIZED: "Authentication required",
16
+ HTTPStatus.FORBIDDEN: "You don't have permission to perform this action",
17
+ HTTPStatus.NOT_FOUND: "Resource not found",
18
+ HTTPStatus.BAD_REQUEST: "Invalid request",
19
+ HTTPStatus.INTERNAL_SERVER_ERROR: "An unexpected error occurred",
20
+ }
21
+
22
+
23
+ class ErrorResponseModel(BaseModel):
24
+ """Pydantic model for error response schema. Use this in FastAPI's `responses` parameter to document the error response schema."""
25
+
26
+ success: bool
27
+ error: str
28
+
29
+
30
+ class ErrorResponse(Exception):
31
+ """Standard error response that includes error message."""
32
+
33
+ def __init__(self, error: str, status_code: int = HTTPStatus.BAD_REQUEST) -> None:
34
+ """Initialize error response with message and status code.
35
+
36
+ Args:
37
+ error: Error message to return
38
+ status_code: HTTP status code for the response
39
+ """
40
+
41
+ self.error = error
42
+ self.status_code = status_code
43
+
44
+ super().__init__(error)
45
+
46
+ @classmethod
47
+ def from_status_code(cls, status_code: int) -> "ErrorResponse":
48
+ """Create an error response from a status code.
49
+
50
+ Args:
51
+ status_code: HTTP status code to get error message for
52
+
53
+ Returns:
54
+ ErrorResponse with the appropriate error message for the status code
55
+ """
56
+
57
+ return cls(
58
+ error=ERROR_MESSAGES.get(status_code, ERROR_MESSAGES[HTTPStatus.INTERNAL_SERVER_ERROR]),
59
+ status_code=status_code,
60
+ )
61
+
62
+
63
+ def _validation_exception_handler(_: Request, exc: RequestValidationError) -> JSONResponse:
64
+ """Handle validation errors from pydantic models."""
65
+
66
+ logger.exception(exc)
67
+
68
+ response = Response(success=False, error=ERROR_MESSAGES[HTTPStatus.BAD_REQUEST])
69
+
70
+ return JSONResponse(
71
+ status_code=status.HTTP_400_BAD_REQUEST,
72
+ content=response.model_dump(mode="json"),
73
+ )
74
+
75
+
76
+ def _value_error_handler(_: Request, exc: ValueError) -> JSONResponse:
77
+ """Handle value errors, e.g., Pydantic validation errors."""
78
+
79
+ logger.exception(exc)
80
+
81
+ response = Response(success=False, error=str(exc))
82
+
83
+ return JSONResponse(
84
+ status_code=status.HTTP_400_BAD_REQUEST,
85
+ content=response.model_dump(mode="json"),
86
+ )
87
+
88
+
89
+ def _error_response_handler(_: Request, exc: ErrorResponse) -> JSONResponse:
90
+ """Convert ErrorResponse exceptions to proper JSONResponse objects."""
91
+
92
+ logger.info("ErrorResponse: %s - %s", exc.status_code, exc.error)
93
+
94
+ response = Response(success=False, error=exc.error)
95
+
96
+ return JSONResponse(
97
+ status_code=exc.status_code,
98
+ content=response.model_dump(mode="json"),
99
+ )
100
+
101
+
102
+ def _general_exception_handler(_: Request, exc: Exception) -> JSONResponse:
103
+ """Handle all unhandled exceptions."""
104
+
105
+ logger.exception(exc)
106
+
107
+ response = Response(success=False, error=ERROR_MESSAGES[HTTPStatus.INTERNAL_SERVER_ERROR])
108
+
109
+ return JSONResponse(
110
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
111
+ content=response.model_dump(mode="json"),
112
+ )
113
+
114
+
115
+ EXCEPTION_HANDLERS: dict[type[Exception], Callable[[Request, Exception], JSONResponse]] = {
116
+ RequestValidationError: _value_error_handler,
117
+ ValueError: _value_error_handler,
118
+ ErrorResponse: _error_response_handler,
119
+ Exception: _general_exception_handler,
120
+ }
@@ -0,0 +1,25 @@
1
+ from typing import Any
2
+
3
+ from pydantic_super_model import SuperModel
4
+
5
+
6
+ class Response[T](SuperModel):
7
+ """Response model."""
8
+
9
+ success: bool
10
+ data: T | None = None
11
+ error: str | None = None
12
+
13
+
14
+ class PaginationMeta(SuperModel):
15
+ """Pagination metadata model."""
16
+
17
+ offset: int
18
+ limit: int
19
+ total: int
20
+
21
+
22
+ class PaginatedResponse[T: Any](Response[list[T]]):
23
+ """Paginated response model."""
24
+
25
+ meta: PaginationMeta
@@ -0,0 +1,109 @@
1
+ Metadata-Version: 2.4
2
+ Name: fastapi-custom-responses
3
+ Version: 0.0.11
4
+ Summary: FastAPI Custom Responses
5
+ License: MIT License
6
+
7
+ Copyright (c) 2025 KRYSTAL
8
+
9
+ Permission is hereby granted, free of charge, to any person obtaining a copy
10
+ of this software and associated documentation files (the "Software"), to deal
11
+ in the Software without restriction, including without limitation the rights
12
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13
+ copies of the Software, and to permit persons to whom the Software is
14
+ furnished to do so, subject to the following conditions:
15
+
16
+ The above copyright notice and this permission notice shall be included in all
17
+ copies or substantial portions of the Software.
18
+
19
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
25
+ SOFTWARE.
26
+ License-File: LICENSE
27
+ Author: Julien Kmec
28
+ Author-email: me@julien.dev
29
+ Requires-Python: >=3.11,<3.15
30
+ Classifier: License :: Other/Proprietary License
31
+ Classifier: Programming Language :: Python :: 3
32
+ Classifier: Programming Language :: Python :: 3.11
33
+ Classifier: Programming Language :: Python :: 3.12
34
+ Classifier: Programming Language :: Python :: 3.13
35
+ Classifier: Programming Language :: Python :: 3.14
36
+ Provides-Extra: dev
37
+ Requires-Dist: black (>=24.3.0,<25.0.0) ; extra == "dev"
38
+ Requires-Dist: fastapi[standard] (>=0.115.14)
39
+ Requires-Dist: isort (>=5.12.0,<6.0.0) ; extra == "dev"
40
+ Requires-Dist: pydantic (>=2.10.6)
41
+ Requires-Dist: pydantic-super-model (>=1.1.2)
42
+ Requires-Dist: pylint (>=3.0.1,<4.0.0) ; extra == "dev"
43
+ Description-Content-Type: text/markdown
44
+
45
+ # FastAPI Custom Responses
46
+
47
+ Provides normalized response objects and error handling
48
+
49
+ ## Example
50
+
51
+ ```py
52
+ from http import HTTPStatus
53
+ from fastapi_custom_responses import EXCEPTION_HANDLERS, ErrorResponse, ErrorResponseModel, Response
54
+ from fastapi import APIRouter, FastAPI, Request
55
+
56
+ # Initialize FastAPI
57
+ router = APIRouter()
58
+
59
+ app = FastAPI(
60
+ title="API",
61
+ description="My API",
62
+ version="1.0.0",
63
+ exception_handlers=EXCEPTION_HANDLERS, # Use error handler from library
64
+ )
65
+
66
+ # Define data model
67
+ class Data(Response):
68
+ example: str
69
+
70
+ # Routes
71
+ @router.get(
72
+ "/",
73
+ response_model=Response[Data],
74
+ responses={
75
+ 400: {"model": ErrorResponseModel, "description": "Bad request"},
76
+ 500: {"model": ErrorResponseModel, "description": "Internal server error"},
77
+ },
78
+ )
79
+ async def index(_: Request) -> Response[Data]:
80
+ """Index route."""
81
+
82
+ return Response(
83
+ success=True,
84
+ data=Data(example="hello"),
85
+ )
86
+
87
+ @router.get(
88
+ "/return-error",
89
+ response_model=Response[Data],
90
+ responses={
91
+ HTTPStatus.FORBIDDEN: {
92
+ "description": "User belongs to a different organization",
93
+ "model": ErrorResponseModel,
94
+ "content": {
95
+ "application/json": {
96
+ "example": {
97
+ "success": False,
98
+ "error": "User belongs to a different organization",
99
+ },
100
+ },
101
+ },
102
+ },
103
+ },
104
+ )
105
+ async def error_route(_: Request) -> Response:
106
+ """Error route."""
107
+
108
+ raise ErrorResponse(error="Your request is invalid.", status_code=HTTPStatus.BAD_REQUEST)
109
+ ```
@@ -0,0 +1,7 @@
1
+ fastapi_custom_responses/__init__.py,sha256=zi9Dki562lstWxGcx5qQulI12x4YNHXij2r4j6kPnfU,141
2
+ fastapi_custom_responses/errors.py,sha256=LuzUfo432BkO4stbKo57lS_npYypczFohWr1lomHwD0,3665
3
+ fastapi_custom_responses/responses.py,sha256=IFWAEyI-UQQ8hgMQraAoUX7ehe_joB1oEo63hBLEcZo,437
4
+ fastapi_custom_responses-0.0.11.dist-info/METADATA,sha256=0wqgmeRE-bTQlUiAdwAya_H3sSvdBhR6YkJoUFUZ1Gs,3752
5
+ fastapi_custom_responses-0.0.11.dist-info/WHEEL,sha256=zp0Cn7JsFoX2ATtOhtaFYIiE2rmFAD4OcMhtUki8W3U,88
6
+ fastapi_custom_responses-0.0.11.dist-info/licenses/LICENSE,sha256=QhnxalVFkRcaDnRpKtlGMBA0V_riuWAFEauYASyBTmI,1064
7
+ fastapi_custom_responses-0.0.11.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: poetry-core 2.2.1
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 KRYSTAL
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.