dmr-jsonapi 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,269 @@
1
+ #### joe made this: http://goel.io/joe
2
+ #### macos ####
3
+ # General
4
+ *.DS_Store
5
+ .AppleDouble
6
+ .LSOverride
7
+
8
+ # Icon must end with two \r
9
+ Icon
10
+
11
+
12
+ # Thumbnails
13
+ ._*
14
+
15
+ # Files that might appear in the root of a volume
16
+ .DocumentRevisions-V100
17
+ .fseventsd
18
+ .Spotlight-V100
19
+ .TemporaryItems
20
+ .Trashes
21
+ .VolumeIcon.icns
22
+ .com.apple.timemachine.donotpresent
23
+
24
+ # Directories potentially created on remote AFP share
25
+ .AppleDB
26
+ .AppleDesktop
27
+ Network Trash Folder
28
+ Temporary Items
29
+ .apdisk
30
+ #### linux ####
31
+ *~
32
+
33
+ # temporary files which can be created if a process still has a handle open of a deleted file
34
+ .fuse_hidden*
35
+
36
+ # KDE directory preferences
37
+ .directory
38
+
39
+ # Linux trash folder which might appear on any partition or disk
40
+ .Trash-*
41
+
42
+ # .nfs files are created when an open file is removed but is still being accessed
43
+ .nfs*
44
+ #### windows ####
45
+ # Windows thumbnail cache files
46
+ Thumbs.db
47
+ ehthumbs.db
48
+ ehthumbs_vista.db
49
+
50
+ # Dump file
51
+ *.stackdump
52
+
53
+ # Folder config file
54
+ Desktop.ini
55
+
56
+ # Recycle Bin used on file shares
57
+ $RECYCLE.BIN/
58
+
59
+ # Windows Installer files
60
+ *.cab
61
+ *.msi
62
+ *.msm
63
+ *.msp
64
+
65
+ # Windows shortcuts
66
+ *.lnk
67
+ #### python ####
68
+ # Byte-compiled / optimized / DLL files
69
+ __pycache__/
70
+ *.py[cod]
71
+ *$py.class
72
+
73
+ # C extensions
74
+ *.so
75
+
76
+ # Distribution / packaging
77
+ .Python
78
+ build/
79
+ develop-eggs/
80
+ dist/
81
+ downloads/
82
+ eggs/
83
+ .eggs/
84
+ lib/
85
+ lib64/
86
+ parts/
87
+ sdist/
88
+ var/
89
+ wheels/
90
+ *.egg-info/
91
+ .installed.cfg
92
+ *.egg
93
+
94
+ # PyInstaller
95
+ # Usually these files are written by a python script from a template
96
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
97
+ *.manifest
98
+ *.spec
99
+
100
+ # Installer logs
101
+ pip-log.txt
102
+ pip-delete-this-directory.txt
103
+
104
+ # Unit test / coverage / tracecov reports
105
+ htmlcov/
106
+ .tox/
107
+ .coverage
108
+ .coverage.*
109
+ .cache
110
+ nosetests.xml
111
+ coverage.xml
112
+ *.cover
113
+ .hypothesis/
114
+ .ruff_cache/
115
+ tracecov-report.md
116
+ tracecov-report.html
117
+
118
+ # Translations
119
+ !*.mo
120
+ *.pot
121
+
122
+ # Django stuff:
123
+ *.log
124
+ local_settings.py
125
+
126
+ # Flask stuff:
127
+ instance/
128
+ .webassets-cache
129
+
130
+ # Scrapy stuff:
131
+ .scrapy
132
+
133
+ # Sphinx documentation
134
+ docs/_build/
135
+ .auto_pytabs_cache/
136
+
137
+ # PyBuilder
138
+ target/
139
+
140
+ # Jupyter Notebook
141
+ .ipynb_checkpoints
142
+
143
+ # celery beat schedule file
144
+ celerybeat-schedule
145
+
146
+ # SageMath parsed files
147
+ *.sage.py
148
+
149
+ # Environments
150
+ .env
151
+ .venv
152
+ env/
153
+ venv/
154
+ ENV/
155
+
156
+ # Spyder project settings
157
+ .spyderproject
158
+ .spyproject
159
+
160
+ # Rope project settings
161
+ .ropeproject
162
+
163
+ # mkdocs documentation
164
+ /site
165
+
166
+ # mypy
167
+ .mypy_cache/
168
+
169
+ #### jetbrains ####
170
+ # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm
171
+ # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
172
+
173
+ #### vscode ####
174
+ .vscode/
175
+
176
+ # User-specific stuff:
177
+ .idea/**/workspace.xml
178
+ .idea/**/tasks.xml
179
+ .idea/dictionaries
180
+
181
+ # Sensitive or high-churn files:
182
+ .idea/**/dataSources/
183
+ .idea/**/dataSources.ids
184
+ .idea/**/dataSources.xml
185
+ .idea/**/dataSources.local.xml
186
+ .idea/**/sqlDataSources.xml
187
+ .idea/**/dynamic.xml
188
+ .idea/**/uiDesigner.xml
189
+
190
+ # Gradle:
191
+ .idea/**/gradle.xml
192
+ .idea/**/libraries
193
+
194
+ # CMake
195
+ cmake-build-debug/
196
+
197
+ # Mongo Explorer plugin:
198
+ .idea/**/mongoSettings.xml
199
+
200
+ ## File-based project format:
201
+ *.iws
202
+
203
+ ## Plugin-specific files:
204
+
205
+ # IntelliJ
206
+ /out/
207
+
208
+ # mpeltonen/sbt-idea plugin
209
+ .idea_modules/
210
+
211
+ # JIRA plugin
212
+ atlassian-ide-plugin.xml
213
+
214
+ # Cursive Clojure plugin
215
+ .idea/replstate.xml
216
+
217
+ # Crashlytics plugin (for Android Studio and IntelliJ)
218
+ com_crashlytics_export_strings.xml
219
+ crashlytics.properties
220
+ crashlytics-build.properties
221
+ fabric.properties
222
+
223
+ # pyenv
224
+ .python-version
225
+
226
+
227
+ #####=== Custom ===#####
228
+ # File types:
229
+ *.sqlite3
230
+ *.db
231
+
232
+ # Configuration file with private data:
233
+ *.env
234
+ .env
235
+
236
+ # Artifacts:
237
+ .gitlab/.svn/
238
+ artifacts/
239
+ wheelhouse/
240
+
241
+ # mypy:
242
+ .mypy_cache/
243
+
244
+ # pytest and hypothesis
245
+ .pytest_cache/
246
+ .hypothesis/
247
+
248
+ # ipython:
249
+ .ipython/
250
+ .python_history
251
+
252
+ # ruff:
253
+ .ruff_cache/
254
+
255
+ # import-linter:
256
+ .import_linter_cache/
257
+
258
+ # safety:
259
+ .safety/
260
+
261
+ # PyCharm:
262
+ .idea/
263
+
264
+ # CodSpeed:
265
+ .codspeed/
266
+
267
+ # AI slop:
268
+ .claude/
269
+ .codex/
@@ -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.
@@ -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
+ [![Tests Result](https://github.com/blfpd/dmr-jsonapi/actions/workflows/test.yml/badge.svg?event=push)](https://github.com/blfpd/dmr-jsonapi/actions/workflows/test.yml)
43
+ [![PyPI](https://img.shields.io/pypi/v/dmr-jsonapi.svg)](https://pypi.org/project/dmr-jsonapi/)
44
+ [![Supported Python Version](https://img.shields.io/pypi/pyversions/dmr-jsonapi.svg)](https://pypi.org/project/dmr-jsonapi/)
45
+ [![Code Style](https://img.shields.io/badge/style-wemake-000000.svg)](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,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
@@ -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
@@ -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
+ )