dmr-jsonapi 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.
- dmr_jsonapi/__init__.py +7 -0
- dmr_jsonapi/_json.py +35 -0
- dmr_jsonapi/_members.py +25 -0
- dmr_jsonapi/builders.py +178 -0
- dmr_jsonapi/constants.py +10 -0
- dmr_jsonapi/controller.py +137 -0
- dmr_jsonapi/errors.py +204 -0
- dmr_jsonapi/negotiation.py +46 -0
- dmr_jsonapi/objects.py +194 -0
- dmr_jsonapi/parsers.py +112 -0
- dmr_jsonapi/py.typed +0 -0
- dmr_jsonapi/renderers.py +43 -0
- dmr_jsonapi-0.1.0.dist-info/METADATA +261 -0
- dmr_jsonapi-0.1.0.dist-info/RECORD +16 -0
- dmr_jsonapi-0.1.0.dist-info/WHEEL +4 -0
- dmr_jsonapi-0.1.0.dist-info/licenses/LICENSE +20 -0
dmr_jsonapi/__init__.py
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
"""JSON:API support for ``django-modern-rest``."""
|
|
2
|
+
|
|
3
|
+
from dmr_jsonapi.constants import JSON_API_CONTENT_TYPE as JSON_API_CONTENT_TYPE
|
|
4
|
+
from dmr_jsonapi.controller import JsonApiController as JsonApiController
|
|
5
|
+
from dmr_jsonapi.errors import JsonApiError as JsonApiError
|
|
6
|
+
from dmr_jsonapi.parsers import JsonApiParser as JsonApiParser
|
|
7
|
+
from dmr_jsonapi.renderers import JsonApiRenderer as JsonApiRenderer
|
dmr_jsonapi/_json.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
from collections.abc import Callable
|
|
2
|
+
from typing import TYPE_CHECKING, Any
|
|
3
|
+
|
|
4
|
+
from dmr.internal.json import JsonModule, NativeJson
|
|
5
|
+
|
|
6
|
+
if TYPE_CHECKING:
|
|
7
|
+
from dmr.parsers import Raw
|
|
8
|
+
|
|
9
|
+
try:
|
|
10
|
+
import msgspec
|
|
11
|
+
except ImportError: # pragma: no cover
|
|
12
|
+
default_json_module: JsonModule = NativeJson
|
|
13
|
+
else:
|
|
14
|
+
|
|
15
|
+
class _MsgspecJson: # noqa: WPS431
|
|
16
|
+
"""Json module for ``dmr`` that is based on ``msgspec``."""
|
|
17
|
+
|
|
18
|
+
__slots__ = ()
|
|
19
|
+
|
|
20
|
+
@classmethod
|
|
21
|
+
def dumps(
|
|
22
|
+
cls,
|
|
23
|
+
to_serialize: Any,
|
|
24
|
+
/,
|
|
25
|
+
default: Callable[[Any], Any] | None = None,
|
|
26
|
+
) -> bytes:
|
|
27
|
+
"""Dump an object to json bytes."""
|
|
28
|
+
return msgspec.json.encode(to_serialize, enc_hook=default)
|
|
29
|
+
|
|
30
|
+
@classmethod
|
|
31
|
+
def loads(cls, to_deserialize: 'str | Raw', /) -> Any:
|
|
32
|
+
"""Load a simple object from json."""
|
|
33
|
+
return msgspec.json.decode(to_deserialize)
|
|
34
|
+
|
|
35
|
+
default_json_module = _MsgspecJson
|
dmr_jsonapi/_members.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
from collections.abc import Mapping
|
|
2
|
+
from typing import Any, TypeVar, cast
|
|
3
|
+
|
|
4
|
+
_BaseT = TypeVar('_BaseT', bound=Mapping[str, Any])
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def with_members(base: _BaseT, optional: Mapping[str, Any]) -> _BaseT:
|
|
8
|
+
"""
|
|
9
|
+
Add optional members to the *base*, but only the ones that were passed.
|
|
10
|
+
|
|
11
|
+
Returns a new object of the same ``TypedDict`` type as *base*.
|
|
12
|
+
Never use it for members that can legitimately be ``None``,
|
|
13
|
+
like ``data`` of a document, they must be a part of the *base*.
|
|
14
|
+
"""
|
|
15
|
+
return cast(
|
|
16
|
+
_BaseT,
|
|
17
|
+
{
|
|
18
|
+
**base,
|
|
19
|
+
**{
|
|
20
|
+
member_name: member
|
|
21
|
+
for member_name, member in optional.items()
|
|
22
|
+
if member is not None
|
|
23
|
+
},
|
|
24
|
+
},
|
|
25
|
+
)
|
dmr_jsonapi/builders.py
ADDED
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
"""Helpers to build JSON:API documents from your data."""
|
|
2
|
+
|
|
3
|
+
import functools
|
|
4
|
+
import math
|
|
5
|
+
from collections.abc import Iterable
|
|
6
|
+
from typing import Any
|
|
7
|
+
from uuid import UUID
|
|
8
|
+
|
|
9
|
+
from django.http import HttpRequest
|
|
10
|
+
from typing_extensions import TypeVar
|
|
11
|
+
|
|
12
|
+
from dmr_jsonapi._members import with_members
|
|
13
|
+
from dmr_jsonapi.constants import JSON_API_VERSION
|
|
14
|
+
from dmr_jsonapi.objects import (
|
|
15
|
+
Document,
|
|
16
|
+
Links,
|
|
17
|
+
Meta,
|
|
18
|
+
Relationship,
|
|
19
|
+
ResourceIdentifier,
|
|
20
|
+
ResourceObject,
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
_AttributesT = TypeVar('_AttributesT')
|
|
24
|
+
_DataT = TypeVar('_DataT')
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def resource_identifier(
|
|
28
|
+
resource_type: str,
|
|
29
|
+
resource_id: str | int | UUID,
|
|
30
|
+
*,
|
|
31
|
+
meta: Meta | None = None,
|
|
32
|
+
) -> ResourceIdentifier:
|
|
33
|
+
"""
|
|
34
|
+
Build a resource identifier.
|
|
35
|
+
|
|
36
|
+
The specification requires ids to be strings, so we convert them.
|
|
37
|
+
"""
|
|
38
|
+
identifier: ResourceIdentifier = {
|
|
39
|
+
'type': resource_type,
|
|
40
|
+
'id': str(resource_id),
|
|
41
|
+
}
|
|
42
|
+
return with_members(identifier, {'meta': meta})
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def resource_object( # noqa: WPS211
|
|
46
|
+
resource_type: str,
|
|
47
|
+
resource_id: str | int | UUID,
|
|
48
|
+
attributes: _AttributesT | None = None,
|
|
49
|
+
*,
|
|
50
|
+
relationships: dict[str, Relationship] | None = None,
|
|
51
|
+
links: Links | None = None,
|
|
52
|
+
meta: Meta | None = None,
|
|
53
|
+
) -> ResourceObject[_AttributesT]:
|
|
54
|
+
"""
|
|
55
|
+
Build a resource object.
|
|
56
|
+
|
|
57
|
+
Members that are not passed are not included.
|
|
58
|
+
"""
|
|
59
|
+
resource: ResourceObject[_AttributesT] = {
|
|
60
|
+
'type': resource_type,
|
|
61
|
+
'id': str(resource_id),
|
|
62
|
+
}
|
|
63
|
+
return with_members(
|
|
64
|
+
resource,
|
|
65
|
+
{
|
|
66
|
+
'attributes': attributes,
|
|
67
|
+
'relationships': relationships,
|
|
68
|
+
'links': links,
|
|
69
|
+
'meta': meta,
|
|
70
|
+
},
|
|
71
|
+
)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def relationship_to_one(
|
|
75
|
+
identifier: ResourceIdentifier | None,
|
|
76
|
+
*,
|
|
77
|
+
links: Links | None = None,
|
|
78
|
+
meta: Meta | None = None,
|
|
79
|
+
) -> Relationship:
|
|
80
|
+
"""Build a to-one relationship, ``None`` means that it is empty."""
|
|
81
|
+
relationship: Relationship = {'data': identifier}
|
|
82
|
+
return with_members(relationship, {'links': links, 'meta': meta})
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def relationship_to_many(
|
|
86
|
+
identifiers: Iterable[ResourceIdentifier],
|
|
87
|
+
*,
|
|
88
|
+
links: Links | None = None,
|
|
89
|
+
meta: Meta | None = None,
|
|
90
|
+
) -> Relationship:
|
|
91
|
+
"""Build a to-many relationship."""
|
|
92
|
+
relationship: Relationship = {'data': list(identifiers)}
|
|
93
|
+
return with_members(relationship, {'links': links, 'meta': meta})
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def document( # noqa: WPS211
|
|
97
|
+
data: _DataT,
|
|
98
|
+
*,
|
|
99
|
+
included: list[ResourceObject[Any]] | None = None,
|
|
100
|
+
links: Links | None = None,
|
|
101
|
+
meta: Meta | None = None,
|
|
102
|
+
jsonapi: bool = False,
|
|
103
|
+
) -> Document[_DataT]:
|
|
104
|
+
"""
|
|
105
|
+
Build a top level document.
|
|
106
|
+
|
|
107
|
+
Pass ``jsonapi=True`` to include the ``jsonapi`` member
|
|
108
|
+
with the version of the specification that we implement.
|
|
109
|
+
"""
|
|
110
|
+
top_level: Document[_DataT] = {'data': data}
|
|
111
|
+
return with_members(
|
|
112
|
+
top_level,
|
|
113
|
+
{
|
|
114
|
+
'included': included,
|
|
115
|
+
'links': links,
|
|
116
|
+
'meta': meta,
|
|
117
|
+
'jsonapi': {'version': JSON_API_VERSION} if jsonapi else None,
|
|
118
|
+
},
|
|
119
|
+
)
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def pagination_links( # noqa: WPS211
|
|
123
|
+
request: HttpRequest,
|
|
124
|
+
*,
|
|
125
|
+
number: int,
|
|
126
|
+
size: int,
|
|
127
|
+
total: int,
|
|
128
|
+
number_param: str = 'page[number]',
|
|
129
|
+
size_param: str = 'page[size]',
|
|
130
|
+
) -> Links:
|
|
131
|
+
"""
|
|
132
|
+
Build ``self``, ``first``, ``last``, ``prev``, and ``next`` links.
|
|
133
|
+
|
|
134
|
+
Works with page-based pagination, other query parameters
|
|
135
|
+
of the *request* are kept as they are.
|
|
136
|
+
|
|
137
|
+
Args:
|
|
138
|
+
request: Current request, urls are built from it.
|
|
139
|
+
number: Number of the current page, starts with ``1``.
|
|
140
|
+
size: Size of one page.
|
|
141
|
+
total: Total number of items in the collection.
|
|
142
|
+
number_param: Name of the query parameter with a page number.
|
|
143
|
+
size_param: Name of the query parameter with a page size.
|
|
144
|
+
|
|
145
|
+
"""
|
|
146
|
+
if number < 1 or size < 1 or total < 0:
|
|
147
|
+
raise ValueError(
|
|
148
|
+
'Page number and size must be positive, total must not be negative',
|
|
149
|
+
)
|
|
150
|
+
last = max(math.ceil(total / size), 1)
|
|
151
|
+
build_url = functools.partial(
|
|
152
|
+
_build_page_url,
|
|
153
|
+
request,
|
|
154
|
+
size=size,
|
|
155
|
+
number_param=number_param,
|
|
156
|
+
size_param=size_param,
|
|
157
|
+
)
|
|
158
|
+
return {
|
|
159
|
+
'self': build_url(number),
|
|
160
|
+
'first': build_url(1),
|
|
161
|
+
'last': build_url(last),
|
|
162
|
+
'prev': build_url(number - 1) if number > 1 else None,
|
|
163
|
+
'next': build_url(number + 1) if number < last else None,
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def _build_page_url(
|
|
168
|
+
request: HttpRequest,
|
|
169
|
+
number: int,
|
|
170
|
+
*,
|
|
171
|
+
size: int,
|
|
172
|
+
number_param: str,
|
|
173
|
+
size_param: str,
|
|
174
|
+
) -> str:
|
|
175
|
+
query = request.GET.copy()
|
|
176
|
+
query[number_param] = str(number)
|
|
177
|
+
query[size_param] = str(size)
|
|
178
|
+
return request.build_absolute_uri(f'{request.path}?{query.urlencode()}')
|
dmr_jsonapi/constants.py
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
from typing import Final
|
|
2
|
+
|
|
3
|
+
#: Media type of all JSON:API documents.
|
|
4
|
+
JSON_API_CONTENT_TYPE: Final = 'application/vnd.api+json'
|
|
5
|
+
|
|
6
|
+
#: The version of the JSON:API specification that we follow.
|
|
7
|
+
JSON_API_VERSION: Final = '1.1'
|
|
8
|
+
|
|
9
|
+
#: Media type parameters that are allowed by the specification.
|
|
10
|
+
JSON_API_MEDIA_PARAMS: Final = frozenset(('ext', 'profile'))
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
from collections.abc import Mapping
|
|
2
|
+
from http import HTTPStatus
|
|
3
|
+
from typing import Any, Final
|
|
4
|
+
|
|
5
|
+
from django.http import HttpRequest
|
|
6
|
+
from django.http.response import HttpResponse, HttpResponseBase
|
|
7
|
+
from dmr import Controller
|
|
8
|
+
from dmr.cookies import NewCookie
|
|
9
|
+
from dmr.errors import ErrorType
|
|
10
|
+
from dmr.exceptions import NotAcceptableError
|
|
11
|
+
from dmr.renderers import Renderer
|
|
12
|
+
from dmr.serializer import BaseSerializer
|
|
13
|
+
from typing_extensions import TypeVar, override
|
|
14
|
+
|
|
15
|
+
from dmr_jsonapi.errors import format_error, with_status
|
|
16
|
+
from dmr_jsonapi.negotiation import is_accept_unsatisfiable
|
|
17
|
+
from dmr_jsonapi.objects import ErrorDocument
|
|
18
|
+
from dmr_jsonapi.parsers import JsonApiParser
|
|
19
|
+
from dmr_jsonapi.renderers import JsonApiRenderer
|
|
20
|
+
|
|
21
|
+
_SerializerT = TypeVar('_SerializerT', bound=BaseSerializer)
|
|
22
|
+
|
|
23
|
+
_NOT_ACCEPTABLE_MSG: Final = (
|
|
24
|
+
'All JSON:API media types in `Accept` have parameters'
|
|
25
|
+
' that are not supported'
|
|
26
|
+
)
|
|
27
|
+
_NOT_ALLOWED_MSG: Final = 'Method {method} is not allowed, allowed: {allowed}'
|
|
28
|
+
|
|
29
|
+
# Used for responses that are built before the negotiation happens:
|
|
30
|
+
_FALLBACK_RENDERER: Final = JsonApiRenderer()
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class JsonApiController(Controller[_SerializerT]):
|
|
34
|
+
"""
|
|
35
|
+
Base controller for JSON:API endpoints.
|
|
36
|
+
|
|
37
|
+
What it does:
|
|
38
|
+
|
|
39
|
+
- Parses and renders ``application/vnd.api+json``
|
|
40
|
+
- Returns all errors, including ones that ``django-modern-rest`` raises
|
|
41
|
+
by itself, as JSON:API error documents
|
|
42
|
+
- Sets ``status`` of errors to the HTTP status code of a response
|
|
43
|
+
- Responds with ``406`` when ``Accept`` can't be satisfied
|
|
44
|
+
|
|
45
|
+
Use it like any other reusable controller:
|
|
46
|
+
|
|
47
|
+
.. code:: python
|
|
48
|
+
|
|
49
|
+
>>> from dmr.plugins.pydantic import PydanticSerializer
|
|
50
|
+
>>> from dmr_jsonapi import JsonApiController
|
|
51
|
+
|
|
52
|
+
>>> class UserController(JsonApiController[PydanticSerializer]):
|
|
53
|
+
... pass
|
|
54
|
+
|
|
55
|
+
"""
|
|
56
|
+
|
|
57
|
+
parsers = (JsonApiParser(),)
|
|
58
|
+
renderers = (JsonApiRenderer(),)
|
|
59
|
+
error_model = ErrorDocument
|
|
60
|
+
|
|
61
|
+
@override
|
|
62
|
+
def dispatch(
|
|
63
|
+
self,
|
|
64
|
+
request: HttpRequest,
|
|
65
|
+
*args: Any,
|
|
66
|
+
**kwargs: Any,
|
|
67
|
+
) -> HttpResponseBase:
|
|
68
|
+
"""Check ``Accept`` header the way JSON:API wants it."""
|
|
69
|
+
if is_accept_unsatisfiable(request.META.get('HTTP_ACCEPT')):
|
|
70
|
+
response = self.to_error(
|
|
71
|
+
self.format_error(
|
|
72
|
+
NotAcceptableError(_NOT_ACCEPTABLE_MSG),
|
|
73
|
+
),
|
|
74
|
+
status_code=HTTPStatus.NOT_ACCEPTABLE,
|
|
75
|
+
# Negotiation did not happen, so we choose the renderer:
|
|
76
|
+
renderer=_FALLBACK_RENDERER,
|
|
77
|
+
)
|
|
78
|
+
return _respond(response, is_async=self.is_async)
|
|
79
|
+
return super().dispatch(request, *args, **kwargs)
|
|
80
|
+
|
|
81
|
+
@override
|
|
82
|
+
def format_error(
|
|
83
|
+
self,
|
|
84
|
+
error: str | Exception,
|
|
85
|
+
*,
|
|
86
|
+
loc: str | list[str | int] | None = None,
|
|
87
|
+
error_type: str | ErrorType | None = None,
|
|
88
|
+
) -> ErrorDocument:
|
|
89
|
+
"""Convert an error to a JSON:API error document."""
|
|
90
|
+
return format_error(error, loc=loc, error_type=error_type)
|
|
91
|
+
|
|
92
|
+
@override
|
|
93
|
+
def handle_method_not_allowed(self, method: str) -> HttpResponse:
|
|
94
|
+
"""Return ``405`` as a JSON:API error document."""
|
|
95
|
+
allowed_methods = sorted(self.api_endpoints)
|
|
96
|
+
response = self.to_error(
|
|
97
|
+
self.format_error(
|
|
98
|
+
_NOT_ALLOWED_MSG.format(
|
|
99
|
+
method=repr(method),
|
|
100
|
+
allowed=repr(allowed_methods),
|
|
101
|
+
),
|
|
102
|
+
error_type=ErrorType.not_allowed,
|
|
103
|
+
),
|
|
104
|
+
status_code=HTTPStatus.METHOD_NOT_ALLOWED,
|
|
105
|
+
headers={'Allow': ', '.join(allowed_methods)},
|
|
106
|
+
renderer=_FALLBACK_RENDERER,
|
|
107
|
+
)
|
|
108
|
+
return _respond(response, is_async=self.is_async)
|
|
109
|
+
|
|
110
|
+
@override
|
|
111
|
+
def to_error(
|
|
112
|
+
self,
|
|
113
|
+
raw_data: Any,
|
|
114
|
+
*,
|
|
115
|
+
status_code: HTTPStatus,
|
|
116
|
+
headers: Mapping[str, str] | None = None,
|
|
117
|
+
cookies: Mapping[str, NewCookie] | None = None,
|
|
118
|
+
renderer: Renderer | None = None,
|
|
119
|
+
) -> HttpResponse:
|
|
120
|
+
"""Make sure that ``status`` of errors matches the response."""
|
|
121
|
+
return super().to_error(
|
|
122
|
+
with_status(raw_data, status_code),
|
|
123
|
+
status_code=status_code,
|
|
124
|
+
headers=headers,
|
|
125
|
+
cookies=cookies,
|
|
126
|
+
renderer=renderer,
|
|
127
|
+
)
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
async def _awaitable(response: HttpResponse) -> HttpResponse:
|
|
131
|
+
return response
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def _respond(response: HttpResponse, *, is_async: bool | None) -> HttpResponse:
|
|
135
|
+
# Async controllers must return awaitable responses from `dispatch`.
|
|
136
|
+
# Type annotations of `dispatch` don't know about it, same as in `dmr`.
|
|
137
|
+
return _awaitable(response) if is_async else response # type: ignore[return-value]
|
dmr_jsonapi/errors.py
ADDED
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
"""Errors in JSON:API format, see https://jsonapi.org/format/#errors."""
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
from collections.abc import Mapping, Sequence
|
|
5
|
+
from http import HTTPStatus
|
|
6
|
+
from typing import Any, Final, Literal, TypeGuard
|
|
7
|
+
|
|
8
|
+
from dmr.cookies import NewCookie
|
|
9
|
+
from dmr.errors import ErrorDetail, ErrorType
|
|
10
|
+
from dmr.errors import format_error as dmr_format_error
|
|
11
|
+
from dmr.response import APIError
|
|
12
|
+
|
|
13
|
+
from dmr_jsonapi._members import with_members
|
|
14
|
+
from dmr_jsonapi.objects import (
|
|
15
|
+
ErrorDocument,
|
|
16
|
+
ErrorLinks,
|
|
17
|
+
ErrorObject,
|
|
18
|
+
ErrorSource,
|
|
19
|
+
Meta,
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
# `msgspec` does not provide a location, but it adds it to the message:
|
|
23
|
+
# Expected `str`, got `int` - at `$.parsed_body.data.attributes[0].name`
|
|
24
|
+
_MSGSPEC_MESSAGE: Final = re.compile(r'^(?P<msg>.*) - at `\$(?P<path>.*)`$')
|
|
25
|
+
_PATH_PART: Final = re.compile(r'\.(?P<key>[^.\[\]]+)|\[(?P<index>\d+)\]')
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def error_object( # noqa: WPS211
|
|
29
|
+
detail: str | None = None,
|
|
30
|
+
*,
|
|
31
|
+
status_code: HTTPStatus | None = None,
|
|
32
|
+
code: str | None = None,
|
|
33
|
+
title: str | None = None,
|
|
34
|
+
error_id: str | None = None,
|
|
35
|
+
links: ErrorLinks | None = None,
|
|
36
|
+
source: ErrorSource | None = None,
|
|
37
|
+
meta: Meta | None = None,
|
|
38
|
+
) -> ErrorObject:
|
|
39
|
+
"""
|
|
40
|
+
Build a single error object.
|
|
41
|
+
|
|
42
|
+
Only the passed members are included.
|
|
43
|
+
``status`` is a string in JSON:API, we convert *status_code* for you.
|
|
44
|
+
"""
|
|
45
|
+
error: ErrorObject = {}
|
|
46
|
+
return with_members(
|
|
47
|
+
error,
|
|
48
|
+
{
|
|
49
|
+
'id': error_id,
|
|
50
|
+
'links': links,
|
|
51
|
+
'status': None if status_code is None else str(status_code.value),
|
|
52
|
+
'code': code,
|
|
53
|
+
'title': title,
|
|
54
|
+
'detail': detail,
|
|
55
|
+
'source': source,
|
|
56
|
+
'meta': meta,
|
|
57
|
+
},
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def with_status(raw_data: Any, status_code: HTTPStatus) -> Any:
|
|
62
|
+
"""
|
|
63
|
+
Fill the missing ``status`` of errors in a document.
|
|
64
|
+
|
|
65
|
+
It is how we make sure that ``status`` always matches the status code
|
|
66
|
+
of the response. Existing ``status`` values are kept as they are.
|
|
67
|
+
Anything that does not look like an error document is returned as is.
|
|
68
|
+
"""
|
|
69
|
+
if not _is_error_document(raw_data):
|
|
70
|
+
return raw_data
|
|
71
|
+
status = str(status_code.value)
|
|
72
|
+
return {
|
|
73
|
+
**raw_data,
|
|
74
|
+
'errors': [
|
|
75
|
+
error if 'status' in error else {'status': status, **error}
|
|
76
|
+
for error in raw_data['errors']
|
|
77
|
+
],
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _is_error_document(raw_data: Any) -> TypeGuard[ErrorDocument]:
|
|
82
|
+
return isinstance(raw_data, dict) and 'errors' in raw_data
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
class JsonApiError(APIError[ErrorDocument]):
|
|
86
|
+
"""
|
|
87
|
+
Raise it anywhere in your API to return errors in JSON:API format.
|
|
88
|
+
|
|
89
|
+
It is a subclass of :class:`dmr.response.APIError`.
|
|
90
|
+
Build errors with :func:`error_object`:
|
|
91
|
+
|
|
92
|
+
.. code:: python
|
|
93
|
+
|
|
94
|
+
>>> from http import HTTPStatus
|
|
95
|
+
>>> from dmr_jsonapi.errors import JsonApiError, error_object
|
|
96
|
+
|
|
97
|
+
>>> raise JsonApiError(
|
|
98
|
+
... error_object('User does not exist', code='no_user'),
|
|
99
|
+
... status_code=HTTPStatus.NOT_FOUND,
|
|
100
|
+
... )
|
|
101
|
+
Traceback (most recent call last):
|
|
102
|
+
...
|
|
103
|
+
dmr_jsonapi.errors.JsonApiError
|
|
104
|
+
|
|
105
|
+
Several errors can be returned at once, ``status`` of each of them
|
|
106
|
+
is set to *status_code* when it is missing.
|
|
107
|
+
"""
|
|
108
|
+
|
|
109
|
+
def __init__(
|
|
110
|
+
self,
|
|
111
|
+
*errors: ErrorObject,
|
|
112
|
+
status_code: HTTPStatus,
|
|
113
|
+
headers: Mapping[str, str] | None = None,
|
|
114
|
+
cookies: Mapping[str, NewCookie] | None = None,
|
|
115
|
+
) -> None:
|
|
116
|
+
"""Create an error from error objects, at least one is required."""
|
|
117
|
+
if not errors:
|
|
118
|
+
raise ValueError('At least one error object is required')
|
|
119
|
+
super().__init__(
|
|
120
|
+
with_status({'errors': list(errors)}, status_code),
|
|
121
|
+
status_code=status_code,
|
|
122
|
+
headers=headers,
|
|
123
|
+
cookies=cookies,
|
|
124
|
+
)
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def source_from_loc(
|
|
128
|
+
loc: Sequence[str | int],
|
|
129
|
+
) -> ErrorSource | Literal[False]:
|
|
130
|
+
"""
|
|
131
|
+
Convert ``dmr`` error location to the error source.
|
|
132
|
+
|
|
133
|
+
Returns ``False`` when location can't be represented as a source.
|
|
134
|
+
"""
|
|
135
|
+
if not loc:
|
|
136
|
+
return False
|
|
137
|
+
component, *path = loc
|
|
138
|
+
if component == 'parsed_body':
|
|
139
|
+
return {'pointer': _to_pointer(path)}
|
|
140
|
+
if component == 'parsed_query' and path:
|
|
141
|
+
return {'parameter': str(path[0])}
|
|
142
|
+
if component == 'parsed_headers' and path:
|
|
143
|
+
return {'header': str(path[0])}
|
|
144
|
+
return False
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def format_error(
|
|
148
|
+
error: str | Exception,
|
|
149
|
+
*,
|
|
150
|
+
loc: str | list[str | int] | None = None,
|
|
151
|
+
error_type: str | ErrorType | None = None,
|
|
152
|
+
) -> ErrorDocument:
|
|
153
|
+
"""
|
|
154
|
+
Convert any error to a JSON:API error document.
|
|
155
|
+
|
|
156
|
+
It has the same signature as :func:`dmr.errors.format_error`,
|
|
157
|
+
and it handles the same set of errors.
|
|
158
|
+
"""
|
|
159
|
+
status_code: HTTPStatus | None = getattr(error, 'status_code', None)
|
|
160
|
+
default = dmr_format_error(error, loc=loc, error_type=error_type)
|
|
161
|
+
return {
|
|
162
|
+
'errors': [
|
|
163
|
+
_convert_detail(detail, status_code) for detail in default['detail']
|
|
164
|
+
],
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def _convert_detail(
|
|
169
|
+
detail: ErrorDetail,
|
|
170
|
+
status_code: HTTPStatus | None,
|
|
171
|
+
) -> ErrorObject:
|
|
172
|
+
message = detail['msg']
|
|
173
|
+
loc: list[str | int] | None = detail.get('loc')
|
|
174
|
+
if loc is None:
|
|
175
|
+
match = _MSGSPEC_MESSAGE.match(message)
|
|
176
|
+
if match:
|
|
177
|
+
message = match.group('msg')
|
|
178
|
+
loc = _parse_msgspec_path(match.group('path'))
|
|
179
|
+
|
|
180
|
+
source = source_from_loc(loc) if loc else False
|
|
181
|
+
return error_object(
|
|
182
|
+
message,
|
|
183
|
+
status_code=status_code,
|
|
184
|
+
code=detail.get('type'),
|
|
185
|
+
source=source or None,
|
|
186
|
+
# We don't want to lose information about locations
|
|
187
|
+
# that cannot be represented as a source:
|
|
188
|
+
meta={'loc': loc} if loc and not source else None,
|
|
189
|
+
)
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def _parse_msgspec_path(path: str) -> list[str | int]:
|
|
193
|
+
return [
|
|
194
|
+
int(index) if index else key for key, index in _PATH_PART.findall(path)
|
|
195
|
+
]
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def _to_pointer(path: Sequence[str | int]) -> str:
|
|
199
|
+
# See RFC 6901, `~` must be escaped first:
|
|
200
|
+
return ''.join(f'/{_escape_pointer_part(part)}' for part in path)
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def _escape_pointer_part(part: str | int) -> str:
|
|
204
|
+
return str(part).replace('~', '~0').replace('/', '~1')
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import re
|
|
2
|
+
from collections.abc import Set
|
|
3
|
+
from itertools import takewhile
|
|
4
|
+
from typing import Final
|
|
5
|
+
|
|
6
|
+
from dmr_jsonapi.constants import JSON_API_CONTENT_TYPE, JSON_API_MEDIA_PARAMS
|
|
7
|
+
|
|
8
|
+
# Splits by a separator that is not inside of a quoted string:
|
|
9
|
+
_COMMA: Final = re.compile(r',(?=(?:[^"]*"[^"]*")*[^"]*$)')
|
|
10
|
+
_SEMICOLON: Final = re.compile(r';(?=(?:[^"]*"[^"]*")*[^"]*$)')
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def is_accept_unsatisfiable(
|
|
14
|
+
accept: str | None,
|
|
15
|
+
allowed_params: Set[str] = JSON_API_MEDIA_PARAMS,
|
|
16
|
+
) -> bool:
|
|
17
|
+
"""
|
|
18
|
+
Tell whether ``Accept`` header can't be satisfied by a JSON:API server.
|
|
19
|
+
|
|
20
|
+
The specification says that if ``Accept`` has the JSON:API media type
|
|
21
|
+
and all of its instances are modified with media type parameters
|
|
22
|
+
(other than ``ext`` and ``profile``), a server must return ``406``.
|
|
23
|
+
|
|
24
|
+
Other media types and the headers that don't mention JSON:API at all
|
|
25
|
+
are not our business, so they are never reported here.
|
|
26
|
+
"""
|
|
27
|
+
if accept is None or ';' not in accept:
|
|
28
|
+
return False # fast path, there are no parameters
|
|
29
|
+
|
|
30
|
+
instances = 0
|
|
31
|
+
for media_range in _COMMA.split(accept.lower()):
|
|
32
|
+
media_type, *parts = (
|
|
33
|
+
part.strip() for part in _SEMICOLON.split(media_range)
|
|
34
|
+
)
|
|
35
|
+
if media_type != JSON_API_CONTENT_TYPE:
|
|
36
|
+
continue
|
|
37
|
+
instances += 1
|
|
38
|
+
if _param_names(parts) <= allowed_params:
|
|
39
|
+
return False
|
|
40
|
+
return instances > 0
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _param_names(parts: list[str]) -> set[str]:
|
|
44
|
+
names = (part.partition('=')[0].strip() for part in parts)
|
|
45
|
+
# Parameters after `q` are not media type parameters:
|
|
46
|
+
return set(takewhile(lambda name: name != 'q', names))
|
dmr_jsonapi/objects.py
ADDED
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Typed models for the objects that JSON:API defines.
|
|
3
|
+
|
|
4
|
+
They are all :class:`typing.TypedDict` types, so they work with any
|
|
5
|
+
serializer that ``django-modern-rest`` supports.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from typing import Any, Generic, NotRequired, TypeAlias
|
|
9
|
+
|
|
10
|
+
from typing_extensions import TypedDict, TypeVar
|
|
11
|
+
|
|
12
|
+
#: Free-form non-standard meta information.
|
|
13
|
+
Meta: TypeAlias = dict[str, Any]
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class LinkObject(TypedDict):
|
|
17
|
+
"""A link that carries some extra information, not just an url."""
|
|
18
|
+
|
|
19
|
+
href: str
|
|
20
|
+
rel: NotRequired[str]
|
|
21
|
+
describedby: NotRequired[str | dict[str, Any]]
|
|
22
|
+
title: NotRequired[str]
|
|
23
|
+
type: NotRequired[str]
|
|
24
|
+
hreflang: NotRequired[str | list[str]]
|
|
25
|
+
meta: NotRequired[Meta]
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
#: A link is either an url string or a link object.
|
|
29
|
+
Link: TypeAlias = str | LinkObject
|
|
30
|
+
|
|
31
|
+
#: Named links, ``None`` is used for the links that are not available.
|
|
32
|
+
Links: TypeAlias = dict[str, Link | None]
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class JsonApiObject(TypedDict):
|
|
36
|
+
"""Top level ``jsonapi`` object that describes server's implementation."""
|
|
37
|
+
|
|
38
|
+
version: NotRequired[str]
|
|
39
|
+
ext: NotRequired[list[str]]
|
|
40
|
+
profile: NotRequired[list[str]]
|
|
41
|
+
meta: NotRequired[Meta]
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class ResourceIdentifier(TypedDict):
|
|
45
|
+
"""Identifies a resource without describing it."""
|
|
46
|
+
|
|
47
|
+
type: str
|
|
48
|
+
id: str
|
|
49
|
+
lid: NotRequired[str]
|
|
50
|
+
meta: NotRequired[Meta]
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class Relationship(TypedDict):
|
|
54
|
+
"""
|
|
55
|
+
Relationship of a resource.
|
|
56
|
+
|
|
57
|
+
Specification requires at least one of ``links``, ``data``, or ``meta``.
|
|
58
|
+
``data`` is a single identifier for to-one relationships, a list of them
|
|
59
|
+
for to-many relationships, and ``None`` for empty to-one relationships.
|
|
60
|
+
"""
|
|
61
|
+
|
|
62
|
+
links: NotRequired[Links]
|
|
63
|
+
data: NotRequired[ResourceIdentifier | list[ResourceIdentifier] | None]
|
|
64
|
+
meta: NotRequired[Meta]
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
_AttributesT = TypeVar('_AttributesT', default=dict[str, Any])
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class ResourceObject(TypedDict, Generic[_AttributesT]):
|
|
71
|
+
"""
|
|
72
|
+
A resource, which is the main thing that JSON:API documents carry.
|
|
73
|
+
|
|
74
|
+
Define your own ``TypedDict`` for the attributes
|
|
75
|
+
and pass it as a type argument.
|
|
76
|
+
"""
|
|
77
|
+
|
|
78
|
+
type: str
|
|
79
|
+
id: str
|
|
80
|
+
attributes: NotRequired[_AttributesT]
|
|
81
|
+
relationships: NotRequired[dict[str, Relationship]]
|
|
82
|
+
links: NotRequired[Links]
|
|
83
|
+
meta: NotRequired[Meta]
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
class NewResourceObject(TypedDict, Generic[_AttributesT]):
|
|
87
|
+
"""
|
|
88
|
+
A resource that a client wants to create.
|
|
89
|
+
|
|
90
|
+
Unlike :class:`ResourceObject`, ``id`` is optional.
|
|
91
|
+
Servers can accept client-generated ids or generate their own.
|
|
92
|
+
"""
|
|
93
|
+
|
|
94
|
+
type: str
|
|
95
|
+
id: NotRequired[str]
|
|
96
|
+
lid: NotRequired[str]
|
|
97
|
+
attributes: NotRequired[_AttributesT]
|
|
98
|
+
relationships: NotRequired[dict[str, Relationship]]
|
|
99
|
+
meta: NotRequired[Meta]
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
#: Resources that are related to the primary data, but are not a part of it.
|
|
103
|
+
IncludedResources: TypeAlias = list[ResourceObject[Any]]
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
class DocumentEnvelope(TypedDict):
|
|
107
|
+
"""
|
|
108
|
+
Members that top level documents have in common, except for ``data``.
|
|
109
|
+
|
|
110
|
+
The best way to describe your documents is to subclass this type
|
|
111
|
+
and to add ``data`` with a concrete type:
|
|
112
|
+
|
|
113
|
+
.. code:: python
|
|
114
|
+
|
|
115
|
+
>>> from dmr_jsonapi.objects import DocumentEnvelope, ResourceObject
|
|
116
|
+
|
|
117
|
+
>>> class UserAttributes(TypedDict):
|
|
118
|
+
... name: str
|
|
119
|
+
|
|
120
|
+
>>> class UserDocument(DocumentEnvelope):
|
|
121
|
+
... data: ResourceObject[UserAttributes]
|
|
122
|
+
|
|
123
|
+
Why? Schema generators name all specializations of a generic
|
|
124
|
+
``TypedDict`` the same way. So, ``Document[A]`` and ``Document[B]``
|
|
125
|
+
would clash in your OpenAPI schema when used as top level types.
|
|
126
|
+
And python can't substitute type arguments when you subclass
|
|
127
|
+
a specialized generic ``TypedDict``, validation would silently be lost.
|
|
128
|
+
"""
|
|
129
|
+
|
|
130
|
+
included: NotRequired[IncludedResources]
|
|
131
|
+
links: NotRequired[Links]
|
|
132
|
+
meta: NotRequired[Meta]
|
|
133
|
+
jsonapi: NotRequired[JsonApiObject]
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
_DataT = TypeVar('_DataT')
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
class Document(DocumentEnvelope, Generic[_DataT]):
|
|
140
|
+
"""
|
|
141
|
+
Top level object of a successful response or of a request.
|
|
142
|
+
|
|
143
|
+
``data`` is a resource, a list of resources,
|
|
144
|
+
a resource identifier (or a list of them), or ``None``.
|
|
145
|
+
|
|
146
|
+
It is a handy type for annotating things that build documents,
|
|
147
|
+
like :func:`dmr_jsonapi.builders.document`.
|
|
148
|
+
It is compatible with the documents that subclass
|
|
149
|
+
:class:`DocumentEnvelope`. But prefer to use your own documents
|
|
150
|
+
as response and request models, see the note there.
|
|
151
|
+
"""
|
|
152
|
+
|
|
153
|
+
data: _DataT
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
class ErrorSource(TypedDict):
|
|
157
|
+
"""
|
|
158
|
+
Points to the place that caused the error.
|
|
159
|
+
|
|
160
|
+
Specification only allows one of these to be used at once.
|
|
161
|
+
"""
|
|
162
|
+
|
|
163
|
+
pointer: NotRequired[str]
|
|
164
|
+
parameter: NotRequired[str]
|
|
165
|
+
header: NotRequired[str]
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
class ErrorLinks(TypedDict):
|
|
169
|
+
"""Links of an error object."""
|
|
170
|
+
|
|
171
|
+
about: NotRequired[Link]
|
|
172
|
+
type: NotRequired[Link]
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
class ErrorObject(TypedDict):
|
|
176
|
+
"""A single error, see https://jsonapi.org/format/#error-objects."""
|
|
177
|
+
|
|
178
|
+
id: NotRequired[str]
|
|
179
|
+
links: NotRequired[ErrorLinks]
|
|
180
|
+
status: NotRequired[str]
|
|
181
|
+
code: NotRequired[str]
|
|
182
|
+
title: NotRequired[str]
|
|
183
|
+
detail: NotRequired[str]
|
|
184
|
+
source: NotRequired[ErrorSource]
|
|
185
|
+
meta: NotRequired[Meta]
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
class ErrorDocument(TypedDict):
|
|
189
|
+
"""Top level object of an unsuccessful response."""
|
|
190
|
+
|
|
191
|
+
errors: list[ErrorObject]
|
|
192
|
+
links: NotRequired[Links]
|
|
193
|
+
meta: NotRequired[Meta]
|
|
194
|
+
jsonapi: NotRequired[JsonApiObject]
|
dmr_jsonapi/parsers.py
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
from collections.abc import Mapping, Set
|
|
2
|
+
from http import HTTPStatus
|
|
3
|
+
from typing import TYPE_CHECKING, Any, Final
|
|
4
|
+
|
|
5
|
+
from django.http import HttpRequest
|
|
6
|
+
from dmr.internal.json import JsonModule
|
|
7
|
+
from dmr.metadata import EndpointMetadata, ResponseSpec
|
|
8
|
+
from dmr.parsers import DeserializeFunc, JsonParser, Raw
|
|
9
|
+
from typing_extensions import TypeForm, override
|
|
10
|
+
|
|
11
|
+
from dmr_jsonapi._json import default_json_module
|
|
12
|
+
from dmr_jsonapi.constants import (
|
|
13
|
+
JSON_API_CONTENT_TYPE,
|
|
14
|
+
JSON_API_MEDIA_PARAMS,
|
|
15
|
+
)
|
|
16
|
+
from dmr_jsonapi.errors import JsonApiError, error_object
|
|
17
|
+
|
|
18
|
+
if TYPE_CHECKING:
|
|
19
|
+
from dmr.controller import Controller
|
|
20
|
+
from dmr.serializer import BaseSerializer
|
|
21
|
+
|
|
22
|
+
_UNSUPPORTED_PARAMS_MSG: Final = (
|
|
23
|
+
'Media type parameters {params} are not supported for {content_type},'
|
|
24
|
+
' only {allowed} can be used'
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class JsonApiParser(JsonParser):
|
|
29
|
+
"""
|
|
30
|
+
Parses ``application/vnd.api+json`` request bodies.
|
|
31
|
+
|
|
32
|
+
The specification requires servers to respond with ``415``
|
|
33
|
+
when a request has a ``Content-Type`` with media type parameters
|
|
34
|
+
other than ``ext`` and ``profile``. We do that.
|
|
35
|
+
You can change allowed parameters with *allowed_params*.
|
|
36
|
+
"""
|
|
37
|
+
|
|
38
|
+
__slots__ = ('_allowed_params',)
|
|
39
|
+
|
|
40
|
+
def __init__(
|
|
41
|
+
self,
|
|
42
|
+
content_type: str = JSON_API_CONTENT_TYPE,
|
|
43
|
+
*,
|
|
44
|
+
json_module: JsonModule = default_json_module,
|
|
45
|
+
allowed_params: Set[str] = JSON_API_MEDIA_PARAMS,
|
|
46
|
+
) -> None:
|
|
47
|
+
"""Init the parser with the JSON:API media type by default."""
|
|
48
|
+
super().__init__(content_type, json_module=json_module)
|
|
49
|
+
self._allowed_params = allowed_params
|
|
50
|
+
|
|
51
|
+
@override
|
|
52
|
+
def parse(
|
|
53
|
+
self,
|
|
54
|
+
to_deserialize: Raw,
|
|
55
|
+
deserializer_hook: DeserializeFunc | None = None,
|
|
56
|
+
*,
|
|
57
|
+
request: HttpRequest,
|
|
58
|
+
model: TypeForm[Any],
|
|
59
|
+
) -> Any:
|
|
60
|
+
"""
|
|
61
|
+
Decode a JSON:API body.
|
|
62
|
+
|
|
63
|
+
Raises:
|
|
64
|
+
JsonApiError: With ``415`` status code
|
|
65
|
+
when media type has unsupported parameters.
|
|
66
|
+
DataParsingError: If error decoding *to_deserialize*.
|
|
67
|
+
|
|
68
|
+
"""
|
|
69
|
+
# `django` strips parameters from `content_type`, but keeps them here:
|
|
70
|
+
unsupported = sorted(
|
|
71
|
+
set(getattr(request, 'content_params', None) or ())
|
|
72
|
+
- self._allowed_params,
|
|
73
|
+
)
|
|
74
|
+
if unsupported:
|
|
75
|
+
raise JsonApiError(
|
|
76
|
+
error_object(
|
|
77
|
+
_UNSUPPORTED_PARAMS_MSG.format(
|
|
78
|
+
params=unsupported,
|
|
79
|
+
content_type=self.content_type,
|
|
80
|
+
allowed=sorted(self._allowed_params),
|
|
81
|
+
),
|
|
82
|
+
code='unsupported_media_type',
|
|
83
|
+
source={'header': 'Content-Type'},
|
|
84
|
+
),
|
|
85
|
+
status_code=HTTPStatus.UNSUPPORTED_MEDIA_TYPE,
|
|
86
|
+
)
|
|
87
|
+
return super().parse(
|
|
88
|
+
to_deserialize,
|
|
89
|
+
deserializer_hook,
|
|
90
|
+
request=request,
|
|
91
|
+
model=model,
|
|
92
|
+
)
|
|
93
|
+
|
|
94
|
+
@override
|
|
95
|
+
def provide_response_specs(
|
|
96
|
+
self,
|
|
97
|
+
metadata: EndpointMetadata,
|
|
98
|
+
controller_cls: type['Controller[BaseSerializer]'],
|
|
99
|
+
existing_responses: Mapping[HTTPStatus, ResponseSpec],
|
|
100
|
+
) -> list[ResponseSpec]:
|
|
101
|
+
"""Describe the ``415`` error that this parser can produce."""
|
|
102
|
+
return self._add_new_response(
|
|
103
|
+
ResponseSpec(
|
|
104
|
+
return_type=controller_cls.error_model,
|
|
105
|
+
status_code=HTTPStatus.UNSUPPORTED_MEDIA_TYPE,
|
|
106
|
+
description=(
|
|
107
|
+
'Raised when `Content-Type` has unsupported'
|
|
108
|
+
' media type parameters'
|
|
109
|
+
),
|
|
110
|
+
),
|
|
111
|
+
existing_responses,
|
|
112
|
+
)
|
dmr_jsonapi/py.typed
ADDED
|
File without changes
|
dmr_jsonapi/renderers.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
from dmr.internal.json import JsonModule
|
|
2
|
+
from dmr.parsers import JsonParser
|
|
3
|
+
from dmr.renderers import JsonRenderer
|
|
4
|
+
from typing_extensions import override
|
|
5
|
+
|
|
6
|
+
from dmr_jsonapi._json import default_json_module
|
|
7
|
+
from dmr_jsonapi.constants import JSON_API_CONTENT_TYPE
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class JsonApiRenderer(JsonRenderer):
|
|
11
|
+
"""
|
|
12
|
+
Renders responses as ``application/vnd.api+json``.
|
|
13
|
+
|
|
14
|
+
Uses ``msgspec`` when it is installed, the same way ``django-modern-rest``
|
|
15
|
+
does it by default. Alternative json backends can be passed
|
|
16
|
+
with *json_module*, see ``django-modern-rest`` docs.
|
|
17
|
+
|
|
18
|
+
It only sets the right media type. Documents themselves are built
|
|
19
|
+
by your code, see :mod:`dmr_jsonapi.objects`
|
|
20
|
+
and :mod:`dmr_jsonapi.builders`.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
__slots__ = ()
|
|
24
|
+
|
|
25
|
+
def __init__(
|
|
26
|
+
self,
|
|
27
|
+
content_type: str = JSON_API_CONTENT_TYPE,
|
|
28
|
+
*,
|
|
29
|
+
json_module: JsonModule = default_json_module,
|
|
30
|
+
) -> None:
|
|
31
|
+
"""Init the renderer with the JSON:API media type by default."""
|
|
32
|
+
super().__init__(content_type, json_module=json_module)
|
|
33
|
+
|
|
34
|
+
@property
|
|
35
|
+
@override
|
|
36
|
+
def validation_parser(self) -> JsonParser:
|
|
37
|
+
"""
|
|
38
|
+
Plain json parser can parse the result.
|
|
39
|
+
|
|
40
|
+
We don't want any media type checks here,
|
|
41
|
+
because there is no incoming request.
|
|
42
|
+
"""
|
|
43
|
+
return JsonParser(self.content_type, json_module=self._json_module)
|
|
@@ -0,0 +1,261 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: dmr-jsonapi
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: JSON:API support for django-modern-rest
|
|
5
|
+
Project-URL: Documentation, https://github.com/blfpd/dmr-jsonapi#readme
|
|
6
|
+
Project-URL: Changelog, https://github.com/blfpd/dmr-jsonapi/blob/main/CHANGELOG.md
|
|
7
|
+
Project-URL: GitHub, https://github.com/blfpd/dmr-jsonapi
|
|
8
|
+
Author-email: Baptiste Darthenay <baptiste@ikso.net>
|
|
9
|
+
License-Expression: MIT
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Keywords: API,REST,django,django-api,django-modern-rest,dmr,json:api,jsonapi,wemake-python-package
|
|
12
|
+
Classifier: Development Status :: 3 - Alpha
|
|
13
|
+
Classifier: Environment :: Web Environment
|
|
14
|
+
Classifier: Framework :: AsyncIO
|
|
15
|
+
Classifier: Framework :: Django
|
|
16
|
+
Classifier: Framework :: Django :: 5.2
|
|
17
|
+
Classifier: Framework :: Django :: 6.0
|
|
18
|
+
Classifier: Intended Audience :: Developers
|
|
19
|
+
Classifier: Operating System :: OS Independent
|
|
20
|
+
Classifier: Programming Language :: Python
|
|
21
|
+
Classifier: Programming Language :: Python :: 3
|
|
22
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
23
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
24
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
25
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
26
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
27
|
+
Classifier: Programming Language :: Python :: 3.15
|
|
28
|
+
Classifier: Programming Language :: Python :: Implementation :: CPython
|
|
29
|
+
Classifier: Topic :: Internet :: WWW/HTTP
|
|
30
|
+
Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content
|
|
31
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
32
|
+
Classifier: Typing :: Typed
|
|
33
|
+
Requires-Python: >=3.11
|
|
34
|
+
Requires-Dist: django-modern-rest<0.18,>=0.15
|
|
35
|
+
Requires-Dist: typing-extensions>=4.12
|
|
36
|
+
Description-Content-Type: text/markdown
|
|
37
|
+
|
|
38
|
+
# dmr-jsonapi
|
|
39
|
+
|
|
40
|
+
*[JSON:API](https://jsonapi.org/) support for [django-modern-rest](https://github.com/wemake-services/django-modern-rest).*
|
|
41
|
+
|
|
42
|
+
[](https://github.com/blfpd/dmr-jsonapi/actions/workflows/test.yml)
|
|
43
|
+
[](https://pypi.org/project/dmr-jsonapi/)
|
|
44
|
+
[](https://pypi.org/project/dmr-jsonapi/)
|
|
45
|
+
[](https://github.com/wemake-services/wemake-python-styleguide)
|
|
46
|
+
|
|
47
|
+
## Features
|
|
48
|
+
|
|
49
|
+
- Parses and renders `application/vnd.api+json`
|
|
50
|
+
- Typed models for resources, relationships, links, documents, and errors,
|
|
51
|
+
they work with `pydantic`, `msgspec`, and any other serializer
|
|
52
|
+
that `django-modern-rest` supports
|
|
53
|
+
- Every error, including the ones that `django-modern-rest` raises
|
|
54
|
+
by itself, becomes a JSON:API error document with `status`, `code`,
|
|
55
|
+
`detail`, and `source`
|
|
56
|
+
- Follows the media type rules of the specification:
|
|
57
|
+
`415` for unsupported `Content-Type` parameters,
|
|
58
|
+
`406` for unsupported `Accept` parameters
|
|
59
|
+
- Helpers to build documents and pagination links
|
|
60
|
+
- OpenAPI schema with the right media types and error documents
|
|
61
|
+
- Fully typed, 100% test coverage, same tools and style as `django-modern-rest`
|
|
62
|
+
|
|
63
|
+
## Installation
|
|
64
|
+
|
|
65
|
+
```bash
|
|
66
|
+
pip install dmr-jsonapi
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
Works with `django-modern-rest` from `0.15` to `0.17`
|
|
70
|
+
and Python 3.11 and newer.
|
|
71
|
+
|
|
72
|
+
## Quick start
|
|
73
|
+
|
|
74
|
+
Describe your resource, your document, and use `JsonApiController`
|
|
75
|
+
instead of a regular `Controller`:
|
|
76
|
+
|
|
77
|
+
```python
|
|
78
|
+
>>> from typing_extensions import TypedDict
|
|
79
|
+
|
|
80
|
+
>>> from dmr import Path
|
|
81
|
+
>>> from dmr.plugins.pydantic import PydanticSerializer
|
|
82
|
+
>>> from dmr_jsonapi import JsonApiController
|
|
83
|
+
>>> from dmr_jsonapi.builders import document, resource_object
|
|
84
|
+
>>> from dmr_jsonapi.objects import DocumentEnvelope, ResourceObject
|
|
85
|
+
|
|
86
|
+
>>> class UserAttributes(TypedDict):
|
|
87
|
+
... name: str
|
|
88
|
+
|
|
89
|
+
>>> class UserPath(TypedDict):
|
|
90
|
+
... user_id: int
|
|
91
|
+
|
|
92
|
+
>>> class UserDocument(DocumentEnvelope):
|
|
93
|
+
... data: ResourceObject[UserAttributes]
|
|
94
|
+
|
|
95
|
+
>>> class UserController(JsonApiController[PydanticSerializer]):
|
|
96
|
+
... def get(self, parsed_path: Path[UserPath]) -> UserDocument:
|
|
97
|
+
... attributes: UserAttributes = {'name': 'Zamenhof'}
|
|
98
|
+
... return document(
|
|
99
|
+
... resource_object('users', parsed_path['user_id'], attributes),
|
|
100
|
+
... )
|
|
101
|
+
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
Call it like any other controller. The response has the JSON:API media type:
|
|
105
|
+
|
|
106
|
+
```python
|
|
107
|
+
>>> from dmr.test import DMRRequestFactory
|
|
108
|
+
|
|
109
|
+
>>> request = DMRRequestFactory().get('/users/1/')
|
|
110
|
+
>>> response = UserController.as_view()(request, user_id=1)
|
|
111
|
+
>>> response.status_code
|
|
112
|
+
200
|
|
113
|
+
>>> response['Content-Type']
|
|
114
|
+
'application/vnd.api+json'
|
|
115
|
+
>>> response.content
|
|
116
|
+
b'{"data":{"type":"users","id":"1","attributes":{"name":"Zamenhof"}}}'
|
|
117
|
+
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
### Name your documents
|
|
121
|
+
|
|
122
|
+
Define documents by subclassing `DocumentEnvelope` and adding `data`,
|
|
123
|
+
like `UserDocument` above. Do not use `Document[ResourceObject[...]]`
|
|
124
|
+
as a top level request or response type.
|
|
125
|
+
Schema generators name every specialization of a generic `TypedDict`
|
|
126
|
+
the same, so two of them clash in your OpenAPI schema.
|
|
127
|
+
Python also can't substitute type arguments when you subclass
|
|
128
|
+
a specialized generic `TypedDict`, so validation would silently go away.
|
|
129
|
+
|
|
130
|
+
`Document[...]` is still handy to annotate your own helpers,
|
|
131
|
+
the documents that you define this way are compatible with it.
|
|
132
|
+
|
|
133
|
+
## Errors
|
|
134
|
+
|
|
135
|
+
All errors that `django-modern-rest` produces (validation, `404`, `406`,
|
|
136
|
+
`405`, throttling, authentication, and so on) are rendered as JSON:API errors:
|
|
137
|
+
|
|
138
|
+
```python
|
|
139
|
+
>>> import json
|
|
140
|
+
|
|
141
|
+
>>> class ArticleController(JsonApiController[PydanticSerializer]):
|
|
142
|
+
... def get(self) -> UserDocument:
|
|
143
|
+
... raise NotImplementedError
|
|
144
|
+
|
|
145
|
+
>>> request = DMRRequestFactory().delete('/articles/')
|
|
146
|
+
>>> response = ArticleController.as_view()(request)
|
|
147
|
+
>>> response.status_code
|
|
148
|
+
405
|
|
149
|
+
>>> json.loads(response.content)['errors'][0]['status']
|
|
150
|
+
'405'
|
|
151
|
+
|
|
152
|
+
```
|
|
153
|
+
|
|
154
|
+
Validation errors point to the broken place in the request:
|
|
155
|
+
|
|
156
|
+
```json
|
|
157
|
+
{
|
|
158
|
+
"errors": [
|
|
159
|
+
{
|
|
160
|
+
"status": "400",
|
|
161
|
+
"code": "value_error",
|
|
162
|
+
"detail": "Input should be a valid string",
|
|
163
|
+
"source": {"pointer": "/data/attributes/name"}
|
|
164
|
+
}
|
|
165
|
+
]
|
|
166
|
+
}
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
Locations of the body become JSON pointers, locations of query parameters
|
|
170
|
+
and headers become `source.parameter` and `source.header`.
|
|
171
|
+
|
|
172
|
+
To return your own errors, raise `JsonApiError` anywhere in your API:
|
|
173
|
+
|
|
174
|
+
```python
|
|
175
|
+
>>> from http import HTTPStatus
|
|
176
|
+
>>> from dmr import ResponseSpec
|
|
177
|
+
>>> from dmr_jsonapi import JsonApiError
|
|
178
|
+
>>> from dmr_jsonapi.errors import error_object
|
|
179
|
+
>>> from dmr_jsonapi.objects import ErrorDocument
|
|
180
|
+
|
|
181
|
+
>>> class MissingUserController(JsonApiController[PydanticSerializer]):
|
|
182
|
+
... responses = (
|
|
183
|
+
... ResponseSpec(ErrorDocument, status_code=HTTPStatus.NOT_FOUND),
|
|
184
|
+
... )
|
|
185
|
+
...
|
|
186
|
+
... def get(self) -> UserDocument:
|
|
187
|
+
... raise JsonApiError(
|
|
188
|
+
... error_object(
|
|
189
|
+
... 'User does not exist',
|
|
190
|
+
... code='user_not_found',
|
|
191
|
+
... source={'parameter': 'user_id'},
|
|
192
|
+
... ),
|
|
193
|
+
... status_code=HTTPStatus.NOT_FOUND,
|
|
194
|
+
... )
|
|
195
|
+
|
|
196
|
+
>>> response = MissingUserController.as_view()(DMRRequestFactory().get('/'))
|
|
197
|
+
>>> response.status_code
|
|
198
|
+
404
|
|
199
|
+
>>> json.loads(response.content)
|
|
200
|
+
{'errors': [{'status': '404', 'code': 'user_not_found', 'detail': 'User does not exist', 'source': {'parameter': 'user_id'}}]}
|
|
201
|
+
|
|
202
|
+
```
|
|
203
|
+
|
|
204
|
+
`status` is always filled in for you and always matches the HTTP status code.
|
|
205
|
+
Like with any `django-modern-rest` response, declare the status codes
|
|
206
|
+
that you return, unless you turn off response validation.
|
|
207
|
+
Several error objects can be passed to one `JsonApiError`.
|
|
208
|
+
|
|
209
|
+
## Documents and pagination
|
|
210
|
+
|
|
211
|
+
`dmr_jsonapi.builders` has small functions for the repetitive parts:
|
|
212
|
+
`resource_identifier`, `resource_object`, `relationship_to_one`,
|
|
213
|
+
`relationship_to_many`, `document`, and `pagination_links`.
|
|
214
|
+
They only include members that you pass, ids are converted to strings.
|
|
215
|
+
|
|
216
|
+
```python
|
|
217
|
+
>>> from django.test import RequestFactory
|
|
218
|
+
>>> from dmr_jsonapi.builders import pagination_links
|
|
219
|
+
|
|
220
|
+
>>> request = RequestFactory().get('/users/', {'page[number]': '2'})
|
|
221
|
+
>>> links = pagination_links(request, number=2, size=10, total=25)
|
|
222
|
+
>>> links['next']
|
|
223
|
+
'http://testserver/users/?page%5Bnumber%5D=3&page%5Bsize%5D=10'
|
|
224
|
+
>>> links['last']
|
|
225
|
+
'http://testserver/users/?page%5Bnumber%5D=3&page%5Bsize%5D=10'
|
|
226
|
+
|
|
227
|
+
```
|
|
228
|
+
|
|
229
|
+
## What `JsonApiController` does
|
|
230
|
+
|
|
231
|
+
- Uses `JsonApiParser` and `JsonApiRenderer` by default.
|
|
232
|
+
Both use `msgspec` when it is installed, same as `django-modern-rest`.
|
|
233
|
+
- Responds with `415` if a request body has `Content-Type` parameters
|
|
234
|
+
other than `ext` and `profile`. Pass `allowed_params=` to `JsonApiParser`
|
|
235
|
+
if you need to relax it, for example to accept `charset`.
|
|
236
|
+
- Responds with `406` if every JSON:API media type in `Accept`
|
|
237
|
+
has parameters other than `ext` and `profile`.
|
|
238
|
+
- Uses `ErrorDocument` as the error model in the OpenAPI schema.
|
|
239
|
+
|
|
240
|
+
You can use the parser and the renderer without the controller too,
|
|
241
|
+
add them to `parsers` and `renderers` of any `django-modern-rest` controller
|
|
242
|
+
or to the `DMR_SETTINGS`.
|
|
243
|
+
|
|
244
|
+
## Not supported yet
|
|
245
|
+
|
|
246
|
+
- Parsing of `include`, `fields[...]`, `sort`, and `filter` query parameters,
|
|
247
|
+
you can describe them with regular `Query` components
|
|
248
|
+
- Endpoints for relationships (`/users/1/relationships/posts/`)
|
|
249
|
+
- Negotiation of `ext` and `profile` media type parameters,
|
|
250
|
+
they are accepted, but ignored
|
|
251
|
+
- JSON:API errors for `404` and `500` handlers of the whole project,
|
|
252
|
+
`build_404_handler` and `build_500_handler` return the default format
|
|
253
|
+
|
|
254
|
+
## Development
|
|
255
|
+
|
|
256
|
+
We use [uv](https://github.com/astral-sh/uv) and
|
|
257
|
+
[just](https://github.com/casey/just), see [CONTRIBUTING.md](CONTRIBUTING.md).
|
|
258
|
+
|
|
259
|
+
## License
|
|
260
|
+
|
|
261
|
+
[MIT](LICENSE)
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
dmr_jsonapi/__init__.py,sha256=9sQu1HNqnkRoWaS_OpwLO4yRH8uIrQxkZywbnWLSfZQ,399
|
|
2
|
+
dmr_jsonapi/_json.py,sha256=hvveDzpjcSlZZySugk7P_wG3VNX7E-lGOPPBsOfMbdk,963
|
|
3
|
+
dmr_jsonapi/_members.py,sha256=OMyYHcJ0X27SwG2eUFDboMB108Jy-ckGMyh2mNjfCyA,737
|
|
4
|
+
dmr_jsonapi/builders.py,sha256=BhWoiorSs6LDfKYiQqNO27hkBcV586HlrW2oNiUWEHE,4757
|
|
5
|
+
dmr_jsonapi/constants.py,sha256=Huarogj4ykUI0XQoiO1pcqlKJUMJX2z9jgg2O1EbCJo,345
|
|
6
|
+
dmr_jsonapi/controller.py,sha256=XKpXs35j6aD2TiN8EPCl5L5qZbmtXjbhczPEYUb37Mc,4695
|
|
7
|
+
dmr_jsonapi/errors.py,sha256=1Duu2VN-ChpfA2cfEHXiziukFpO4oKrNiIi43JaBt4w,6177
|
|
8
|
+
dmr_jsonapi/negotiation.py,sha256=6o6S9Taf8P787lobKFir4ZYPdO7bCiWa2Iv4ajuLotA,1633
|
|
9
|
+
dmr_jsonapi/objects.py,sha256=5zEib7wHITFKP9nT9iEoIJmNwnGDa8DuAzMCH8yjRJo,5339
|
|
10
|
+
dmr_jsonapi/parsers.py,sha256=FKT19afdqAw8wVCl1uuPJEt7GPV3TZOcpVxih10qye4,3688
|
|
11
|
+
dmr_jsonapi/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
12
|
+
dmr_jsonapi/renderers.py,sha256=IAEzjo49ETxMowbBEGTEcfiPvxJK8XvNfl4WtETa7UI,1372
|
|
13
|
+
dmr_jsonapi-0.1.0.dist-info/METADATA,sha256=iPKigYVfwPiILxXUQj6v0Fi0nt1Tg8AV7BBI0p-TPZw,9501
|
|
14
|
+
dmr_jsonapi-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
15
|
+
dmr_jsonapi-0.1.0.dist-info/licenses/LICENSE,sha256=GqPOPYaUZ9VzaREw636j2nqADq00NKzOVMx6W2bj8Qk,1097
|
|
16
|
+
dmr_jsonapi-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
The MIT License (MIT)
|
|
2
|
+
Copyright (c) 2026 Baptiste Darthenay
|
|
3
|
+
|
|
4
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
5
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
6
|
+
in the Software without restriction, including without limitation the rights
|
|
7
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
8
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
9
|
+
furnished to do so, subject to the following conditions:
|
|
10
|
+
|
|
11
|
+
The above copyright notice and this permission notice shall be included in all
|
|
12
|
+
copies or substantial portions of the Software.
|
|
13
|
+
|
|
14
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
|
15
|
+
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
|
16
|
+
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
|
17
|
+
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
|
|
18
|
+
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
|
|
19
|
+
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
|
|
20
|
+
OR OTHER DEALINGS IN THE SOFTWARE.
|