aiohttp-json-api: JSON API implementation for aiohttp

Contents:

JSON API implementation for aiohttp

https://img.shields.io/pypi/v/aiohttp_json_api.svg https://img.shields.io/travis/vovanbo/aiohttp_json_api.svg Documentation Status Updates

Introduction

This project heavily inspired by py-jsonapi (author is Benedikt Schmitt). Some parts of this project is improved and refactored dev-schema branch of py-jsonapi. At beginning of aiohttp-json-api this branch was a great, but not finished implementation of JSON API with schema controllers. Also, py-jsonapi is not asynchronous and use inside self-implemented Request/Response classes.

Some of base entities of py-jsonapi was replaced with aiohttp server’s objects, some of it was divided into new separate entities (e.g. JSONAPIContext or Registry).

Todo

  • Tutorials
  • Improve documentation
  • Tests
  • Features description
  • Customizable payload keys inflection (default is dasherize <-> underscore)
  • Support for JSON API extensions (bulk creation etc.)
  • Polymorphic relationships

Credits

This package was created with Cookiecutter and the cookiecutter-pypackage project template.

Installation

Stable release

To install aiohttp JSON API, run this command in your terminal:

$ pip install aiohttp_json_api

This is the preferred method to install aiohttp JSON API, as it will always install the most recent stable release.

If you don’t have pip installed, this Python installation guide can guide you through the process.

From sources

The sources for aiohttp JSON API can be downloaded from the Github repo.

You can either clone the public repository:

$ git clone git://github.com/vovanbo/aiohttp_json_api

Or download the tarball:

$ curl  -OL https://github.com/vovanbo/aiohttp_json_api/tarball/master

Once you have a copy of the source, you can install it with:

$ python setup.py install

Default setup of resources, routes and handlers

Resource name Method Route Handler
jsonapi.collection GET /{type} get_collection()
jsonapi.collection POST /{type} post_resource()
jsonapi.resource GET /{type}/{id} get_resource()
jsonapi.resource PATCH /{type}/{id} patch_resource()
jsonapi.resource DELETE /{type}/{id} delete_resource()
jsonapi.relationships GET /{type}/{id}/relationships/{relation} get_relationship()
jsonapi.relationships POST /{type}/{id}/relationships/{relation} post_relationship()
jsonapi.relationships PATCH /{type}/{id}/relationships/{relation} patch_relationship()
jsonapi.relationships DELETE /{type}/{id}/relationships/{relation} delete_relationship()
jsonapi.related GET /{type}/{id}/{relation} get_related()

Usage

Todo

Tutorials will be added soon.

At this moment, the best way to examine features of this application is looking at simple example. Models of this example related to entities from official JSON API specification (e.g. here in “Compound Documents” section).

Contributing

Contributions are welcome, and they are greatly appreciated! Every little bit helps, and credit will always be given.

You can contribute in many ways:

Types of Contributions

Report Bugs

Report bugs at https://github.com/vovanbo/aiohttp_json_api/issues.

If you are reporting a bug, please include:

  • Your operating system name and version.
  • Any details about your local setup that might be helpful in troubleshooting.
  • Detailed steps to reproduce the bug.

Fix Bugs

Look through the GitHub issues for bugs. Anything tagged with “bug” and “help wanted” is open to whoever wants to implement it.

Implement Features

Look through the GitHub issues for features. Anything tagged with “enhancement” and “help wanted” is open to whoever wants to implement it.

Write Documentation

aiohttp JSON API could always use more documentation, whether as part of the official aiohttp JSON API docs, in docstrings, or even on the web in blog posts, articles, and such.

Submit Feedback

The best way to send feedback is to file an issue at https://github.com/vovanbo/aiohttp_json_api/issues.

If you are proposing a feature:

  • Explain in detail how it would work.
  • Keep the scope as narrow as possible, to make it easier to implement.
  • Remember that this is a volunteer-driven project, and that contributions are welcome :)

Get Started!

Ready to contribute? Here’s how to set up aiohttp_json_api for local development.

  1. Fork the aiohttp_json_api repo on GitHub.

  2. Clone your fork locally:

    $ git clone git@github.com:your_name_here/aiohttp_json_api.git
    
  3. Install your local copy into a virtualenv. Assuming you have virtualenvwrapper installed, this is how you set up your fork for local development:

    $ mkvirtualenv aiohttp_json_api
    $ cd aiohttp_json_api/
    $ python setup.py develop
    
  4. Create a branch for local development:

    $ git checkout -b name-of-your-bugfix-or-feature
    

    Now you can make your changes locally.

  5. When you’re done making changes, check that your changes pass flake8 and the tests, including testing other Python versions with tox:

    $ flake8 aiohttp_json_api tests
    $ python setup.py test or py.test
    $ tox
    

    To get flake8 and tox, just pip install them into your virtualenv.

  6. Commit your changes and push your branch to GitHub:

    $ git add .
    $ git commit -m "Your detailed description of your changes."
    $ git push origin name-of-your-bugfix-or-feature
    
  7. Submit a pull request through the GitHub website.

Pull Request Guidelines

Before you submit a pull request, check that it meets these guidelines:

  1. The pull request should include tests.
  2. If the pull request adds functionality, the docs should be updated. Put your new functionality into a function with a docstring, and add the feature to the list in README.rst.
  3. The pull request should work for Python 3.6 and later. Check https://travis-ci.org/vovanbo/aiohttp_json_api/pull_requests and make sure that the tests pass for all supported Python versions.

Tips

To run a subset of tests:

$ py.test tests.test_aiohttp_json_api

Credits

Development Lead

Author of core idea

Contributors

None yet. Why not be the first?

History

0.37.0 (2018-03-03)

  • Drop Python 3.5 support
  • Update documentation

0.36.1 (2018-03-03)

  • Fix bug with content negotiation
  • Add cherry-picked and improved helpers from python-mimeparse

