apiformat 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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Core Developer
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,115 @@
1
+ Metadata-Version: 2.4
2
+ Name: apiformat
3
+ Version: 0.1.0
4
+ Summary: A lightweight, framework-agnostic Python package for standardized API responses.
5
+ Author: Core Developer
6
+ License: MIT
7
+ Classifier: Programming Language :: Python :: 3
8
+ Classifier: License :: OSI Approved :: MIT License
9
+ Classifier: Operating System :: OS Independent
10
+ Requires-Python: >=3.8
11
+ Description-Content-Type: text/markdown
12
+ License-File: LICENSE
13
+ Provides-Extra: django
14
+ Requires-Dist: django; extra == "django"
15
+ Provides-Extra: fastapi
16
+ Requires-Dist: fastapi; extra == "fastapi"
17
+ Requires-Dist: pydantic; extra == "fastapi"
18
+ Provides-Extra: dev
19
+ Requires-Dist: pytest>=7.0.0; extra == "dev"
20
+ Requires-Dist: pytest-cov>=4.0.0; extra == "dev"
21
+ Requires-Dist: mypy>=1.0.0; extra == "dev"
22
+ Dynamic: license-file
23
+
24
+ # apiformat
25
+
26
+ A lightweight, framework-agnostic Python package that enforces a single, consistent response format across all API endpoints.
27
+
28
+ ## Installation
29
+
30
+ ```bash
31
+ pip install apiformat
32
+ ```
33
+
34
+ ## Core Module (No Dependencies)
35
+
36
+ ```python
37
+ from apiformat import success, error
38
+
39
+ # Success response
40
+ response = success(
41
+ data={"id": 1, "name": "John"},
42
+ message="User created successfully"
43
+ )
44
+ # Output:
45
+ # {
46
+ # "status": "success",
47
+ # "message": "User created successfully",
48
+ # "data": {"id": 1, "name": "John"},
49
+ # "meta": {}
50
+ # }
51
+
52
+ # Error response
53
+ response = error(
54
+ message="User not found",
55
+ status_code=404
56
+ )
57
+ # Output:
58
+ # {
59
+ # "status": "error",
60
+ # "message": "User not found",
61
+ # "data": None,
62
+ # "meta": {}
63
+ # }
64
+ ```
65
+
66
+ ## Django Integration
67
+
68
+ ```python
69
+ from apiformat.integrations.django import success_response, error_response
70
+
71
+ def create_user(request):
72
+ user = User.objects.create(name="John")
73
+ return success_response(
74
+ data={"id": user.id, "name": user.name},
75
+ message="User created",
76
+ status=201
77
+ )
78
+
79
+ def get_user(request, user_id):
80
+ try:
81
+ user = User.objects.get(id=user_id)
82
+ return success_response(data={"id": user.id, "name": user.name})
83
+ except User.DoesNotExist:
84
+ return error_response(message="User not found", status=404)
85
+ ```
86
+
87
+ ## FastAPI Integration
88
+
89
+ ```python
90
+ from fastapi import FastAPI
91
+ from apiformat.integrations.fastapi import success_response, error_response
92
+
93
+ app = FastAPI()
94
+
95
+ @app.post("/users")
96
+ async def create_user(name: str):
97
+ user = User(name=name)
98
+ user.save()
99
+ return success_response(
100
+ data={"id": user.id, "name": user.name},
101
+ message="User created",
102
+ status_code=201
103
+ )
104
+
105
+ @app.get("/users/{user_id}")
106
+ async def get_user(user_id: int):
107
+ user = User.get_by_id(user_id)
108
+ if not user:
109
+ return error_response(message="User not found", status_code=404)
110
+ return success_response(data={"id": user.id, "name": user.name})
111
+ ```
112
+
113
+ ## License
114
+
115
+ MIT
@@ -0,0 +1,92 @@
1
+ # apiformat
2
+
3
+ A lightweight, framework-agnostic Python package that enforces a single, consistent response format across all API endpoints.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ pip install apiformat
9
+ ```
10
+
11
+ ## Core Module (No Dependencies)
12
+
13
+ ```python
14
+ from apiformat import success, error
15
+
16
+ # Success response
17
+ response = success(
18
+ data={"id": 1, "name": "John"},
19
+ message="User created successfully"
20
+ )
21
+ # Output:
22
+ # {
23
+ # "status": "success",
24
+ # "message": "User created successfully",
25
+ # "data": {"id": 1, "name": "John"},
26
+ # "meta": {}
27
+ # }
28
+
29
+ # Error response
30
+ response = error(
31
+ message="User not found",
32
+ status_code=404
33
+ )
34
+ # Output:
35
+ # {
36
+ # "status": "error",
37
+ # "message": "User not found",
38
+ # "data": None,
39
+ # "meta": {}
40
+ # }
41
+ ```
42
+
43
+ ## Django Integration
44
+
45
+ ```python
46
+ from apiformat.integrations.django import success_response, error_response
47
+
48
+ def create_user(request):
49
+ user = User.objects.create(name="John")
50
+ return success_response(
51
+ data={"id": user.id, "name": user.name},
52
+ message="User created",
53
+ status=201
54
+ )
55
+
56
+ def get_user(request, user_id):
57
+ try:
58
+ user = User.objects.get(id=user_id)
59
+ return success_response(data={"id": user.id, "name": user.name})
60
+ except User.DoesNotExist:
61
+ return error_response(message="User not found", status=404)
62
+ ```
63
+
64
+ ## FastAPI Integration
65
+
66
+ ```python
67
+ from fastapi import FastAPI
68
+ from apiformat.integrations.fastapi import success_response, error_response
69
+
70
+ app = FastAPI()
71
+
72
+ @app.post("/users")
73
+ async def create_user(name: str):
74
+ user = User(name=name)
75
+ user.save()
76
+ return success_response(
77
+ data={"id": user.id, "name": user.name},
78
+ message="User created",
79
+ status_code=201
80
+ )
81
+
82
+ @app.get("/users/{user_id}")
83
+ async def get_user(user_id: int):
84
+ user = User.get_by_id(user_id)
85
+ if not user:
86
+ return error_response(message="User not found", status_code=404)
87
+ return success_response(data={"id": user.id, "name": user.name})
88
+ ```
89
+
90
+ ## License
91
+
92
+ MIT
@@ -0,0 +1,4 @@
1
+ from .core import success, error, APIResponse
2
+ from .exceptions import APIException
3
+
4
+ __all__ = ["success", "error", "APIResponse", "APIException"]
@@ -0,0 +1,51 @@
1
+ from typing import Any, Optional, Dict
2
+
3
+ def success(
4
+ data: Any = None,
5
+ message: str = "Success",
6
+ meta: Optional[Dict] = None
7
+ ) -> Dict[str, Any]:
8
+ """Return a standardized success response."""
9
+ return {
10
+ "status": "success",
11
+ "message": message,
12
+ "data": data,
13
+ "meta": meta or {},
14
+ }
15
+
16
+ def error(
17
+ message: str = "Error",
18
+ data: Any = None,
19
+ meta: Optional[Dict] = None
20
+ ) -> Dict[str, Any]:
21
+ """Return a standardized error response."""
22
+ return {
23
+ "status": "error",
24
+ "message": message,
25
+ "data": data,
26
+ "meta": meta or {},
27
+ }
28
+
29
+ class APIResponse:
30
+ """Encapsulates a standardized API response."""
31
+
32
+ def __init__(
33
+ self,
34
+ status: str,
35
+ message: str = "",
36
+ data: Any = None,
37
+ meta: Optional[Dict] = None
38
+ ):
39
+ self.status = status
40
+ self.message = message
41
+ self.data = data
42
+ self.meta = meta or {}
43
+
44
+ def to_dict(self) -> Dict[str, Any]:
45
+ """Convert to dictionary representation."""
46
+ return {
47
+ "status": self.status,
48
+ "message": self.message,
49
+ "data": self.data,
50
+ "meta": self.meta,
51
+ }
@@ -0,0 +1,10 @@
1
+ from typing import Any
2
+
3
+ class APIException(Exception):
4
+ """Base exception for API errors."""
5
+
6
+ def __init__(self, message: str, status_code: int = 400, data: Any = None):
7
+ self.message = message
8
+ self.status_code = status_code
9
+ self.data = data
10
+ super().__init__(self.message)
@@ -0,0 +1 @@
1
+ # Integrations package
@@ -0,0 +1,10 @@
1
+ from django.http import JsonResponse
2
+ from apiformat.core import success, error
3
+
4
+ def success_response(data=None, message="Success", status=200):
5
+ """Return Django JsonResponse with standardized format."""
6
+ return JsonResponse(success(data, message), status=status)
7
+
8
+ def error_response(message="Error", status=400, data=None):
9
+ """Return Django JsonResponse with standardized error format."""
10
+ return JsonResponse(error(message, data), status=status)
@@ -0,0 +1,10 @@
1
+ from fastapi.responses import JSONResponse
2
+ from apiformat.core import success, error
3
+
4
+ def success_response(data=None, message="Success", status_code=200):
5
+ """Return FastAPI JSONResponse with standardized format."""
6
+ return JSONResponse(success(data, message), status_code=status_code)
7
+
8
+ def error_response(message="Error", status_code=400, data=None):
9
+ """Return FastAPI JSONResponse with standardized error format."""
10
+ return JSONResponse(error(message, data), status_code=status_code)
@@ -0,0 +1,115 @@
1
+ Metadata-Version: 2.4
2
+ Name: apiformat
3
+ Version: 0.1.0
4
+ Summary: A lightweight, framework-agnostic Python package for standardized API responses.
5
+ Author: Core Developer
6
+ License: MIT
7
+ Classifier: Programming Language :: Python :: 3
8
+ Classifier: License :: OSI Approved :: MIT License
9
+ Classifier: Operating System :: OS Independent
10
+ Requires-Python: >=3.8
11
+ Description-Content-Type: text/markdown
12
+ License-File: LICENSE
13
+ Provides-Extra: django
14
+ Requires-Dist: django; extra == "django"
15
+ Provides-Extra: fastapi
16
+ Requires-Dist: fastapi; extra == "fastapi"
17
+ Requires-Dist: pydantic; extra == "fastapi"
18
+ Provides-Extra: dev
19
+ Requires-Dist: pytest>=7.0.0; extra == "dev"
20
+ Requires-Dist: pytest-cov>=4.0.0; extra == "dev"
21
+ Requires-Dist: mypy>=1.0.0; extra == "dev"
22
+ Dynamic: license-file
23
+
24
+ # apiformat
25
+
26
+ A lightweight, framework-agnostic Python package that enforces a single, consistent response format across all API endpoints.
27
+
28
+ ## Installation
29
+
30
+ ```bash
31
+ pip install apiformat
32
+ ```
33
+
34
+ ## Core Module (No Dependencies)
35
+
36
+ ```python
37
+ from apiformat import success, error
38
+
39
+ # Success response
40
+ response = success(
41
+ data={"id": 1, "name": "John"},
42
+ message="User created successfully"
43
+ )
44
+ # Output:
45
+ # {
46
+ # "status": "success",
47
+ # "message": "User created successfully",
48
+ # "data": {"id": 1, "name": "John"},
49
+ # "meta": {}
50
+ # }
51
+
52
+ # Error response
53
+ response = error(
54
+ message="User not found",
55
+ status_code=404
56
+ )
57
+ # Output:
58
+ # {
59
+ # "status": "error",
60
+ # "message": "User not found",
61
+ # "data": None,
62
+ # "meta": {}
63
+ # }
64
+ ```
65
+
66
+ ## Django Integration
67
+
68
+ ```python
69
+ from apiformat.integrations.django import success_response, error_response
70
+
71
+ def create_user(request):
72
+ user = User.objects.create(name="John")
73
+ return success_response(
74
+ data={"id": user.id, "name": user.name},
75
+ message="User created",
76
+ status=201
77
+ )
78
+
79
+ def get_user(request, user_id):
80
+ try:
81
+ user = User.objects.get(id=user_id)
82
+ return success_response(data={"id": user.id, "name": user.name})
83
+ except User.DoesNotExist:
84
+ return error_response(message="User not found", status=404)
85
+ ```
86
+
87
+ ## FastAPI Integration
88
+
89
+ ```python
90
+ from fastapi import FastAPI
91
+ from apiformat.integrations.fastapi import success_response, error_response
92
+
93
+ app = FastAPI()
94
+
95
+ @app.post("/users")
96
+ async def create_user(name: str):
97
+ user = User(name=name)
98
+ user.save()
99
+ return success_response(
100
+ data={"id": user.id, "name": user.name},
101
+ message="User created",
102
+ status_code=201
103
+ )
104
+
105
+ @app.get("/users/{user_id}")
106
+ async def get_user(user_id: int):
107
+ user = User.get_by_id(user_id)
108
+ if not user:
109
+ return error_response(message="User not found", status_code=404)
110
+ return success_response(data={"id": user.id, "name": user.name})
111
+ ```
112
+
113
+ ## License
114
+
115
+ MIT
@@ -0,0 +1,18 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ apiformat/__init__.py
5
+ apiformat/core.py
6
+ apiformat/exceptions.py
7
+ apiformat.egg-info/PKG-INFO
8
+ apiformat.egg-info/SOURCES.txt
9
+ apiformat.egg-info/dependency_links.txt
10
+ apiformat.egg-info/requires.txt
11
+ apiformat.egg-info/top_level.txt
12
+ apiformat/integrations/__init__.py
13
+ apiformat/integrations/django.py
14
+ apiformat/integrations/fastapi.py
15
+ tests/test_core.py
16
+ tests/test_django_integration.py
17
+ tests/test_exceptions.py
18
+ tests/test_fastapi_integration.py
@@ -0,0 +1,12 @@
1
+
2
+ [dev]
3
+ pytest>=7.0.0
4
+ pytest-cov>=4.0.0
5
+ mypy>=1.0.0
6
+
7
+ [django]
8
+ django
9
+
10
+ [fastapi]
11
+ fastapi
12
+ pydantic
@@ -0,0 +1 @@
1
+ apiformat
@@ -0,0 +1,41 @@
1
+ [build-system]
2
+ requires = ["setuptools>=42", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "apiformat"
7
+ version = "0.1.0"
8
+ description = "A lightweight, framework-agnostic Python package for standardized API responses."
9
+ readme = "README.md"
10
+ requires-python = ">=3.8"
11
+ license = {text = "MIT"}
12
+ authors = [
13
+ {name = "Core Developer"}
14
+ ]
15
+ classifiers = [
16
+ "Programming Language :: Python :: 3",
17
+ "License :: OSI Approved :: MIT License",
18
+ "Operating System :: OS Independent",
19
+ ]
20
+ dependencies = []
21
+
22
+ [project.optional-dependencies]
23
+ django = ["django"]
24
+ fastapi = ["fastapi", "pydantic"]
25
+ dev = [
26
+ "pytest>=7.0.0",
27
+ "pytest-cov>=4.0.0",
28
+ "mypy>=1.0.0"
29
+ ]
30
+
31
+ [tool.setuptools.packages.find]
32
+ include = ["apiformat*"]
33
+ exclude = ["tests*"]
34
+
35
+ [tool.pytest.ini_options]
36
+ addopts = "--cov=apiformat --cov-report=term-missing"
37
+ testpaths = ["tests"]
38
+
39
+ [tool.mypy]
40
+ files = ["apiformat", "tests"]
41
+ ignore_missing_imports = true
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,57 @@
1
+ import pytest
2
+ from apiformat.core import success, error, APIResponse
3
+
4
+ def test_success_default():
5
+ result = success()
6
+ assert result == {
7
+ "status": "success",
8
+ "message": "Success",
9
+ "data": None,
10
+ "meta": {}
11
+ }
12
+
13
+ def test_success_custom():
14
+ result = success(data=[1, 2], message="OK", meta={"page": 1})
15
+ assert result == {
16
+ "status": "success",
17
+ "message": "OK",
18
+ "data": [1, 2],
19
+ "meta": {"page": 1}
20
+ }
21
+
22
+ def test_error_default():
23
+ result = error()
24
+ assert result == {
25
+ "status": "error",
26
+ "message": "Error",
27
+ "data": None,
28
+ "meta": {}
29
+ }
30
+
31
+ def test_error_custom():
32
+ result = error(message="Not found", data={"id": 1}, meta={"code": 404})
33
+ assert result == {
34
+ "status": "error",
35
+ "message": "Not found",
36
+ "data": {"id": 1},
37
+ "meta": {"code": 404}
38
+ }
39
+
40
+ def test_apiresponse_default():
41
+ response = APIResponse(status="success")
42
+ assert response.to_dict() == {
43
+ "status": "success",
44
+ "message": "",
45
+ "data": None,
46
+ "meta": {}
47
+ }
48
+
49
+ def test_apiresponse_custom():
50
+ response = APIResponse(status="error", message="Failed", data="X", meta={"k": "v"})
51
+ print(response.to_dict())
52
+ assert response.to_dict() == {
53
+ "status": "error",
54
+ "message": "Failed",
55
+ "data": "X",
56
+ "meta": {"k": "v"}
57
+ }
@@ -0,0 +1,25 @@
1
+ from unittest.mock import patch
2
+ from apiformat.integrations.django import success_response, error_response
3
+
4
+ @patch('apiformat.integrations.django.JsonResponse')
5
+ def test_django_success_response(mock_json_response):
6
+ success_response(data={"user": "test"}, message="Saved", status=201)
7
+ print(mock_json_response.call_args)
8
+ mock_json_response.assert_called_once_with({
9
+ "status": "success",
10
+ "message": "Saved",
11
+ "data": {"user": "test"},
12
+ "meta": {}
13
+ }, status=201)
14
+
15
+
16
+ @patch('apiformat.integrations.django.JsonResponse')
17
+ def test_django_error_response(mock_json_response):
18
+ error_response(message="Invalid", status=403, data={"field": "name"})
19
+
20
+ mock_json_response.assert_called_once_with({
21
+ "status": "error",
22
+ "message": "Invalid",
23
+ "data": {"field": "name"},
24
+ "meta": {}
25
+ }, status=403)
@@ -0,0 +1,16 @@
1
+ import pytest
2
+ from apiformat.exceptions import APIException
3
+
4
+ def test_api_exception_default():
5
+ exc = APIException(message="Something went wrong")
6
+ assert exc.message == "Something went wrong"
7
+ assert exc.status_code == 400
8
+ assert exc.data is None
9
+ assert str(exc) == "Something went wrong"
10
+
11
+ def test_api_exception_custom():
12
+ exc = APIException(message="Not found", status_code=404, data={"id": 5})
13
+ assert exc.message == "Not found"
14
+ assert exc.status_code == 404
15
+ assert exc.data == {"id": 5}
16
+ assert str(exc) == "Not found"
@@ -0,0 +1,24 @@
1
+ from unittest.mock import patch
2
+ from apiformat.integrations.fastapi import success_response, error_response
3
+
4
+ @patch('apiformat.integrations.fastapi.JSONResponse')
5
+ def test_fastapi_success_response(mock_json_response):
6
+ success_response(data=[1], message="Fetched", status_code=200)
7
+
8
+ mock_json_response.assert_called_once_with({
9
+ "status": "success",
10
+ "message": "Fetched",
11
+ "data": [1],
12
+ "meta": {}
13
+ }, status_code=200)
14
+
15
+ @patch('apiformat.integrations.fastapi.JSONResponse')
16
+ def test_fastapi_error_response(mock_json_response):
17
+ error_response(message="Missing parameters", status_code=422, data={"param": "id"})
18
+
19
+ mock_json_response.assert_called_once_with({
20
+ "status": "error",
21
+ "message": "Missing parameters",
22
+ "data": {"param": "id"},
23
+ "meta": {}
24
+ }, status_code=422)