fastapi-custom-responses 0.0.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,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.
@@ -0,0 +1,21 @@
1
+ Metadata-Version: 2.3
2
+ Name: fastapi-custom-responses
3
+ Version: 0.0.0
4
+ Summary: FastAPI Custom Responses
5
+ Author: Julien Kmec
6
+ Author-email: me@julien.dev
7
+ Requires-Python: >=3.11.0,<3.14
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: Programming Language :: Python :: 3.11
10
+ Classifier: Programming Language :: Python :: 3.12
11
+ Classifier: Programming Language :: Python :: 3.13
12
+ Provides-Extra: dev
13
+ Requires-Dist: black (>=24.3.0,<25.0.0) ; extra == "dev"
14
+ Requires-Dist: fastapi[standard] (>=0.115.14)
15
+ Requires-Dist: isort (>=5.12.0,<6.0.0) ; extra == "dev"
16
+ Requires-Dist: pydantic (>=2.10.6)
17
+ Requires-Dist: pydantic-super-model (>=1.0.3,<2.0.0)
18
+ Requires-Dist: pylint (>=3.0.1,<4.0.0) ; extra == "dev"
19
+ Description-Content-Type: text/markdown
20
+
21
+
File without changes
@@ -0,0 +1,2 @@
1
+ from .errors import setup_error_handlers, ErrorResponse
2
+ from .responses import Response, PaginatedResponse
@@ -0,0 +1,95 @@
1
+ from http import HTTPStatus
2
+ import logging
3
+ from fastapi import FastAPI, Request, status
4
+ from fastapi.exceptions import RequestValidationError
5
+ from fastapi.responses import JSONResponse
6
+ from fastapi_responses.responses import Response
7
+
8
+ logger = logging.getLogger(__name__)
9
+
10
+ ERROR_MESSAGES: dict[int, str] = {
11
+ 401: "Authentication required",
12
+ 403: "You don't have permission to perform this action",
13
+ 404: "Resource not found",
14
+ 400: "Invalid request",
15
+ 422: "Invalid request data",
16
+ 500: "An unexpected error occurred",
17
+ }
18
+
19
+
20
+ class ErrorResponse(Exception):
21
+ """Standard error response that includes error message."""
22
+
23
+ def __init__(self, error: str, status_code: int = HTTPStatus.BAD_REQUEST) -> None:
24
+ """Initialize error response with message and status code.
25
+
26
+ Args:
27
+ error: Error message to return
28
+ status_code: HTTP status code for the response
29
+ """
30
+
31
+ self.error = error
32
+ self.status_code = status_code
33
+
34
+ super().__init__(error)
35
+
36
+ @classmethod
37
+ def from_status_code(cls, status_code: int) -> "ErrorResponse":
38
+ """Create an error response from a status code.
39
+
40
+ Args:
41
+ status_code: HTTP status code to get error message for
42
+
43
+ Returns:
44
+ ErrorResponse with the appropriate error message for the status code
45
+ """
46
+
47
+ return cls(
48
+ error=ERROR_MESSAGES.get(status_code, ERROR_MESSAGES[500]),
49
+ status_code=status_code,
50
+ )
51
+
52
+
53
+ def setup_error_handlers(app: FastAPI) -> None:
54
+ """Set up global error handlers for the application."""
55
+
56
+ @app.exception_handler(RequestValidationError)
57
+ async def validation_exception_handler(
58
+ _: Request, exc: RequestValidationError
59
+ ) -> JSONResponse:
60
+ """Handle validation errors from pydantic models."""
61
+
62
+ logger.exception(exc)
63
+
64
+ response = Response(success=False, error=ERROR_MESSAGES[422])
65
+
66
+ return JSONResponse(
67
+ status_code=status.HTTP_400_BAD_REQUEST,
68
+ content=response.model_dump(mode="json"),
69
+ )
70
+
71
+ @app.exception_handler(ErrorResponse)
72
+ async def error_response_handler(_: Request, exc: ErrorResponse) -> JSONResponse:
73
+ """Convert ErrorResponse exceptions to proper JSONResponse objects."""
74
+
75
+ logger.info("ErrorResponse: %s - %s", exc.status_code, exc.error)
76
+
77
+ response = Response(success=False, error=exc.error)
78
+
79
+ return JSONResponse(
80
+ status_code=exc.status_code,
81
+ content=response.model_dump(mode="json"),
82
+ )
83
+
84
+ @app.exception_handler(Exception)
85
+ async def general_exception_handler(_: Request, exc: Exception) -> JSONResponse:
86
+ """Handle all unhandled exceptions."""
87
+
88
+ logger.exception(exc)
89
+
90
+ response = Response(success=False, error=ERROR_MESSAGES[500])
91
+
92
+ return JSONResponse(
93
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
94
+ content=response.model_dump(mode="json"),
95
+ )
@@ -0,0 +1,24 @@
1
+ from typing import Any
2
+ from pydantic_super_model import SuperModel
3
+
4
+
5
+ class Response[T](SuperModel):
6
+ """Response model."""
7
+
8
+ success: bool
9
+ data: T | None = None
10
+ error: str | None = None
11
+
12
+
13
+ class PaginationMeta(SuperModel):
14
+ """Pagination metadata model."""
15
+
16
+ offset: int
17
+ limit: int
18
+ count: int
19
+
20
+
21
+ class PaginatedResponse[T: Any](Response[list[T]]):
22
+ """Paginated response model."""
23
+
24
+ meta: PaginationMeta
@@ -0,0 +1,35 @@
1
+ [project]
2
+ name = "fastapi-custom-responses"
3
+ version = "0.0.0"
4
+ description = "FastAPI Custom Responses"
5
+ authors = [
6
+ { name = "Julien Kmec", email = "me@julien.dev" },
7
+ ]
8
+ readme = "README.md"
9
+ homepage = "https://github.com/julien777z/fastapi-custom-responses"
10
+ packages = [{include = "fastapi_custom_responses"}]
11
+ requires-python = ">=3.11.0,<3.14"
12
+ dependencies = [
13
+ "pydantic>=2.10.6",
14
+ "fastapi[standard]>=0.115.14",
15
+ "pydantic-super-model (>=1.0.3,<2.0.0)",
16
+ ]
17
+
18
+ [tool.black]
19
+ line-length = 110
20
+ target-version = ["py312"]
21
+
22
+ [tool.isort]
23
+ profile = "black"
24
+ line_length = 110
25
+
26
+ [project.optional-dependencies]
27
+ dev = [
28
+ "black (>=24.3.0,<25.0.0)",
29
+ "isort (>=5.12.0,<6.0.0)",
30
+ "pylint (>=3.0.1,<4.0.0)",
31
+ ]
32
+
33
+ [build-system]
34
+ requires = ["poetry-core", "setuptools"]
35
+ build-backend = "poetry.core.masonry.api"