0.36.0 (2018-03-02)

  • Improve content negotiation (fix #185) with python-mimeparse
  • Update requirements

0.35.2 (2017-12-13)

  • Fix bug with wrong query parameters of links in compound documents

0.35.1 (2017-12-12)

  • Fix trafaret requirement to 1.0.2 (included rfc3339.Date)

0.35.0 (2017-12-11)

BREAKING CHANGES!

  • Schema is separated into Schema (marshaller) and Controller
  • Request context instantiated in handlers and was renamed to JSONAPIContext
  • Change signature of setup JSON API method in application (now we should pass a mapping between schemas and controllers)
  • New abstract base class for Controller
  • Schema and Controller must be initialized with only one parameter — JSONAPIContext
  • Passing a context to almost each method of Schema no more required (context is accessible from Schema or Controller instance directly)
  • Remove decorator for JSON API handlers (content negotiation moved to middleware)
  • Refactored fields and schema modules
  • Improved fetching of compound documents
  • Examples are updated to conform with all changes in this release

0.33.1 (2017-12-06)

  • Fix bug with no Accept header in request

0.33.0 (2017-12-06)

  • Improve content type negotiation
  • Improve documentation
  • Add field for Date
  • Add example based on fantasy database
  • Introduce JSON API integration test suite (not done yet!)
  • Improve collections helpers
  • No more links normalization by default
  • Move meta object at top level of result document

0.32.0 (2017-11-21)

  • Constants, enums and structs refactoring (backward incompatible)
  • Add useful typings
  • Documentation fixes
  • Extend development requirements

0.31.0 (2017-11-14)

  • Improve performance of URL resolving again. At this time with usage of standard Python urllib
  • Upgrade requirements

0.30.0 (2017-11-13)

  • Improve performance of URL resolving in Link field (with cachetools)
  • Upgrade requirements

0.29.2 (2017-11-02)

  • Documentation improvements

0.29.1 (2017-11-02)

  • Update README
  • Upgrade requirements

0.29.0 (2017-11-02)

  • Simple example of usage is added
  • Fix bug in handler of relationship query

0.28.3 (2017-11-02)

  • Fix bug with wrong read-only field error
  • Don’t require setup ID field in Schema to update a resource

0.28.2 (2017-11-01)

  • Add multidict to requirements and to README

0.28.1 (2017-10-31)

  • Fix small bug with wrong empty sorting in RequestContext

0.28.0 (2017-10-31)

  • Add support for customizable inflection of fields from query string.
  • Convert static methods of RequestContext to class methods
  • Update docs of RequestContext methods

0.27.1 (2017-10-31)

  • Fix packaging of ABCs and compats

0.27.0 (2017-10-31)

  • Abstract base classes refactoring (separate Field and Schema ABCs)
  • Fix bug with compound documents in case models has no property “resource_id”
  • Remove buggy helper to check subclass of any instance
  • Decompose setup application method to increase readability
  • Properly error raised in jsonapi_handler decorator
  • Use one field instead of two to check what type of relation have the field

0.26.0 (2017-10-30)

  • Properly use abstract base classes. Inherit SchemaABC from ABC.
  • Rename resource validation methods (backward incompatible)

0.25.0 (2017-10-18)

  • Add Tuple field
  • Fix bug with List field items enumeration
  • Fix wrong conversion of Decimal field to string on deserialization
  • Add yarl (>=0.13) to requirements

0.24.1 (2017-10-12)

  • Add support for length range specifying for List field

0.24.0 (2017-10-04)

  • Convert document render utility to async coroutine (backward incompatible)
  • Rename Error class property “json” to “as_dict” to clarify

0.23.0 (2017-10-03)

  • Use MultiDict for request context filters and FilterRule tuple (backward incompatible)
  • Debug info on request context creation

0.22.2 (2017-09-27)

  • Add support for nullable List field

0.22.1 (2017-09-25)

  • Fix bug with wrong exit from compound documents fetch utility (“return” instead of “break”)

0.22.0 (2017-09-22)

  • Remove recursive fetching of compound documents. Replace it with simple loop.

0.21.2 (2017-09-22)

  • Fix bug with fetching compound documents when query parameter “include” contains the same relation twice and more.

0.21.1 (2017-09-19)

  • Fix bug with non-underscored relation name in relationship handlers

0.21.0 (2017-09-19)

  • Add support for field names conversion passed to “include” request context
  • Update development requirements

0.20.2 (2017-08-30)

  • Avoid assertion in Registry ensure identifier method
  • Make Schema getter of object id static
  • Avoid to filter out empty fields of rendered documents (less memory and faster)
  • Get id field of schema more safely in URI resource ID validator

0.20.1 (2017-08-15)

  • Add support for load only fields (like a Marshmallow)

0.20.0 (2017-08-14)

  • Asynchronous validators support
  • Routes namespace can be customized
  • Relative links support

0.19.1 (2017-08-10)

  • Improve serialization result default keys creation

0.19.0 (2017-08-10)

  • Refactor schema serializer to fix bug with no resource link in result
  • Clean-up validation of expected ID in pre-validaiton of resource
  • Use status property of ErrorList in error middleware to return HTTP status
  • Remove default getter from Link field, because it doesn’t used anymore

0.18.1 (2017-08-09)

  • Migrate to trafaret >= 0.11.0
  • Fix requirement of trafaret to version greater than 0.11.0

0.18.0 (2017-08-09)

  • Properly handle missing values in deserialization and validation

0.17.1 (2017-07-31)

  • Add support for validation of Relationships ID field

0.17.0 (2017-07-28)

  • Normalize resource_id parameter usage in all mutation methods.
  • Add fetch_resource schema coroutine to receive resource instance by ID.
  • Add separate method for mapping deserialized data to schema.
  • Context is required parameter for deserialization schema method.
  • Move docs to ABC schema.
  • Properly handle allow_none parameter for UUID field

0.16.2 (2017-07-24)

  • Fix arguments passed to validators

0.16.1 (2017-07-24)

  • Pass context to value setter in update methods

0.16.0 (2017-07-22)

0.15.2 (2017-07-21)

  • Initialize default relationships links in meta-class, to avoid bug with empty names of relationships fields

0.15.1 (2017-07-19)

  • Rename resource ID parameter of query_resource schema’ method.

0.15.0 (2017-07-18)

  • Pagination is initialized from request by default. Remove separate class method of BasePagination to initialize pagination instance
  • Improve value validation error for absent fields
  • Improve validation error of string field with choices

0.14.0 (2017-07-13)

  • Customisable JSON API handlers support
  • DRY in handlers
  • Move context builder from middleware to jsonapi_handler decorator
  • Request context receive optional resource_type now

0.13.0 (2017-07-12)

  • Revert back to asynchronous setters, because it’s used in update relationships and it might want to query DB, for example

0.12.0 (2017-07-12)

  • Base Registry class from UserDict, so Registry is a dict with ensure_identifier method.
  • More strict typing checks on setup.

0.11.1 (2017-07-11)

  • Fix bug with mutation not cloned resource in method for delete relationship
  • Require JSON API content type on delete relationships

0.11.0 (2017-07-11)

  • Method for update return original and updated resource as result. Updated resource is created via deepcopy. It will be useful to determine returned HTTP status
  • Fix bug with enumeration (choices) in String field
  • Fix bug with context event setup for OPTIONS, HEAD and another request methods not used in JSON API

0.10.0 (2017-07-10)

  • Mass refactoring of schema, fields, validation and decorators
  • Generic approach to setup Schema decorators is used (inspired by Marshmallow)
  • Fields are used only for encode/decode now (with pre/post validation). Additional validators for fields must be created on schema level
  • Custom JSON encoder with support JSONPointer serialization
  • Remove boltons from requirements
  • No more remap input data dictionary with key names to underscores conversion.
  • Add helpers “first” and “make_sentinel” (cherry-picked from boltons)
  • Fix enumeration (choices) support in String field

0.9.3 (2017-07-06)

  • Setup content-type validation on mutation API methods (application/vnd.api+json is required)
  • Properly get and encode relationships fields
  • Update docs and typing for ensure_identifier Registry’s method

0.9.2 (2017-07-06)

  • Fix bugs related to Python 3.5
  • Generation of documentation on RTD is fixed

0.9.1 (2017-07-06)

  • Python 3.5 compatibility changes

0.9.0 (2017-07-06)

  • Handle aiohttp-json-api exceptions and errors in middleware. If exceptions is not related to JSON API errors, then exception is reraised
  • Huge refactoring of RequestContext
  • No more use of boltons cachedproperties, instead use parsing static methods related to each request context’ entity
  • Update docs for RequestContext methods
  • Add typings to RequestContext

0.8.2 (2017-07-05)

  • Properly handle error with wrong relation name (raise HTTP 400)

0.8.1 (2017-07-05)

  • Fix bdist_wheel python tag to support Python 3.5

0.8.0 (2017-07-05)

  • Python 3.5 support (avoid usage of Python 3.6 format strings)
  • Registry is plain object now
  • Custom Registry support (registry_class parameter in aiohttp_json_api.setup_jsonapi method)
  • Log debugging information at start about registered resources, methods and routes
  • Use OrderedDict inside SchemaMeta

0.7.2 (2017-07-04)

  • Fix bug with JSONPointer when part passed via __truediv__ is integer
  • Validate relationship object before adding relationship in ToMany field

0.7.1 (2017-07-04)

  • Fix bugs with validation of resource identifier in relationships fields
  • Add typings for base fields

0.7.0 (2017-07-03)

  • Setup of JSON API must be imported from package directly
  • Fix bugs with decode fields and allow None values

0.6.2 (2017-06-29)

  • Update HISTORY

0.6.1 (2017-06-29)

  • Fix bug with Enum choices of String field

0.6.0 (2017-06-29)

  • Return resource in update method of Schema class. This will be helpful in inherit classes of Schemas.

0.5.5 (2017-06-15)

  • Setup auto-deploy to PyPI in Travis CI

0.5.4 (2017-06-15)

  • Initial release on PyPI

0.5.3 (2017-06-14)

  • Improve documentation

0.5.0 (2017-06-14)

  • Don’t use attrs package anymore
  • Refactor requirements (move it into setup.py)

0.4.0 (2017-06-13)

  • Schema imports refactoring (e.g. don’t use aiohttp_json_api.schema.schema.Schema anymore)

0.3.0 (2017-06-13)

  • Upgrade requirements

0.2.0 (2017-05-26)

  • Fix setup.py
  • Add test for Decimal trafaret field

0.1.1 (2017-05-26)

  • Dirty initial version

API Reference

Contents:

aiohttp_json_api package

Submodules

Common constants, enumerations and structures.

aiohttp_json_api.common.ALLOWED_MEMBER_NAME_REGEX = re.compile('^[a-zA-Z0-9]([a-zA-Z0-9\\-_]+[a-zA-Z0-9]|[a-zA-Z0-9]?)$')

Compiled regexp of rule

aiohttp_json_api.common.ALLOWED_MEMBER_NAME_RULE = '[a-zA-Z0-9]([a-zA-Z0-9\\-_]+[a-zA-Z0-9]|[a-zA-Z0-9]?)'

Regular expression rule for check allowed fields and types names

class aiohttp_json_api.common.Event[source]

Bases: enum.Flag

Request event enumeration.

ALWAYS = 15
DELETE = 8
GET = 1
NEVER = 16
PATCH = 4
POST = 2
class aiohttp_json_api.common.FilterRule(name, value)

Bases: tuple

Filter rule

name

Alias for field number 0

value

Alias for field number 1

aiohttp_json_api.common.JSONAPI = 'jsonapi'

Key of JSON API stuff in aiohttp.web.Application

aiohttp_json_api.common.JSONAPI_CONTENT_TYPE = 'application/vnd.api+json'

JSON API Content-Type by specification

class aiohttp_json_api.common.Relation[source]

Bases: enum.Enum

Types of relations enumeration.

TO_MANY = 2
TO_ONE = 1
class aiohttp_json_api.common.ResourceID(type, id)

Bases: tuple

JSON API resource identifier

id

Alias for field number 1

type

Alias for field number 0

class aiohttp_json_api.common.SortDirection[source]

Bases: enum.Enum

Sorting direction enumeration.

ASC = '+'
DESC = '-'
class aiohttp_json_api.common.Step[source]

Bases: enum.Enum

Marshalling step enumeration.

AFTER_DESERIALIZATION = 2
AFTER_SERIALIZATION = 4
BEFORE_DESERIALIZATION = 1
BEFORE_SERIALIZATION = 3
aiohttp_json_api.common.logger = <Logger aiohttp-json-api (WARNING)>

Logger instance

Request context.

class aiohttp_json_api.context.JSONAPIContext(request, resource_type=None)[source]

Bases: object

JSON API request context.

FIELDS_RE = re.compile('fields\\[(?P<name>\\w[-\\w_]*)\\]')
FILTER_KEY = re.compile('filter\\[(?P<field>\\w[-\\w_]*)\\]')
FILTER_VALUE = re.compile('(?P<name>[a-z]+):(?P<value>.*)')
app
controller
classmethod convert_field_name(field_name)[source]
event
fields
filters
get_filter(field, name, default=None)[source]

Get filter from request context by name and field.

If the filter name has been applied on the field, the filter is returned and default otherwise.

Parameters:
  • field (str) – Name of field
  • name (str) – Name of filter
  • default (Any) – A fallback rule value for the filter.
Return type:

Any

get_order(field, default=<SortDirection.ASC: '+'>)[source]

Get sorting order of field from request context.

Checks if a sort criterion (+ or -) for the field exists and returns it.

Parameters:
  • Tuple[str, ..]] field (Union[str,) –
  • default (SortDirection) – Returned, if no criterion is set by the request.
Return type:

SortDirection

has_filter(field, name)[source]

Check current context for existing filters of field.

Returns true, if the filter name has been applied at least once on the field.

Parameters:
  • field (str) – Name of field
  • name (str) – Name of filter
Return type:

bool

include
inflect()

Make an underscored, lowercase form from the expression in the string.

Example:

>>> underscore("DeviceType")
"device_type"

As a rule of thumb you can think of underscore() as the inverse of camelize(), though there are cases where that does not hold:

>>> camelize(underscore("IOError"))
"IoError"
pagination
classmethod parse_request_fields(request)[source]

Parse sparse fields from request query string.

Used for determine fields, which should be included in the response (sparse fieldset).

>>> from aiohttp_json_api.context import JSONAPIContext
>>> from aiohttp.test_utils import make_mocked_request
>>> request = make_mocked_request('GET', '/api/User?fields[User]=email,name&fields[Post]=comments')
>>> JSONAPIContext.parse_request_fields(request)
OrderedDict([('User', ('email', 'name')), ('Post', ('comments',))])
Seealso:http://jsonapi.org/format/#fetching-sparse-fieldsets
Return type:MutableMapping[str, Tuple[str, …]]
classmethod parse_request_filters(request)[source]

Parse filters from request query string.

Hint

Please note, that the filter strategy is not defined by the JSON API specification and depends on the implementation. If you want to use another filter strategy, feel free to override this method.

Returns a MultiDict with field names as keys and rules as values. Rule value is JSON deserialized from query string.

Filters can be applied using the query string.

>>> from aiohttp_json_api.context import JSONAPIContext
>>> from aiohttp.test_utils import make_mocked_request

>>> request = make_mocked_request('GET', '/api/User/?filter[name]=endswith:"Simpson"')
>>> JSONAPIContext.parse_request_filters(request)
<MultiDict('name': FilterRule(name='endswith', value='Simpson'))>

>>> request = make_mocked_request('GET', '/api/User/?filter[name]=endswith:"Simpson"&filter[name]=in:["Some","Names"]')
>>> JSONAPIContext.parse_request_filters(request)
<MultiDict('name': FilterRule(name='endswith', value='Simpson'), 'name': FilterRule(name='in', value=['Some', 'Names']))>

>>> request = make_mocked_request('GET', '/api/User/?filter[name]=in:["Homer Simpson", "Darth Vader"]')
>>> JSONAPIContext.parse_request_filters(request)
<MultiDict('name': FilterRule(name='in', value=['Homer Simpson', 'Darth Vader']))>

>>> request = make_mocked_request('GET', '/api/User/?filter[some-field]=startswith:"lisa"&filter[another-field]=lt:20')
>>> JSONAPIContext.parse_request_filters(request)
<MultiDict('some_field': FilterRule(name='startswith', value='lisa'), 'another_field': FilterRule(name='lt', value=20))>

The general syntax is:

"?filter[field]=name:rule"

where rule is a JSON value.

Raises:
Return type:

MutableMapping[str, FilterRule]

classmethod parse_request_includes(request)[source]

Parse compound documents parameters from request query string.

Returns the names of the relationships, which should be included into the response.

>>> from aiohttp_json_api.context import JSONAPIContext
>>> from aiohttp.test_utils import make_mocked_request
>>> request = make_mocked_request('GET', '/api/Post?include=author,comments.author,some-field.nested')
>>> JSONAPIContext.parse_request_includes(request)
(('author',), ('comments', 'author'), ('some_field', 'nested'))
Seealso:http://jsonapi.org/format/#fetching-includes
Return type:Tuple[Tuple[str, …], …]
classmethod parse_request_sorting(request)[source]

Parse sorting parameters of fields from request query string.

Returns a mapping with tuples as keys, and values with SortDirection, describing how the output should be sorted.

>>> from aiohttp_json_api.context import JSONAPIContext
>>> from aiohttp.test_utils import make_mocked_request
>>> request = make_mocked_request('GET', '/api/Post?sort=name,-age,+comments.count')
>>> JSONAPIContext.parse_request_sorting(request)
OrderedDict([(('name',), <SortDirection.ASC: '+'>), (('age',), <SortDirection.DESC: '-'>), (('comments', 'count'), <SortDirection.ASC: '+'>)])
Seealso:http://jsonapi.org/format/#fetching-sorting
Return type:MutableMapping[Tuple[str, …], SortDirection]
registry
request
resource_type
schema
Return type:Optional[SchemaABC]
sorting
class aiohttp_json_api.controller.DefaultController(context)[source]

Bases: aiohttp_json_api.abc.contoller.ControllerABC

add_relationship(field, resource, data, sp, **kwargs)[source]

Adds the members specified in the JSON API relationship object data to the relationship, unless the relationships already exist.

Parameters:
  • field (FieldABC) – Relationship field.
  • resource – Resource instance fetched by fetch_resource() in handler.
  • data (str) – The JSON API relationship object with the update information.
  • sp (JSONPointer) – The JSON pointer to the source of data.
static default_add(resource, data, sp, **kwargs)[source]
static default_include(resources, **kwargs)[source]
static default_query(resource, **kwargs)[source]
static default_remove(resource, data, sp, **kwargs)[source]
fetch_compound_documents(field, resources, **kwargs)[source]

Fetches the related resources. The default method uses the controller’s default_include(). Can be overridden.

Parameters:
  • field (FieldABC) – Relationship field.
  • resources – A list of resources.
  • context (JSONAPIContext) – Request context instance.
  • rest_path (list) – The name of the relationships of the returned relatives, which will also be included.
Return type:

list

Returns:

A list with the related resources. The list is empty or has exactly one element in the case of to-one relationships. If to-many relationships are paginated, the relatives from the first page should be returned.

query_relatives(field, resource, **kwargs)[source]

Controller for the related endpoint of the relationship with then name relation_name.

Parameters:
  • field (FieldABC) – Relationship field.
  • resource – Resource instance fetched by fetch_resource() in handler.
remove_relationship(field, resource, data, sp, **kwargs)[source]

Deletes the members specified in the JSON API relationship object data from the relationship.

Parameters:
  • field (FieldABC) – Relationship field.
  • resource – Resource instance fetched by fetch_resource() in handler.
  • data (str) – The JSON API relationship object with the update information.
  • sp (JSONPointer) – The JSON pointer to the source of data.
  • context (JSONAPIContext) – Request context instance.
update_relationship(field, resource, data, sp, **kwargs)[source]

Updates the relationship with the JSON API name relation_name.

Parameters:
  • field (FieldABC) – Relationship field.
  • resource – Resource instance fetched by fetch_resource() in handler.
  • data (str) – The JSON API relationship object with the update information.
  • sp (JSONPointer) – The JSON pointer to the source of data.
update_resource(resource, data, sp, **kwargs)[source]

Updates an existing resource. You should overridde this method in order to save the changes in the database.

The default implementation uses the BaseField descriptors to update the resource.

Parameters:
  • resource_id – The id of the resource
  • data (dict) – The JSON API resource object with the update information
  • sp (JSONPointer) – The JSON pointer to the source of data.
  • context (JSONAPIContext) – Request context instance

JSON encoder extension.

class aiohttp_json_api.encoder.JSONEncoder(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)[source]

Bases: json.encoder.JSONEncoder

Overloaded JSON encoder with JSONPointer support.

default(o)[source]

Add JSONPointer serializing support to default json.dumps.

Errors.

exception aiohttp_json_api.errors.Error(*, id_=None, about='', code=None, title=None, detail='', source_parameter=None, source_pointer=None, meta=None)[source]

Bases: Exception

Base class for all exceptions thrown by the API.

All subclasses of this exception are catches and converted into a response. All other exceptions will be replaced by an HTTPInternalServerError exception.

Seealso:http://jsonapi.org/format/#errors
as_dict

Represent instance of Error as dictionary.

status = 500
exception aiohttp_json_api.errors.ErrorList(errors=None)[source]

Bases: Exception

Exception contains list of errors.

Can be used to store a list of exceptions, which occur during the execution of a request.

Seealso:http://jsonapi.org/format/#error-objects
Seealso:http://jsonapi.org/examples/#error-objects-multiple-errors
append(error)[source]

Append the Error error to the error list.

Parameters:error (Error) – JSON API Error instance
extend(errors)[source]

Append errors to the list.

Parameters:errorsErrorList or a sequence of Error.
json

Create the JSON API error object.

Seealso:http://jsonapi.org/format/#error-objects
status

Return the most specific HTTP status code for all errors.

For single error in list returns its status. For many errors returns maximal status code.

exception aiohttp_json_api.errors.HTTPBadRequest(*, id_=None, about='', code=None, title=None, detail='', source_parameter=None, source_pointer=None, meta=None)[source]

Bases: aiohttp_json_api.errors.Error

HTTP 400 Bad Request.

The request could not be fulfilled due to the incorrect syntax of the request.

status = 400
exception aiohttp_json_api.errors.HTTPUnauthorized(*, id_=None, about='', code=None, title=None, detail='', source_parameter=None, source_pointer=None, meta=None)[source]

Bases: aiohttp_json_api.errors.Error

HTTP 401 Unauthorized.

The requester is not authorized to access the resource. This is similar to 403 but is used in cases where authentication is expected but has failed or has not been provided.

status = 401
exception aiohttp_json_api.errors.HTTPForbidden(*, id_=None, about='', code=None, title=None, detail='', source_parameter=None, source_pointer=None, meta=None)[source]

Bases: aiohttp_json_api.errors.Error

HTTP 403 Forbidden.

The request was formatted correctly but the server is refusing to supply the requested resource. Unlike 401, authenticating will not make a difference in the server’s response.

status = 403
exception aiohttp_json_api.errors.HTTPNotFound(*, id_=None, about='', code=None, title=None, detail='', source_parameter=None, source_pointer=None, meta=None)[source]

Bases: aiohttp_json_api.errors.Error

HTTP 404 Not found.

The resource could not be found. This is often used as a catch-all for all invalid URIs requested of the server.

status = 404
exception aiohttp_json_api.errors.HTTPMethodNotAllowed(*, id_=None, about='', code=None, title=None, detail='', source_parameter=None, source_pointer=None, meta=None)[source]

Bases: aiohttp_json_api.errors.Error

HTTP 405 Method not allowed.

The resource was requested using a method that is not allowed. For example, requesting a resource via a POST method when the resource only supports the GET method.

status = 405
exception aiohttp_json_api.errors.HTTPNotAcceptable(*, id_=None, about='', code=None, title=None, detail='', source_parameter=None, source_pointer=None, meta=None)[source]

Bases: aiohttp_json_api.errors.Error

HTTP 406 Not acceptable.

The resource is valid, but cannot be provided in a format specified in the Accept headers in the request.

status = 406
exception aiohttp_json_api.errors.HTTPConflict(*, id_=None, about='', code=None, title=None, detail='', source_parameter=None, source_pointer=None, meta=None)[source]

Bases: aiohttp_json_api.errors.Error

HTTP 409 Conflict.

The request cannot be completed due to a conflict in the request parameters.

status = 409
exception aiohttp_json_api.errors.HTTPGone(*, id_=None, about='', code=None, title=None, detail='', source_parameter=None, source_pointer=None, meta=None)[source]

Bases: aiohttp_json_api.errors.Error

HTTP 410 Gone.

The resource is no longer available at the requested URI and no redirection will be given.

status = 410
exception aiohttp_json_api.errors.HTTPPreConditionFailed(*, id_=None, about='', code=None, title=None, detail='', source_parameter=None, source_pointer=None, meta=None)[source]

Bases: aiohttp_json_api.errors.Error

HTTP 412 Precondition failed.

The server does not meet one of the preconditions specified by the client.

status = 412
exception aiohttp_json_api.errors.HTTPUnsupportedMediaType(*, id_=None, about='', code=None, title=None, detail='', source_parameter=None, source_pointer=None, meta=None)[source]

Bases: aiohttp_json_api.errors.Error

HTTP 415 Unsupported media type.

The client provided data with a media type that the server does not support.

status = 415
exception aiohttp_json_api.errors.HTTPUnprocessableEntity(*, id_=None, about='', code=None, title=None, detail='', source_parameter=None, source_pointer=None, meta=None)[source]

Bases: aiohttp_json_api.errors.Error

HTTP 422 Unprocessable entity.

The request was formatted correctly but cannot be processed in its current form. Often used when the specified parameters fail validation errors.

WebDAV - RFC 4918

status = 422
exception aiohttp_json_api.errors.HTTPLocked(*, id_=None, about='', code=None, title=None, detail='', source_parameter=None, source_pointer=None, meta=None)[source]

Bases: aiohttp_json_api.errors.Error

HTTP 423 Locked.

The requested resource was found but has been locked and will not be returned.

WebDAV - RFC 4918

status = 423
exception aiohttp_json_api.errors.HTTPFailedDependency(*, id_=None, about='', code=None, title=None, detail='', source_parameter=None, source_pointer=None, meta=None)[source]

Bases: aiohttp_json_api.errors.Error

HTTP 424 Failed dependency.

The request failed due to a failure of a previous request.

WebDAV - RFC 4918

status = 424
exception aiohttp_json_api.errors.HTTPTooManyRequests(*, id_=None, about='', code=None, title=None, detail='', source_parameter=None, source_pointer=None, meta=None)[source]

Bases: aiohttp_json_api.errors.Error

HTTP 429 Too many requests.

The user has sent too many requests in a given amount of time (“rate limiting”).

Additional HTTP Status Codes - RFC 6585

status = 429
exception aiohttp_json_api.errors.HTTPInternalServerError(*, id_=None, about='', code=None, title=None, detail='', source_parameter=None, source_pointer=None, meta=None)[source]

Bases: aiohttp_json_api.errors.Error

HTTP 500 Internal server error.

A generic status for an error in the server itself.

status = 500
exception aiohttp_json_api.errors.HTTPNotImplemented(*, id_=None, about='', code=None, title=None, detail='', source_parameter=None, source_pointer=None, meta=None)[source]

Bases: aiohttp_json_api.errors.Error

HTTP 501 Not implemented.

The server cannot respond to the request. This usually implies that the server could possibly support the request in the future — otherwise a 4xx status may be more appropriate.

status = 501
exception aiohttp_json_api.errors.HTTPBadGateway(*, id_=None, about='', code=None, title=None, detail='', source_parameter=None, source_pointer=None, meta=None)[source]

Bases: aiohttp_json_api.errors.Error

HTTP 502 Bad gateway.

The server is acting as a proxy and did not receive an acceptable response from the upstream server.

status = 502
exception aiohttp_json_api.errors.HTTPServiceUnavailable(*, id_=None, about='', code=None, title=None, detail='', source_parameter=None, source_pointer=None, meta=None)[source]

Bases: aiohttp_json_api.errors.Error

HTTP 503 Service unavailable.

The server is down and is not accepting requests.

status = 503
exception aiohttp_json_api.errors.HTTPGatewayTimeout(*, id_=None, about='', code=None, title=None, detail='', source_parameter=None, source_pointer=None, meta=None)[source]

Bases: aiohttp_json_api.errors.Error

HTTP 504 Gateway timeout.

The server is acting as a proxy and did not receive a response from the upstream server.

status = 504
exception aiohttp_json_api.errors.HTTPVariantAlsoNegotiates(*, id_=None, about='', code=None, title=None, detail='', source_parameter=None, source_pointer=None, meta=None)[source]

Bases: aiohttp_json_api.errors.Error

HTTP 506 Variant also negotiates.

Transparent content negotiation for the request results in a circular reference.

status = 506
exception aiohttp_json_api.errors.HTTPInsufficientStorage(*, id_=None, about='', code=None, title=None, detail='', source_parameter=None, source_pointer=None, meta=None)[source]

Bases: aiohttp_json_api.errors.Error

HTTP 507 Insufficient storage.

The user or server does not have sufficient storage quota to fulfill the request.

WebDAV - RFC 4918

status = 507
exception aiohttp_json_api.errors.HTTPNotExtended(*, id_=None, about='', code=None, title=None, detail='', source_parameter=None, source_pointer=None, meta=None)[source]

Bases: aiohttp_json_api.errors.Error

HTTP 510 Not extended.

Further extensions to the request are necessary for it to be fulfilled.

status = 510
exception aiohttp_json_api.errors.ValidationError(*, id_=None, about='', code=None, title=None, detail='', source_parameter=None, source_pointer=None, meta=None)[source]

Bases: aiohttp_json_api.errors.HTTPBadRequest

JSON API validation error. HTTP 400 Bad request.

Raised, if the structure of a json document in a request body is invalid.

Please note, that this does not include semantic errors, like an unknown typename.

This type of exception is used often in the jsonapi.validator and jsonapi.validation modules.

Seealso:http://jsonapi.org/format/#document-structure
exception aiohttp_json_api.errors.InvalidType(*, id_=None, about='', code=None, title=None, detail='', source_parameter=None, source_pointer=None, meta=None)[source]

Bases: aiohttp_json_api.errors.ValidationError

JSON API invalid type error. HTTP 400 Bad request.

Raised if an input value (part of a JSON API document) has the wrong type.

This type of exception is often raised during decoding.

Seealso:http://jsonapi.org/format/#document-structure
exception aiohttp_json_api.errors.InvalidValue(*, id_=None, about='', code=None, title=None, detail='', source_parameter=None, source_pointer=None, meta=None)[source]

Bases: aiohttp_json_api.errors.ValidationError

JSON API invalid value error. HTTP 400 Bad request.

Raised if an input value (part of a JSON API document) has an invalid value.

Seealso:http://jsonapi.org/format/#document-structure
exception aiohttp_json_api.errors.UnresolvableIncludePath(path, **kwargs)[source]

Bases: aiohttp_json_api.errors.HTTPBadRequest

JSON API unresolvable include path error. HTTP 400 Bad request.

Raised if an include path does not exist. The include path is part of the include query argument. (An include path is invalid, if a relationship mentioned in it is not defined on a resource).

Seealso:http://jsonapi.org/format/#fetching-includes
exception aiohttp_json_api.errors.UnsortableField(type, field, **kwargs)[source]

Bases: aiohttp_json_api.errors.HTTPBadRequest

JSON API unsortable field. HTTP 400 Bad request.

If a field is used as sort key, but sorting is not supported on this field.

Seealso:http://jsonapi.org/format/#fetching-sorting
exception aiohttp_json_api.errors.UnsortableField(type, field, **kwargs)[source]

Bases: aiohttp_json_api.errors.HTTPBadRequest

JSON API unsortable field. HTTP 400 Bad request.

If a field is used as sort key, but sorting is not supported on this field.

Seealso:http://jsonapi.org/format/#fetching-sorting
exception aiohttp_json_api.errors.ResourceNotFound(type, id, **kwargs)[source]

Bases: aiohttp_json_api.errors.HTTPNotFound

JSON API resource not found error. HTTP 404 Not found.

Raised, if a resource does not exist.

Handlers.

aiohttp_json_api.handlers.get_collection(request)[source]

Fetch resources collection, render JSON API document and return response.

Uses the query_collection() method of the schema to query the resources in the collection.

Seealso:http://jsonapi.org/format/#fetching
aiohttp_json_api.handlers.post_resource(request)[source]

Create resource, render JSON API document and return response.

Uses the create_resource() method of the schema to create a new resource.

Seealso:http://jsonapi.org/format/#crud-creating
aiohttp_json_api.handlers.get_resource(request)[source]

Get single resource, render JSON API document and return response.

Uses the query_resource() method of the schema to query the requested resource.

Seealso:http://jsonapi.org/format/#fetching-resources
aiohttp_json_api.handlers.patch_resource(request)[source]

Update resource (via PATCH), render JSON API document and return response.

Uses the update_resource() method of the schema to update a resource.

Seealso:http://jsonapi.org/format/#crud-updating
aiohttp_json_api.handlers.delete_resource(request)[source]

Remove resource.

Uses the delete_resource() method of the schema to delete a resource.

Seealso:http://jsonapi.org/format/#crud-deleting
aiohttp_json_api.handlers.get_relationship(request)[source]

Get relationships of resource.

Parameters:request (Request) – Request instance
Returns:Response
aiohttp_json_api.handlers.post_relationship(request)[source]

Create relationships of resource.

Uses the add_relationship() method of the schemato add new relationships.

Seealso:http://jsonapi.org/format/#crud-updating-relationships
aiohttp_json_api.handlers.patch_relationship(request)[source]

Update relationships of resource.

Uses the update_relationship() method of the schema to update the relationship.

Seealso:http://jsonapi.org/format/#crud-updating-relationships
aiohttp_json_api.handlers.delete_relationship(request)[source]

Remove relationships of resource.

Uses the delete_relationship() method of the schema to update the relationship.

Seealso:http://jsonapi.org/format/#crud-updating-relationships

Get related resources.

Uses the query_relative() method of the schema to query the related resource.

Seealso:http://jsonapi.org/format/#fetching

Helpers.

aiohttp_json_api.helpers.best_match(supported, header)[source]

Return mime-type with the highest quality (‘q’) from list of candidates. Takes a list of supported mime-types and finds the best match for all the media-ranges listed in header. The value of header must be a string that conforms to the format of the HTTP Accept: header. The value of ‘supported’ is a list of mime-types. The list of supported mime-types should be sorted in order of increasing desirability, in case of a situation where there is a tie.

Cherry-picked from python-mimeparse and improved.

>>> best_match(['application/xbel+xml', 'text/xml'],
               'text/*;q=0.5,*/*; q=0.1')
('text/xml', ('text', '*', {'q': '0.5'}))
Return type:Tuple[str, Optional[Tuple[str, str, Dict[str, str]]]]
aiohttp_json_api.helpers.ensure_collection(value, exclude=())[source]

Ensure value is collection.

aiohttp_json_api.helpers.first(iterable, default=None, key=None)[source]

Return first element of iterable.

Return first element of iterable that evaluates to True, else return None or optional default.

>>> first([0, False, None, [], (), 42])
42
>>> first([0, False, None, [], ()]) is None
True
>>> first([0, False, None, [], ()], default='ohai')
'ohai'
>>> import re
>>> m = first(re.match(regex, 'abc') for regex in ['b.*', 'a(.*)'])
>>> m.group(1)
'bc'

The optional key argument specifies a one-argument predicate function like that used for filter(). The key argument, if supplied, should be in keyword form. For example, finding the first even number in an iterable:

>>> first([1, 1, 3, 4, 5], key=lambda x: x % 2 == 0)
4

Contributed by Hynek Schlawack, author of the original standalone module

aiohttp_json_api.helpers.get_mime_type_params(mime_type)[source]
aiohttp_json_api.helpers.get_processors(obj, tag, field, default=None)[source]
aiohttp_json_api.helpers.get_router_resource(app, resource)[source]

Return route of JSON API application for resource.

aiohttp_json_api.helpers.is_collection(obj, exclude=())[source]

Return True if obj is a collection type.

aiohttp_json_api.helpers.is_generator(obj)[source]

Return True if obj is a generator.

aiohttp_json_api.helpers.is_indexable_but_not_string(obj)[source]

Return True if obj is indexable but isn’t a string.

aiohttp_json_api.helpers.is_iterable_but_not_string(obj)[source]

Return True if obj is an iterable object that isn’t a string.

aiohttp_json_api.helpers.make_sentinel(name='_MISSING', var_name=None)[source]

Create sentinel instance.

Creates and returns a new instance of a new class, suitable for usage as a “sentinel”, a kind of singleton often used to indicate a value is missing when None is a valid input.

>>> make_sentinel(var_name='_MISSING')
_MISSING

The most common use cases here in project are as default values for optional function arguments, partly because of its less-confusing appearance in automatically generated documentation. Sentinels also function well as placeholders in queues and linked lists.

Note

By design, additional calls to make_sentinel with the same values will not produce equivalent objects.

>>> make_sentinel('TEST') == make_sentinel('TEST')
False
>>> type(make_sentinel('TEST')) == type(make_sentinel('TEST'))
False
Parameters:
  • name (str) – Name of the Sentinel
  • var_name (str) – Set this name to the name of the variable in its respective module enable pickleability.
aiohttp_json_api.helpers.quality_and_fitness_parsed(mime_type, parsed_ranges)[source]

Find the best match for a mime-type amongst parsed media-ranges.

Find the best match for a given mime-type against a list of media_ranges that have already been parsed by parse_media_range(). Returns a tuple of the fitness value and the value of the ‘q’ quality parameter of the best match, or (-1, 0) if no match was found. Just as for quality_parsed(), ‘parsed_ranges’ must be a list of parsed media ranges.

Cherry-picked from python-mimeparse and improved.

Return type:Tuple[Tuple[float, int], Optional[Tuple[str, str, Dict[str, str]]]]
Extended JSONPointer from python-json-pointer
class aiohttp_json_api.jsonpointer.JSONPointer(pointer)[source]

Bases: jsonpointer.JsonPointer

Middleware.

aiohttp_json_api.middleware.jsonapi_middleware(app, handler)[source]

Middleware for handling JSON API errors.

Application registry.

class aiohttp_json_api.registry.Registry(**kwargs)[source]

Bases: collections.UserDict

JSON API application registry.

This is a dictionary created on JSON API application set up. It contains a mapping between types, resource classes and schemas.

data
ensure_identifier(obj, asdict=False)[source]

Return the identifier object for the resource.

(ResourceID)

>>> registry.ensure_identifier({'type': 'something', 'id': 123})
ResourceID(type='something', id='123')
Parameters:
  • obj – A two tuple (typename, id), a resource object or a resource document, which contains the id and type key {"type": ..., "id": ...}.
  • asdict (bool) – Return ResourceID as dictionary if true
Return type:

Union[ResourceID, Dict[str, str]]

Base schema

This module contains the base schema which implements the encoding, decoding, validation and update operations based on fields.

class aiohttp_json_api.schema.BaseSchema(context)[source]

Bases: aiohttp_json_api.abc.schema.SchemaABC

A schema defines how we can serialize a resource and patch it. It also allows to patch a resource. All in all, it defines a controller for a type in the JSON API.

If you want, you can implement your own request handlers and only use the schema for validation and serialization.

static default_getter(resource, **kwargs)[source]
static default_setter(resource, data, sp, **kwargs)[source]
deserialize_resource(data, sp, *, expected_id=None, validate=True, validation_steps=None)[source]

Decodes the JSON API resource object data and returns a dictionary which maps the key of a field to its decoded input data.

Parameters:
  • data – The received JSON API resource object
  • sp (JSONPointer) – The JSON pointer to the source of data.
  • context (JSONAPIContext) – Request context instance
  • expected_id (str) – If passed, then ID of resource will be compared with this value. This is required in update methods
  • validate (bool) – Is validation required?
  • validation_steps (tuple) – Required validation steps
Return type:

OrderedDict

Returns:

An ordered dictionary which maps a fields key to a two tuple (data, sp) which contains the input data and the source pointer to it.

classmethod get_field(key)[source]
Return type:FieldABC
static get_object_id(resource)[source]

Can be overridden.

Returns the id (string) of the resource. The default implementation looks for a property resource.id, an id method resource.id(), resource.get_id() or a key resource["id"].

Parameters:resource – A resource object
Return type:str
Returns:The string representation of ID of the resource
classmethod get_relationship_field(relation_name, source_parameter=None)[source]
get_value(field, resource, **kwargs)[source]
map_data_to_schema(data)[source]
Return type:Dict[~KT, ~VT]
opts = <aiohttp_json_api.abc.schema.SchemaOpts object>
post_validate_resource(data)[source]

Validates the decoded data of JSON API resource object.

Parameters:
pre_validate_field(field, data, sp)[source]

Validates the input data for a field, before it is deserialized. If the field has nested fields, the nested fields are validated first.

Parameters:
pre_validate_resource(data, sp, *, expected_id=None)[source]

Validates a JSON API resource object received from an API client:

schema.pre_validate_resource(
    data=request.json["data"], sp="/data"
)
Parameters:
  • data – The received JSON API resource object
  • sp (JSONPointer) – The JSON pointer to the source of data.
  • context (JSONAPIContext) – Request context instance
  • expected_id (str) – If passed, then ID of resrouce will be compared with this value. This is required in update methods
serialize_relationship(relation_name, resource, *, pagination=None)[source]

Creates the JSON API relationship object of the relationship relation_name.

Parameters:
  • relation_name (str) – The name of the relationship
  • resource – A resource object
  • pagination (PaginationABC) – Describes the pagination in case of a to-many relationship.
Return type:

dict

Returns:

The JSON API relationship object for the relationship relation_name of the resource

serialize_resource(resource, **kwargs)[source]
Parameters:resource – A resource object
Return type:MutableMapping
set_value(field, resource, data, sp, **kwargs)[source]

Useful typing.

aiohttp_json_api.typings.Callee = typing.Union[typing.Callable, typing.Coroutine]

Type for callable or co-routine

aiohttp_json_api.typings.RequestFields

alias of typing.MutableMapping

aiohttp_json_api.typings.RequestFilters

alias of typing.MutableMapping

aiohttp_json_api.typings.RequestIncludes

alias of typing.Tuple

aiohttp_json_api.typings.RequestSorting

alias of typing.MutableMapping

aiohttp_json_api.typings.ResourceIdentifier = typing.Union[aiohttp_json_api.common.ResourceID, typing.Dict[str, str]]

Type for Resource identifier

Utilities related to JSON API.

aiohttp_json_api.utils.error_to_response(request, error)[source]

Convert an Error or ErrorList to JSON API response.

Parameters:
  • request (Request) – The web request instance.
  • ErrorList] error (typing.Union[Error,) – The error, which is converted into a response.
Return type:

Response

aiohttp_json_api.utils.get_compound_documents(resources, ctx)[source]

Get compound documents of resources.

Fetches the relationship paths paths.

Parameters:
  • resources – A list with the primary data (resources) of the compound response document.
  • ctx – A web Request context
Returns:

A two tuple with a list of the included resources and a dictionary, which maps each resource (primary and included) to a set with the names of the included relationships.

aiohttp_json_api.utils.jsonapi_response(data, *, status=200, reason=None, headers=None, dumps=None)[source]

Return JSON API response.

Parameters:
  • data – Rendered JSON API document
  • status – HTTP status of JSON API response
  • reason – Readable reason of error response
  • headers – Headers
  • dumps – Custom JSON dumps callable
Returns:

Response instance

aiohttp_json_api.utils.render_document(data, included, ctx, *, pagination=None, links=None)[source]

Render JSON API document.

Parameters:
  • data – One or many resources
  • included – Compound documents
  • ctx – Request context
  • pagination – Pagination instance
  • links – Additional links
Return type:

MutableMapping[~KT, ~VT]

Returns:

Rendered JSON API document

aiohttp_json_api.utils.serialize_resource(resource, ctx)[source]

Serialize resource by schema.

Parameters:
  • resource – Resource instance
  • ctx – Request context
Returns:

Serialized resource

aiohttp_json_api.utils.validate_uri_resource_id(schema, resource_id)[source]

Validate resource ID from URI.

Parameters:
  • schema – Resource schema
  • resource_id – Resource ID

Module contents

JSON API implementation for aiohttp.

aiohttp_json_api.setup_app_registry(app, registry_class, config)[source]

Set up JSON API application registry.

aiohttp_json_api.setup_custom_handlers(custom_handlers)[source]

Set up default and custom handlers for JSON API application.

aiohttp_json_api.setup_jsonapi(app, config, *, base_path='/api', version='1.0', meta=None, context_cls=None, registry_class=None, custom_handlers=None, log_errors=True, routes_namespace=None)[source]

Set up JSON API in aiohttp application.

This function will setup resources, handlers and middleware.

Parameters:
  • app (Application) – Application instance
  • controllers (Sequence[DefaultController]) – List of controllers to register in JSON API
  • base_path (str) – Prefix of JSON API routes paths
  • version (str) – JSON API version (used in jsonapi key of document)
  • meta (dict) – Meta information will added to response (meta key of document)
  • context_cls – Override of JSONAPIContext class (must be subclass of JSONAPIContext)
  • registry_class – Override of Registry class (must be subclass of Registry)
  • custom_handlers

    Sequence or mapping with overrides of default JSON API handlers.

    If your custom handlers named in conform with convention of this application, then pass it as sequence:

    custom_handlers=(get_collection, patch_resource)
    

    If you have custom name of these handlers, then pass it as mapping:

    custom_handlers={
        'get_collection': some_handler_for_get_collection,
        'patch_resource': another_handler_to_patch_resource
    }
    
  • log_errors (bool) – Log errors handled by jsonapi_middleware()
  • routes_namespace (str) – Namespace of JSON API application routes
Returns:

aiohttp Application instance with configured JSON API

Return type:

Application

aiohttp_json_api.setup_resources(app, base_path, handlers, routes_namespace)[source]

Set up JSON API application resources.

aiohttp_json_api.abc package

Submodules

class aiohttp_json_api.abc.contoller.ControllerABC(context)[source]

Bases: abc.ABC

add_relationship(field, resource, data, sp, **kwargs)[source]

Adds the members specified in the JSON API relationship object data to the relationship, unless the relationships already exist.

Parameters:
  • field (FieldABC) – Relationship field.
  • resource – Resource instance fetched by fetch_resource() in handler.
  • data (str) – The JSON API relationship object with the update information.
  • sp (JSONPointer) – The JSON pointer to the source of data.
create_resource(data, **kwargs)[source]

Creates a new resource instance and returns it. You should override this method.

The default implementation passes the attributes, (dereferenced) relationships and meta data from the JSON API resource object data to the constructor of the resource class. If the primary key is writable on creation and a member of data, it is also passed to the constructor.

Parameters:data (dict) – The JSON API deserialized data by schema.
static default_add(resource, data, sp, **kwargs)[source]
static default_include(resources, **kwargs)[source]
static default_query(resource, **kwargs)[source]
static default_remove(resource, data, sp, **kwargs)[source]
delete_resource(resource_id, **kwargs)[source]

Deletes the resource. You must overridde this method.

Parameters:
  • resource_id – The id of the resource or the resource instance
  • context (JSONAPIContext) – Request context instance
fetch_compound_documents(field, resources, *, rest_path=None, **kwargs)[source]

Fetches the related resources. The default method uses the controller’s default_include(). Can be overridden.

Parameters:
  • field (FieldABC) – Relationship field.
  • resources – A list of resources.
  • context (JSONAPIContext) – Request context instance.
  • rest_path (list) – The name of the relationships of the returned relatives, which will also be included.
Return type:

list

Returns:

A list with the related resources. The list is empty or has exactly one element in the case of to-one relationships. If to-many relationships are paginated, the relatives from the first page should be returned.

fetch_resource(resource_id, **kwargs)[source]
query_collection(**kwargs)[source]

Fetches a subset of the collection represented by this schema. Must be overridden.

Parameters:context (JSONAPIContext) – Request context instance.
query_relatives(field, resource, **kwargs)[source]

Controller for the related endpoint of the relationship with then name relation_name.

Parameters:
query_resource(resource_id, **kwargs)[source]

Fetches the resource with the id id_. Must be overridden.

Parameters:
  • resource_id (str) – The id of the requested resource.
  • context (JSONAPIContext) – A request context instance
Raises:

ResourceNotFound – If there is no resource with the given id_.

remove_relationship(field, resource, data, sp, **kwargs)[source]

Deletes the members specified in the JSON API relationship object data from the relationship.

Parameters:
  • field (FieldABC) – Relationship field.
  • resource – Resource instance fetched by fetch_resource() in handler.
  • data (str) – The JSON API relationship object with the update information.
  • sp (JSONPointer) – The JSON pointer to the source of data.
  • context (JSONAPIContext) – Request context instance.
update_relationship(field, resource, data, sp, **kwargs)[source]

Updates the relationship with the JSON API name relation_name.

Parameters:
  • field (FieldABC) – Relationship field.
  • resource – Resource instance fetched by fetch_resource() in handler.
  • data (str) – The JSON API relationship object with the update information.
  • sp (JSONPointer) – The JSON pointer to the source of data.
update_resource(resource_id, data, sp, **kwargs)[source]

Updates an existing resource. You should overridde this method in order to save the changes in the database.

The default implementation uses the BaseField descriptors to update the resource.

Parameters:
  • resource_id – The id of the resource
  • data (dict) – The JSON API resource object with the update information
  • sp (JSONPointer) – The JSON pointer to the source of data.
  • context (JSONAPIContext) – Request context instance
class aiohttp_json_api.abc.contoller.ControllerMeta(name, bases, attrs)[source]

Bases: abc.ABCMeta, aiohttp_json_api.abc.processors.MetaProcessors

Field abstract base class
class aiohttp_json_api.abc.field.FieldABC[source]

Bases: abc.ABC

deserialize(schema, data, sp, **kwargs)[source]

Deserialize the raw data from the JSON API input document and returns it.

key
Return type:str
mapped_key
Return type:Optional[str]
name
Return type:Optional[str]
post_validate(schema, data, sp)[source]

Validates the decoded input data for this field. This method is called after deserialize().

Parameters:
  • schema (BaseSchema) – The schema this field has been defined on.
  • data – The decoded input data
  • sp (JSONPointer) – A JSON pointer to the source of data.
  • context (JSONAPIContext) – A JSON API request context instance
pre_validate(schema, data, sp)[source]

Validates the raw JSON API input for this field. This method is called before deserialize().

Parameters:
  • schema (BaseSchema) – The schema this field has been defined on.
  • data – The raw input data
  • sp (JSONPointer) – A JSON pointer to the source of data.
  • context (JSONAPIContext) – A JSON API request context instance
serialize(schema, data, **kwargs)[source]

Serialize the passed data.

sp
Return type:JSONPointer
class aiohttp_json_api.abc.processors.MetaProcessors[source]

Bases: object

Schema abstract base classes
class aiohttp_json_api.abc.schema.SchemaABC(context)[source]

Bases: abc.ABC

OPTIONS_CLASS

alias of SchemaOpts

class Options[source]

Bases: object

static default_getter(resource, **kwargs)[source]
static default_setter(resource, data, sp, **kwargs)[source]
deserialize_resource(data, sp, *, expected_id=None, validate=True, validation_steps=None)[source]

Decodes the JSON API resource object data and returns a dictionary which maps the key of a field to its decoded input data.

Parameters:
  • data – The received JSON API resource object
  • sp (JSONPointer) – The JSON pointer to the source of data.
  • context (JSONAPIContext) – Request context instance
  • expected_id (str) – If passed, then ID of resource will be compared with this value. This is required in update methods
  • validate (bool) – Is validation required?
  • validation_steps (tuple) – Required validation steps
Return type:

OrderedDict

Returns:

An ordered dictionary which maps a fields key to a two tuple (data, sp) which contains the input data and the source pointer to it.

classmethod get_field(key)[source]
Return type:FieldABC
classmethod get_relationship_field(relation_name, source_parameter=None)[source]
get_value(field, resource, **kwargs)[source]
opts = <aiohttp_json_api.abc.schema.SchemaOpts object>
post_validate_resource(data)[source]

Validates the decoded data of JSON API resource object.

Parameters:
pre_validate_field(field, data, sp)[source]

Validates the input data for a field, before it is deserialized. If the field has nested fields, the nested fields are validated first.

Parameters:
pre_validate_resource(data, sp, *, expected_id=None)[source]

Validates a JSON API resource object received from an API client:

schema.pre_validate_resource(
    data=request.json["data"], sp="/data"
)
Parameters:
  • data – The received JSON API resource object
  • sp (JSONPointer) – The JSON pointer to the source of data.
  • context (JSONAPIContext) – Request context instance
  • expected_id (str) – If passed, then ID of resrouce will be compared with this value. This is required in update methods
serialize_relationship(relation_name, resource, *, pagination=None)[source]

Creates the JSON API relationship object of the relationship relation_name.

Parameters:
  • relation_name (str) – The name of the relationship
  • resource – A resource object
  • pagination (PaginationABC) – Describes the pagination in case of a to-many relationship.
Return type:

dict

Returns:

The JSON API relationship object for the relationship relation_name of the resource

serialize_resource(resource, **kwargs)[source]
set_value(field, resource, data, sp, **kwargs)[source]
class aiohttp_json_api.abc.schema.SchemaMeta(name, bases, attrs)[source]

Bases: abc.ABCMeta, aiohttp_json_api.abc.processors.MetaProcessors

class aiohttp_json_api.abc.schema.SchemaOpts(options)[source]

Bases: object

class Meta options for the SchemaABC. Defines defaults.

aiohttp_json_api.abc.schema.issubclass(subclass, baseclass)[source]

Just like the built-in issubclass(), this function checks whether subclass is inherited from baseclass. Unlike the built-in function, this issubclass will simply return False if either argument is not suitable (e.g., if subclass is not an instance of type), instead of raising TypeError.

Args:
subclass (type): The target class to check. baseclass (type): The base class subclass will be checked against.
>>> class MyObject(object): pass
...
>>> issubclass(MyObject, object)  # always a fun fact
True
>>> issubclass('hi', 'friend')
False

Module contents

aiohttp_json_api.fields package

Submodules

Fields

Note

Always remember that you can model the JSON API completly with the fields in base_fields.

This module contains fields for several standard Python types and classes from the standard library.

class aiohttp_json_api.fields.attributes.String(*, allow_blank=False, regex=None, choices=None, min_length=None, max_length=None, **kwargs)[source]

Bases: aiohttp_json_api.fields.base.Attribute

deserialize(schema, data, sp, **kwargs)[source]

Deserialize the raw data from the JSON API input document and returns it.

pre_validate(schema, data, sp)[source]

Validates the raw JSON API input for this field. This method is called before deserialize().

Parameters:
  • schema (BaseSchema) – The schema this field has been defined on.
  • data – The raw input data
  • sp (JSONPointer) – A JSON pointer to the source of data.
  • context (JSONAPIContext) – A JSON API request context instance
serialize(schema, data, **kwargs)[source]

Serialize the passed data.

class aiohttp_json_api.fields.attributes.Integer(*, gte=None, lte=None, gt=None, lt=None, **kwargs)[source]

Bases: aiohttp_json_api.fields.base.Attribute

deserialize(schema, data, sp, **kwargs)[source]

Deserialize the raw data from the JSON API input document and returns it.

pre_validate(schema, data, sp)[source]

Validates the raw JSON API input for this field. This method is called before deserialize().

Parameters:
  • schema (BaseSchema) – The schema this field has been defined on.
  • data – The raw input data
  • sp (JSONPointer) – A JSON pointer to the source of data.
  • context (JSONAPIContext) – A JSON API request context instance
serialize(schema, data, **kwargs)[source]

Serialize the passed data.

class aiohttp_json_api.fields.attributes.Float(*, gte=None, lte=None, gt=None, lt=None, **kwargs)[source]

Bases: aiohttp_json_api.fields.base.Attribute

deserialize(schema, data, sp, **kwargs)[source]

Deserialize the raw data from the JSON API input document and returns it.

pre_validate(schema, data, sp)[source]

Validates the raw JSON API input for this field. This method is called before deserialize().

Parameters:
  • schema (BaseSchema) – The schema this field has been defined on.
  • data – The raw input data
  • sp (JSONPointer) – A JSON pointer to the source of data.
  • context (JSONAPIContext) – A JSON API request context instance
serialize(schema, data, **kwargs)[source]

Serialize the passed data.

class aiohttp_json_api.fields.attributes.Complex(*, meta=False, load_only=False, **kwargs)[source]

Bases: aiohttp_json_api.fields.base.Attribute

Encodes a complex number as JSON object with a real and imag member:

{"real": 1.2, "imag": 42}
deserialize(schema, data, sp, **kwargs)[source]

Deserialize the raw data from the JSON API input document and returns it.

pre_validate(schema, data, sp)[source]

Validates the raw JSON API input for this field. This method is called before deserialize().

Parameters:
  • schema (BaseSchema) – The schema this field has been defined on.
  • data – The raw input data
  • sp (JSONPointer) – A JSON pointer to the source of data.
  • context (JSONAPIContext) – A JSON API request context instance
serialize(schema, data, **kwargs)[source]

Serialize the passed data.

class aiohttp_json_api.fields.attributes.Decimal(*, gte=None, lte=None, gt=None, lt=None, **kwargs)[source]

Bases: aiohttp_json_api.fields.base.Attribute

Encodes and decodes a decimal.Decimal as a string.

deserialize(schema, data, sp, **kwargs)[source]

Deserialize the raw data from the JSON API input document and returns it.

pre_validate(schema, data, sp)[source]

Validates the raw JSON API input for this field. This method is called before deserialize().

Parameters:
  • schema (BaseSchema) – The schema this field has been defined on.
  • data – The raw input data
  • sp (JSONPointer) – A JSON pointer to the source of data.
  • context (JSONAPIContext) – A JSON API request context instance
serialize(schema, data, **kwargs)[source]

Serialize the passed data.

class aiohttp_json_api.fields.attributes.Fraction(*, min=None, max=None, **kwargs)[source]

Bases: aiohttp_json_api.fields.base.Attribute

Stores a fractions.Fraction in an object with a numerator and denominator member:

# 1.5
{"numerator": 2, "denominator": 3}
Parameters:
  • min (float) – The fraction must be greater or equal than this value.
  • max (float) – The fraction must be less or equal than this value.
deserialize(schema, data, sp, **kwargs)[source]

Deserialize the raw data from the JSON API input document and returns it.

pre_validate(schema, data, sp)[source]

Validates the raw JSON API input for this field. This method is called before deserialize().

Parameters:
  • schema (BaseSchema) – The schema this field has been defined on.
  • data – The raw input data
  • sp (JSONPointer) – A JSON pointer to the source of data.
  • context (JSONAPIContext) – A JSON API request context instance
serialize(schema, data, **kwargs)[source]

Serialize the passed data.

class aiohttp_json_api.fields.attributes.DateTime(*, allow_blank=False, **kwargs)[source]

Bases: aiohttp_json_api.fields.base.Attribute

Stores a datetime.datetime in ISO-8601 as recommended in http://jsonapi.org/recommendations/#date-and-time-fields.

deserialize(schema, data, sp, **kwargs)[source]

Deserialize the raw data from the JSON API input document and returns it.

pre_validate(schema, data, sp)[source]

Validates the raw JSON API input for this field. This method is called before deserialize().

Parameters:
  • schema (BaseSchema) – The schema this field has been defined on.
  • data – The raw input data
  • sp (JSONPointer) – A JSON pointer to the source of data.
  • context (JSONAPIContext) – A JSON API request context instance
serialize(schema, data, **kwargs)[source]

Serialize the passed data.

class aiohttp_json_api.fields.attributes.TimeDelta(*, min=None, max=None, **kwargs)[source]

Bases: aiohttp_json_api.fields.base.Attribute

Stores a datetime.timedelta as total number of seconds.

Parameters:
  • min (datetime.timedelta) – The timedelta must be greater or equal than this value.
  • max (datetime.timedelta) – The timedelta must be less or equal than this value.
deserialize(schema, data, sp, **kwargs)[source]

Deserialize the raw data from the JSON API input document and returns it.

pre_validate(schema, data, sp)[source]

Validates the raw JSON API input for this field. This method is called before deserialize().

Parameters:
  • schema (BaseSchema) – The schema this field has been defined on.
  • data – The raw input data
  • sp (JSONPointer) – A JSON pointer to the source of data.
  • context (JSONAPIContext) – A JSON API request context instance
serialize(schema, data, **kwargs)[source]

Serialize the passed data.

class aiohttp_json_api.fields.attributes.UUID(*, version=None, **kwargs)[source]

Bases: aiohttp_json_api.fields.base.Attribute

Encodes and decodes a uuid.UUID.

Parameters:version (int) – The required version of the UUID.
deserialize(schema, data, sp, **kwargs)[source]

Deserialize the raw data from the JSON API input document and returns it.

pre_validate(schema, data, sp)[source]

Validates the raw JSON API input for this field. This method is called before deserialize().

Parameters:
  • schema (BaseSchema) – The schema this field has been defined on.
  • data – The raw input data
  • sp (JSONPointer) – A JSON pointer to the source of data.
  • context (JSONAPIContext) – A JSON API request context instance
serialize(schema, data, **kwargs)[source]

Serialize the passed data.

class aiohttp_json_api.fields.attributes.Boolean(**kwargs)[source]

Bases: aiohttp_json_api.fields.base.Attribute

Ensures that the input is a bool.

pre_validate(schema, data, sp)[source]

Validates the raw JSON API input for this field. This method is called before deserialize().

Parameters:
  • schema (BaseSchema) – The schema this field has been defined on.
  • data – The raw input data
  • sp (JSONPointer) – A JSON pointer to the source of data.
  • context (JSONAPIContext) – A JSON API request context instance
serialize(schema, data, **kwargs)[source]

Serialize the passed data.

class aiohttp_json_api.fields.attributes.URI(*, meta=False, load_only=False, **kwargs)[source]

Bases: aiohttp_json_api.fields.base.Attribute

Parses the URI with rfc3986.urlparse() and returns the result.

deserialize(schema, data, sp, **kwargs)[source]

Deserialize the raw data from the JSON API input document and returns it.

pre_validate(schema, data, sp)[source]

Validates the raw JSON API input for this field. This method is called before deserialize().

Parameters:
  • schema (BaseSchema) – The schema this field has been defined on.
  • data – The raw input data
  • sp (JSONPointer) – A JSON pointer to the source of data.
  • context (JSONAPIContext) – A JSON API request context instance
serialize(schema, data, **kwargs)[source]

Serialize the passed data.

class aiohttp_json_api.fields.attributes.Email(**kwargs)[source]

Bases: aiohttp_json_api.fields.base.Attribute

Checks if a string is syntactically correct Email address.

pre_validate(schema, data, sp)[source]

Validates the raw JSON API input for this field. This method is called before deserialize().

Parameters:
  • schema (BaseSchema) – The schema this field has been defined on.
  • data – The raw input data
  • sp (JSONPointer) – A JSON pointer to the source of data.
  • context (JSONAPIContext) – A JSON API request context instance
serialize(schema, data, **kwargs)[source]

Serialize the passed data.

class aiohttp_json_api.fields.attributes.Dict(field, **kwargs)[source]

Bases: aiohttp_json_api.fields.base.Attribute

Realises a dictionary which has only values of a special field:

todo = Dict(String(regex=".*[A-z0-9].*"))

Note

If you deal with dictionaries with values of different types, you can still use the more general Attribute field to model this data.

You are not forced to use a Dict field! It is only a helper.

Parameters:field (Attribute) – All values of the dictionary are encoded and decoded using this field.
deserialize(schema, data, sp, **kwargs)[source]

Deserialize the raw data from the JSON API input document and returns it.

serialize(schema, data, **kwargs)[source]

Serialize the passed data.

class aiohttp_json_api.fields.attributes.List(field, min_length=0, max_length=None, **kwargs)[source]

Bases: aiohttp_json_api.fields.base.Attribute

Note

If your list has items of different types, you can still use the more general Attribute field to model this data.

You are not forced to use a List field! It is only a helper.

Parameters:field (Attribute) – All values of the list are encoded and decoded using this field.
deserialize(schema, data, sp, **kwargs)[source]

Deserialize the raw data from the JSON API input document and returns it.

pre_validate(schema, data, sp)[source]

Validates the raw JSON API input for this field. This method is called before deserialize().

Parameters:
  • schema (BaseSchema) – The schema this field has been defined on.
  • data – The raw input data
  • sp (JSONPointer) – A JSON pointer to the source of data.
  • context (JSONAPIContext) – A JSON API request context instance
serialize(schema, data, **kwargs)[source]

Serialize the passed data.

aiohttp_json_api.fields.attributes.Number

alias of aiohttp_json_api.fields.attributes.Float

aiohttp_json_api.fields.attributes.Str

alias of aiohttp_json_api.fields.attributes.String

aiohttp_json_api.fields.attributes.Bool

alias of aiohttp_json_api.fields.attributes.Boolean

Base fields

This module contains the definition for all basic fields. A field describes how data should be serialized to JSON and deserialized again and allows to define special methods for the different CRUD operations defined by the http://jsonapi.org specification.

You should only work with the following fields directly:

Todo

Add support for nested fields (aka embedded documents).

class aiohttp_json_api.fields.base.BaseField(*, name=None, mapped_key=None, allow_none=False, writable=<Event.ALWAYS: 15>, required=<Event.NEVER: 16>)[source]

Bases: aiohttp_json_api.abc.field.FieldABC

This class describes the base for all fields defined on a schema and knows how to serialize, deserialize and validate the field. A field is usually directly mapped to a property (mapped_key) on the resource object, but this mapping can be customized by implementing custom getters and setters (via decorators).

Hint

The inheritance of fields is currently implemented using the deepcopy() function from the standard library. This means, that in some rare cases, it is necessarily that you implement a custom __deepcopy__() method when you subclass BaseField.

Parameters:
  • name (str) – The name of the field in the JSON API document. If not explicitly given, it’s the same as key.
  • mapped_key (str) – The name of the associated property on the resource class. If not explicitly given, it’s the same as key.
  • allow_none (bool) – Allow to receive ‘null’ value
  • writable (Event) – Can be any Event enumeration value and describes in which CRUD context the field is writable.
  • required (Event) – Can be any Event enumeration value and describes in which CRUD context the field is required as input.
deserialize(schema, data, sp, **kwargs)[source]

Deserialize the raw data from the JSON API input document and returns it.

key
Return type:str
mapped_key
Return type:Optional[str]
name
Return type:Optional[str]
post_validate(schema, data, sp)[source]

Validates the decoded input data for this field. This method is called after deserialize().

Parameters:
  • schema (BaseSchema) – The schema this field has been defined on.
  • data – The decoded input data
  • sp (JSONPointer) – A JSON pointer to the source of data.
  • context (JSONAPIContext) – A JSON API request context instance
pre_validate(schema, data, sp)[source]

Validates the raw JSON API input for this field. This method is called before deserialize().

Parameters:
  • schema (BaseSchema) – The schema this field has been defined on.
  • data – The raw input data
  • sp (JSONPointer) – A JSON pointer to the source of data.
  • context (JSONAPIContext) – A JSON API request context instance
serialize(schema, data, **kwargs)[source]

Serialize the passed data.

sp
Return type:JSONPointer
class aiohttp_json_api.fields.base.Attribute(*, meta=False, load_only=False, **kwargs)[source]

Bases: aiohttp_json_api.fields.base.BaseField

An attribute is always part of the resource’s JSON API attributes object, unless meta is set, in which case the attribute appears in the resource’s meta object.

Per default, an attribute is mapped to a property on the resource object. You can customize this behaviour by implementing your own getter and setter:

class Article(BaseSchema):

    title = Attribute()

Does the same as:

class Article(BaseSchema):

    title = Attribute()

    @gets('title')
    def title(self, article):
        return article.title

    @sets('title')
    def title(self, article, new_title):
        article.title = new_title
        return None
Parameters:
  • meta (bool) – If true, the attribute is part of the resource’s meta object.
  • load_only (bool) – If True skip this field during serialization, otherwise its value will be present in the serialized data.
  • **kwargs – The init arguments for the BaseField.

Bases: aiohttp_json_api.fields.base.BaseField

class Article(BaseSchema):

    self = Link(route="some_route_name")

    author = ToOne()
    author_related = Link(
        route="another_route_name", link_of="author"
    )

In the http://jsonapi.org specification, a link is always part of a JSON API links object and is either a simple string or an object with the members href and meta.

A link is only readable and not mapped to a property on the resource object (You can however define a getter).

Parameters:
  • route (str) – A route name for the link
  • link_of (str) – If given, the link is part of the links object of the field with the key link_of and appears otherwise in the resource object’s links objects. E.g.: link_of = "author".
  • normalize (bool) – If true, the serialize method normalizes the link so that it is always an object.
serialize(schema, data, **kwargs)[source]

Normalizes the links object if wished.

class aiohttp_json_api.fields.base.Relationship(*, dereference=True, require_data=<Event.ALWAYS: 15>, foreign_types=None, links=None, id_field=None, **kwargs)[source]

Bases: aiohttp_json_api.fields.base.BaseField

Additionally to attributes and basic fields, we must know how to include the related resources in the case of relationships. This class defines the common interface of to-one and to-many relationships (links object, meta object, self link, related link, validation, …).

Relationships are always part of the resource’s JSON API relationships object.

See also

  • ToOne
  • ToMany
Parameters:
  • require_data (Event) – If true, the JSON API relationship object must contain the data member. Must be a Event instance.
  • dereference (bool) – If true, the relationship linkage is dereferenced automatic when decoded. (Implicitly sets require_data to Event.ALWAYS)
  • foreign_types (Sequence[str]) – A set with all foreign types. If given, this list is used to validate the input data. Leave it empty to allow all types.

Adds a new link to the links object.

pre_validate(schema, data, sp)[source]

Validates the raw JSON API input for this field. This method is called before deserialize().

Parameters:
  • schema (BaseSchema) – The schema this field has been defined on.
  • data – The raw input data
  • sp (JSONPointer) – A JSON pointer to the source of data.
  • context (JSONAPIContext) – A JSON API request context instance
relation = None
validate_relationship_object(schema, data, sp)[source]

Asserts that data is a JSON API relationship object.

  • data is a dictionary
  • data must be not empty
  • data may only have the members data, links or meta.
  • data must contain a data member, if dereference or require_data is true.
validate_resource_identifier(schema, data, sp)[source]

Asserts that data is a JSON API resource identifier with the correct type value.

Schema decorators

This module contains some decorators, which can be used instead of the descriptors on the BaseField class.

Todo

Allow to define a getter, …, includer for multiple fields:

@includes("author", "comments")
def include_all(self, article, **kargs):
    return (article.author, article.comments)

@validates("a", "b")
def validate_a_and_b(self, a, spa, b, spb, **kargs):
    if a > b:
        raise InvalidValue("a must be less than b", source_pointer=spa)
    return None

Todo

Use convention over configuration:

@gets("author")
def get_author(self, article, **kargs):
    return article.author_id

# Should be the same as

def get_author(self, article, **kargs):
    return article.author_id
class aiohttp_json_api.fields.decorators.Tag[source]

Bases: enum.Enum

An enumeration.

ADD = 'add'
GET = 'get'
INCLUDE = 'include'
QUERY = 'query'
REMOVE = 'remove'
SET = 'set'
VALIDATE = 'validate'
aiohttp_json_api.fields.decorators.gets(field_key)[source]

Decorator for marking the getter of a field:

class Article(BaseSchema):

    title = String()

    @gets("title")
    def get_title(self, article):
        return article.get_title()

A field can have at most one getter.

Parameters:field_key (str) – The key of the field.
aiohttp_json_api.fields.decorators.sets(field_key)[source]

Decorator for marking the setter of a field:

class Article(BaseSchema):

    title = String()

    @sets("title")
    def update_title(self, article, title, sp):
        article.set_title(title)
        return None

A field can have at most one updater.

Parameters:field_key (str) – The key of the field.
aiohttp_json_api.fields.decorators.updates(field_key)

Alias for sets().

aiohttp_json_api.fields.decorators.validates(field_key, step=<Step.AFTER_DESERIALIZATION: 2>, on=<Event.ALWAYS: 15>)[source]

Decorator for adding a validator:

class Article(BaseSchema):

    created_at = DateTime()

    @validates("created_at")
    def validate_created_at(self, data, sp, context):
        if created_at > datetime.utcnow():
            detail = "Must be in the past."
            raise InvalidValue(detail=detail, source_pointer=sp)

A field can have as many validators as you want. Note, that they are not necessarily called in the order of their definition.

Parameters:
  • field_key (str) – The key of the field.
  • step (Step) – Must be any Step enumeration value (e.g. Step.BEFORE_DESERIALIZATION)
  • on (Event) – Validator’s Event
aiohttp_json_api.fields.decorators.adds(field_key)[source]

Decorator for marking the adder of a relationship:

class Article(BaseSchema):

    comments = ToMany()

    @adds("comments")
    def add_comments(self, field, resource, data, sp,
                     context=None, **kwargs):
        for comment in comment:
            comment.article_id = article.id

A relationship can have at most one adder.

Parameters:field_key (str) – The key of the relationship.
aiohttp_json_api.fields.decorators.removes(field_key)[source]

Decorator for marking the remover of a relationship:

class Article(BaseSchema):

    comments = ToMany()

    @removes("comments")
    def remove_comments(self, field, resource, data, sp,
                        context=None, **kwargs):
        for comment in comment:
            comment.article_id = None

A relationship can have at most one remover.

Parameters:field_key (str) – The key of the relationship.
aiohttp_json_api.fields.decorators.includes(field_key)[source]

Decorator for marking the includer of a relationship:

class Article(BaseSchema):

    author = ToOne()

    @includes("author")
    def include_author(self, field, resources, context, **kwargs):
        return article.load_author()

A field can have at most one includer.

Hint

The includer should receive list of all resources related to request. This able to make one request for all related includes at each step of recursively fetched compound documents. Look at get_compound_documents() for more details about how it works.

Parameters:field_key (str) – The name of the relationship.
aiohttp_json_api.fields.decorators.queries(field_key)[source]

Decorator for marking the function used to query the resources in a relationship:

class Article(BaseSchema):

    comments = ToMany()

    @queries("comments")
    def query_comments(self, article_id, **kargs):
        pass

A field can have at most one query method.

Todo

Add an example.

Parameters:field_key (str) – The name of the relationship.
Relationships
class aiohttp_json_api.fields.relationships.ToOne(*, dereference=True, require_data=<Event.ALWAYS: 15>, foreign_types=None, links=None, id_field=None, **kwargs)[source]

Bases: aiohttp_json_api.fields.base.Relationship

Describes how to serialize, deserialize and update a to-one relationship.

relation = 1
serialize(schema, data, **kwargs)[source]

Composes the final relationships object.

Return type:MutableMapping[~KT, ~VT]
validate_relationship_object(schema, data, sp)[source]

Checks additionaly to Relationship.validate_relationship_object() that the data member is a valid resource linkage.

class aiohttp_json_api.fields.relationships.ToMany(*, pagination=None, **kwargs)[source]

Bases: aiohttp_json_api.fields.base.Relationship

Describes how to serialize, deserialize and update a to-many relationship. Additionally to to-one relationships, to-many relationships must also support adding and removing relatives.

Parameters:pagination (aiohttp_json_api.pagination.PaginationABC) – The pagination helper class used to paginate the to-many relationship.
relation = 2
serialize(schema, data, links=None, pagination=None, **kwargs)[source]

Composes the final JSON API relationships object.

Parameters:pagination (PaginationABC) – If not None, the links and meta members of the pagination helper are added to the final JSON API relationship object.
Return type:MutableMapping[~KT, ~VT]
validate_relationship_object(schema, data, sp)[source]

Checks additionaly to Relationship.validate_relationship_object() that the data member is a list of resource identifier objects.

Additional trafaret’s fields
class aiohttp_json_api.fields.trafarets.DecimalTrafaret(places=None, rounding=None, allow_nan=False, **kwargs)[source]

Bases: trafaret.base.Float

check_and_return(data)[source]
convertable = (<class 'str'>, <class 'bytes'>, <class 'numbers.Real'>, <class 'int'>)
value_type

alias of decimal.Decimal

Module contents

Indices and tables