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.