jsonapi.base

This is the base of the py-jsonapi library. It contains the definition for interfaces (database, serializer), which can be overridden and then used by an API instance.

jsonapi.base.handler

jsonapi.base.handler.base

class jsonapi.base.handler.base.BaseHandler(api, db, request)[source]

Bases: object

The base class for a request handler.

Parameters:
prepare()[source]

Called directly before handle().

handle()[source]

Handles a requested.

head()[source]

Handles a HEAD request.

get()[source]

Handles a GET request.

post()[source]

Handles a POST request.

patch()[source]

Handles a PATCH request.

delete()[source]

Handles a DELETE request.

jsonapi.base.handler.collection

class jsonapi.base.handler.collection.CollectionHandler(api, db, request)[source]

Bases: jsonapi.base.handler.base.BaseHandler

Handles the collection endpoint.

prepare()[source]
get()[source]

Handles a GET request. This means to fetch many resourcs from the collection and return it.

http://jsonapi.org/format/#fetching-resources

post()[source]

Handles a POST request. This means to create a new resource and to return it.

http://jsonapi.org/format/#crud-creating

jsonapi.base.handler.relationship

class jsonapi.base.handler.relationship.RelationshipHandler(api, db, request)[source]

Bases: jsonapi.base.handler.base.BaseHandler

Handles the relationship endpoint.

prepare()[source]
build_body()[source]

Serializes the relationship and creates the JSONapi body.

get()[source]

Handles a GET request.

http://jsonapi.org/format/#fetching-relationships

post()[source]

Handles a POST request.

This method is only allowed for to-many relationships.

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

patch()[source]

Handles a PATCH request.

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

delete()[source]

Handles a DELETE request.

jsonapi.base.handler.resource

class jsonapi.base.handler.resource.ResourceHandler(api, db, request)[source]

Bases: jsonapi.base.handler.base.BaseHandler

Handles a resource endpoint.

prepare()[source]
get()[source]

Handles a GET request.

http://jsonapi.org/format/#fetching-resources

patch()[source]

Handles a PATCH request.

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

delete()[source]

Handles a DELETE request.

jsonapi.base.api

The API application. It handles all requests and knows all available resource types.

jsonapi.base.api.build_uris(base_uri)[source]

Returns a dictionary with the uri re(s) for each endpoint type (collection, resource, related and relationships).

Parameters:base_uri (str) –
class jsonapi.base.api.API(uri, db, debug=False, settings=None)[source]

Bases: object

This class is responsible for the request dispatching. It knows all resource classes, typenames, serializers and database adapter.

Parameters:
  • uri (str) – The root uri of the whole API.
  • db (jsonapi.base.database.Database) – The database adapter we use to load resources
  • debug (bool) – If true, exceptions are not catched and the API is more verbose.
  • settings (dict) – A dictionary containing settings, which may be used by extensions.
settings = None

A dictionary, containing settings for extensions, the handlers, ...

jsonapi_object = None

The global jsonapi object, which is added to each response.

You are free to add meta information in the jsonapi_object["meta"] dictionary.

Seealso:http://jsonapi.org/format/#document-jsonapi-object
debug

True, if the API is in debug mode.

This value can be overridden in subclasses to mimic the behaviour of the parent web framework.

database
Return type:jsonapi.base.database.Database
Returns:The database the API uses to load, save and delete resources.
get_resource_class(typename, default=[])[source]

Returns the resource class associated with the typename.

Parameters:
  • typename (str) – The typename of the resource class
  • default – A fallback value, if the typename does not exist.
Raises:

KeyError – If the typename does not exist and no default argument is given.

get_schema(typename, default=[])[source]

Returns the JSONapi schema which represents the structure of the resource type with the given typename.

Parameters:
  • typename (str) –
  • default – A fallback value, if the typename does not exist.
Raises:

KeyError – If the typename is not associated with a schema and no default argument is given.

Return type:

jsonapi.base.schema.Schema

get_serializer(typename, default=[])[source]

Returns the serializer used to serialize types of typename.

Parameters:
  • typename (str) –
  • default – A fallback value, if the typename does not exist.
Raises:

KeyError – If the typename does not exist and no default argument is given.

get_unserializer(typename, default=[])[source]

Returns the unserializer used to unserialize types of typename.

Parameters:
  • typename (str) –
  • default – A fallback value, if the typename does not exist.
Raises:

KeyError – If the typename does not exist and no default argument is given.

get_typename(o, default=[])[source]

Returns the typename of the object o.

Parameters:
  • o – A resource class or a resource
  • default – A fallback value, if the typename can not be retrieved.
Raises:

KeyError – If the resource type of o is not known to the API and no default argument is given.

get_typenames()[source]
Return type:list
Returns:A list with all typenames known to the API.
has_type(typename)[source]

Returns True, if the api has a type with the given name and False otherwise.

Parameters:typename (str) –
dump_json(d)[source]

Encodes the object d as JSON string.

This method can be overridden if you want to use your own json serializer.

The default implementation uses the json module of the standard library and (if available) the bson json utils.

Parameters:d
Return type:str
load_json(s)[source]

Decods the JSON string s.

This method can be overridden if you want to use your own json serializer.

The default implementation uses the json module of the standard library and (if available) the bson json utils.

Parameters:s (str) –
uri

The root uri of api, which has been provided in the constructor.

reverse_url(typename, endpoint, **kargs)[source]

Returns the url for the API endpoint for the type with the given typename.

>>> api.reverse_url("User", "collection")
"/api/User/"

>>> api.reverse_url("User", "resource", id="AA-23")
"/api/User/AA-23"

>>> api.reverse_url(
...     "User", "relationship", id="AA-23", relname="articles"
... )
"/api/User/AA-23/relationships/articles"

>>> api.reverse_url(
...     "User", "related", id="AA-23", relname="articles"
... )
"/api/User/AA-23/articles"
Parameters:
  • typename (str) –
  • endpoint (str) – collection, resource, related or relationship
  • kargs – Additional arguments needed to build the uri. For example: The resource endpoint also needs the resource’s id.
Return type:

str

Raises:
  • ValueError – If the endpoint type does not exist.
  • ValueError – If the typename does not exist.
add_type(schema, **kargs)[source]

Adds the serializer to the API.

Parameters:schema (jsonapi.base.schema.Schema) –
handle_request(request)[source]

Handles the request and returns a Response.

Parameters:request (jsonapi.base.request.Request) –
Return type:jsonapi.base.response.Response

jsonapi.base.database

This module defines some abstract classes, which provide a common interface for the database interactions required by a JSONapi flow.

If you want to implement your own database adapter, you must extend Database and Session according to their documentation. You can take a look at the existing database adapters, if you need an example.

class jsonapi.base.database.Database(api=None)[source]

Bases: object

This class defines the base for a database adapter.

Parameters:api (jsonapi.base.api.API) – The api, which uses this database (see also: add_model()). The api may be given later via init_api().
init_api(api)[source]
Parameters:api (jsonapi.base.api.API) – The API, which uses this database adapter. See also add_model()
session()[source]

Must be overridden

Returns a new instance of Session.

class jsonapi.base.database.Session(api)[source]

Bases: object

This class defines a base for a database session. A session wraps a transaction. Changes made on resources, must only be commited to the database, when commit() is called.

If a resource is queried twice, the same object must be returned (The Python id() must be equal).

Parameters:api (jsonapi.base.api.API) –
query(typename, *, sorting=None, limit=None, offset=None, filters=None)[source]

Must be overridden

Raises:
  • errors.UnsortableField
  • errors.UnfilterableField
query_size(typename, *, sorting=None, limit=None, offset=None, filters=None)[source]

Must be overridden

It takes the same arguments as query(), but returns only the number of resources, which would be returned by query().

get(identifier, required=False)[source]

Must be overridden

Returns the resource with the id identifier or None, if there is no resource with this id.

Parameters:
  • identifier – An identifier tuple: (typename, id)
  • required (bool) – If true, throw a ResourceNotFound error if the resource with the id does not exist.
Raises:

jsonapi.base.errors.ResourceNotFound

get_many(identifiers, required=False)[source]

Must be overridden

Returns a dictionary, which maps each identifier in identifiers to a resource or None.

db.get_many([("people", "42"), ("articles", "18")])
... {
...     ("people", "42"): <People object at 0x.....>,
...     ("articles", "18"): None
... }
Parameters:
  • identifiers – A list of identifier tuples
  • required (bool) – If true, throw a ResourceNotFound error if a resource does not exist.
Raises:

jsonapi.base.errors.ResourceNotFound

save(resources)[source]

Must be overridden

Schedules the resources for beeing saved in the database on the next commit() call.

Parameters:resources – A list of resource objects
delete(resources)[source]

Must be overridden

Schedules the resources for beeing deleted in the database on the next commit() call.

Parameters:resources – A list of resource objects
commit()[source]

Must be overridden

Commits all changes to the database.

get_relatives(resources, paths)[source]

May be overridden for performance reasons.

This method basically helps to implement the include query parameter defined in the JSONapi specification. path is a list of relationship names, starting with a relationship defined on every resource in resources. This method returns then all resources, which are related to at least one of the resources.

E.g.:

# get_relatives() takes a **list** of paths and
# ["parent"] is one path.
db.get_relatives([lisa, bart, maggie], [["parent"]])
[<User (homer)>, <User (marge)>]
Parameters:
  • resources (list) – A list of resources.
  • path (list) – A list of relationship names. The first relationship must exist on every resource in resources.
Raises:

UnresolvableIncludePath – If a relationship is not defined on any of the intermediate resources.

Todo

get_relatives() is not an expressive name for the functionality of this method.

jsonapi.base.errors

This module implements the base class for all JSONapi exceptions: http://jsonapi.org/format/#errors

exception jsonapi.base.errors.Error(http_status=500, id_=None, about='', code=None, title=None, detail='', source_parameter=None, source_pointer=None, meta=None)[source]

Bases: Exception

Hint

This class implements the error specification:

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

This is the base class for all exceptions thrown by your API. All subclasses of this exception are catched by the API and converted into a response. All other exception will not be catched.

Parameters:
  • http_status (int) – The HTTP status code applicable to this problem.
  • id (str) – A unique identifier for this particular occurrence of the problem.
  • about (str) – A link that leeds to further details about this particular occurrence of the problem.
  • code (str) – An application specific error code, expressed as a string value.
  • title (str) – A short, human-readable summay of the problem that SHOULD not change from occurrence to occurrence of the problem, except for purposes of localization. The default value is the class name.
  • detail (str) – A human-readable explanation specific to this occurrence of the problem.
  • source_pointer (str) – A JSON Pointer [RFC6901] to the associated entity in the request document [e.g. “/data” for a primary data object, or “/data/attributes/title” for a specific attribute].
  • source_parameter (str) – A string indicating which URI query parameter caused the error.
  • meta (dict) – A meta object containing non-standard meta-information about the error.
json

The serialized version of this error.

jsonapi.base.errors.error_to_response(error, json_dumps)[source]

Converts an Error to a Response.

Parameters:
  • error (Error) –
  • json_dumps – The json serializer, which is used to serialize Error.json
Return type:

jsonapi.base.request.Request

Seealso:

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

exception jsonapi.base.errors.InternalServerError(**kargs)[source]

Bases: jsonapi.base.errors.Error

exception jsonapi.base.errors.BadRequest(**kargs)[source]

Bases: jsonapi.base.errors.Error

exception jsonapi.base.errors.Forbidden(**kargs)[source]

Bases: jsonapi.base.errors.Error

exception jsonapi.base.errors.NotFound(**kargs)[source]

Bases: jsonapi.base.errors.Error

exception jsonapi.base.errors.MethodNotAllowed(**kargs)[source]

Bases: jsonapi.base.errors.Error

exception jsonapi.base.errors.NotAcceptable(**kargs)[source]

Bases: jsonapi.base.errors.Error

exception jsonapi.base.errors.Conflict(**kargs)[source]

Bases: jsonapi.base.errors.Error

exception jsonapi.base.errors.UnsupportedMediaType(**kargs)[source]

Bases: jsonapi.base.errors.Error

exception jsonapi.base.errors.InvalidDocument(**kargs)[source]

Bases: jsonapi.base.errors.BadRequest

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

Please note, that this does not include semantic errors, like a wrong typename.

Seealso:http://jsonapi.org/format/#document-structure
Seealso:jsonapi.base.validators
exception jsonapi.base.errors.UnresolvableIncludePath(include_path, **kargs)[source]

Bases: jsonapi.base.errors.BadRequest

Raised, if an include path does not exist.

See also

exception jsonapi.base.errors.ReadOnlyAttribute(**kargs)[source]

Bases: jsonapi.base.errors.Forbidden

Raised, if an attribute value can not be changed.

exception jsonapi.base.errors.ReadOnlyRelationship(**kargs)[source]

Bases: jsonapi.base.errors.Forbidden

Raised, if the value of a relationship can not be modified.

exception jsonapi.base.errors.UnsortableField(typename, fieldname, **kargs)[source]

Bases: jsonapi.base.errors.BadRequest

If a field is used as sort key, but does not support sorting.

exception jsonapi.base.errors.UnfilterableField(typename, filtername, fieldname, **kargs)[source]

Bases: jsonapi.base.errors.BadRequest

If a filter should be used on a field, which does not support the filter.

exception jsonapi.base.errors.RelationshipNotFound(typename, relname, **kargs)[source]

Bases: jsonapi.base.errors.NotFound

Raised if a relationship does not exist.

exception jsonapi.base.errors.ResourceNotFound(identifier, **kargs)[source]

Bases: jsonapi.base.errors.NotFound

Raised, if a resource does not exist.

jsonapi.base.pagination

This module contains only a helper for the pagination feature: http://jsonapi.org/format/#fetching-pagination

class jsonapi.base.pagination.Pagination(request, total_resources)[source]

Bases: object

A helper class for the pagination.

The fist page has the number 1.

Parameters:
  • request (jsonapi.base.request.Request) – The current jsonapi request
  • total_resources (int) – The total number of resources, which would have been returned without the pagination.
json_meta

Must be included in the top-level meta object.

Must be included in the top-level links object.

jsonapi.base.request

class jsonapi.base.request.Request(uri, method, headers, body, api=None)[source]

Bases: object

Wraps a request object, which can be used to call the View class.

Parameters:
japi_uri_arguments = None

Contains parameters, which are encoded into the URI. For example a resource uri: http://localhost:5000/api/User/1 contains the id {'id': '1'}

Seealso:jsonapi.base.api.API.find_handler()
parsed_uri

Returns a tuple with the uri components.

query

Returns a dictionary which maps a query key to its values.

get_query_argument(name, fallback=None)[source]

Returns the (first) value of the query argument with the name name. If the argument does not exist, fallback is returned.

Parameters:
  • name (str) –
  • fallback
content_type

Returns a tuple, with the media type and the parameters.

media_type, media_parameters = request.content_type
Seealso:media_parameters
Seealso:https://www.w3.org/Protocols/rfc1341/4_Content-Type.html
japi_page_number

Returns the number of the requested page or None.

Query parameter: page[number]

Raises:
Seealso:

http://jsonapi.org/format/#fetching-pagination

japi_page_size

Returns the size of the pages or None.

Query parameter: page[size]

Raises:
Seealso:

http://jsonapi.org/format/#fetching-pagination

japi_page_limit

Returns the limit based on the japi_page_size

japi_page_offset

Returns the offset based on the japi_page_size and japi_page_number.

japi_paginate

Returns True, if the result should be paginated. This is the case, if page[size] and page[number] are both present and valid.

japi_offset

Return the offset when querying a collection.

Query parameter: offset

Raises:
japi_limit

Extracts the limit parameter from the url query string and returns it.

Query parameter: limit

Raises:
japi_filters

Returns a dictionary, which maps field names to the filter rules applied on them.

A url query may contain these filters (not all of them may be supported by all database adapters):

  • eq
  • ne
  • lt
  • lte
  • gt
  • gte
  • in
  • nin
  • all
  • size
  • exists
  • iexact
  • contains
  • icontains
  • startswith
  • istartswith
  • endswith
  • iendswith
  • match
>>> # /api/User/?filter[name]=endswith:'Simpson'
>>> request.japi_filters
... [("name", "endswith", "Simpson")]

>>> # /api/User/?filter[name]=in:['Homer Simpson', 'Darth Vader']
>>> request.japi_filters
... [("name", "in", ["Homer Simpson", "Darth Vader"])]

>>> # /api/User/?filter[email]=startswith:'lisa'&filter[age]=lt:20
>>> request.japi_filters
... [("email", "startswith", "lisa"), ("age", "lt", 20)]
Raises:
japi_fields

Returns the fields, which should be included in the response (sparse fieldset).

>>> # /api/User?fields[User]=email,name&fields[Post]=comments
>>> request.japi_fields
... {"User": ["email", "name"], "Post": ["comments"]}
Seealso:http://jsonapi.org/format/#fetching-sparse-fieldsets
japi_include

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

>>> # /api/Post?include=author,comments.author
>>> req.japi_include
... [["author"], ["comments", "author"]
Seealso:http://jsonapi.org/format/#fetching-includes
japi_sort

Returns a list with two tuples, describing how the output should be sorted:

>>> # /api/Post?sort=name,-age
... [("+", "name"), ("-", "age")]
Seealso:http://jsonapi.org/format/#fetching-sorting
json

Parses the body and returns the result.

has_json

Returns True, if the body contains a json document.

print()[source]

Prints all information about the request to stdout. This method is only used for debugging.

jsonapi.base.response

class jsonapi.base.response.Response(status=200, headers=None, body=None, file=None)[source]

Bases: object

Contains all information needed for a creating a proper http response.

Parameters:
  • status (int) – The http status code
  • headers (dict) – A dictionary containing all headers of the response.
  • body (bytes) – The body of the http response as bytes. This attribute maybe None.
  • file – If not None, this is a file like object or a filename.
has_body

Returns true, if the response contains a body (and not a file).

is_file

Returns true, if the response is a file, which must be sent to the client.

print()[source]

Prints information about the response object. This method is only used for debugging purposes.

jsonapi.base.schema

This module defines the base for the schema we use to represent the structure of a resource. The schema is used to serialize, create and update a resource.

Because most of the will use an ORM, and therefore already have a metatype class, this schema is not implemented as meta class.

See also

class jsonapi.base.schema.Attribute(name)[source]

Bases: object

This class defines the interface for getting and changing the value of an attribute.

Parameters:name (str) – The name of the attribute as it is displayed in the JSONapi
get(resource)[source]

Must be overridden

Returns the value of the attribute.

set(resource, value)[source]

Must be overridden

Changes the value of the attribute to value.

class jsonapi.base.schema.IDAttribute(name='id')[source]

Bases: jsonapi.base.schema.Attribute

The same as Attribute, but must be used for the id attribute.

class jsonapi.base.schema.BaseRelationship(name)[source]

Bases: object

This is the base class for a relationship.

Seealso:ToOneRelationship
Seealso:ToManyRelationship
Parameters:name (str) – The name of the relationship as it is displayed in the JSONapi.
to_one = None

True, if isinstance(self, ToOneRelationship) holds for instances of the subclass.

to_many = None

True, if isinstance(self, ToManyRelationship) holds for instances of this subclass.

get(resource)[source]

Must be overridden

set(resource, relatives)[source]

Must be overridden

clear(resource)[source]

Must be overridden

class jsonapi.base.schema.ToOneRelationship(name)[source]

Bases: jsonapi.base.schema.BaseRelationship

Describes a to-one relationship.

to_one = True
to_many = False
clear(resource)[source]

Can be overridden

Default implementation is equal to:

self.set(resource, None)
class jsonapi.base.schema.ToManyRelationship(name)[source]

Bases: jsonapi.base.schema.BaseRelationship

Describes a to-many relationship.

to_one = False
to_many = True
add(resource, relative)[source]

Must be overridden

Adds the relative to the relationship.

extend(resource, relatives)[source]

Can be overridden

Adds all relatives to the relationship.

clear(resource)[source]

Can be overridden

Default implementation is equal to:

self.set(resource, list())
class jsonapi.base.schema.Constructor[source]

Bases: object

Defines the interface for creating a new resource.

create(**kargs)[source]

Must be overridden

Creates a new resource using the keyword arguments and returns it. The keyword arguments are the fields of the resource mapped to their initial value.

class jsonapi.base.schema.InitConstructor(resource_class)[source]

Bases: jsonapi.base.schema.Constructor

This constructor simply uses the __init__ method of the resource_class class to create a new resource.

Parameters:resource_class
create(**kargs)[source]
class jsonapi.base.schema.Schema(resource_class, typename=None)[source]

Bases: object

Describes the structure of a resource class. The serializer will use a schema to serialize, create and update a resource.

Todo

Parameters:
  • resource_class – The resource class
  • typename – The typename of the resource_class in the JSONapi. If not given, we use the name of the resource class.
resource_class = None

The resource class

typename = None

The typename of the resource class in the API.

constructor = None

The Constructor marker, which can be used to create new instances of the resource. If no special constructor is defined on the resource_class, the default __init__ method is used.

id_attribute = None

The IDAttribute marker.

attributes = None

A dictionary, which maps the attributes names to the Attribute instance.

relationships = None

A dictionary, which maps the relationhip names to the ToOneRelationship or ToManyRelationship.

fields = None

Contains the names of all attributes and relationships.

find_fields()[source]

We search for fields instances on the resource_class. If we find an attriute, relationship, constructor, ... definition we add it to the schema.

jsonapi.base.serializer

A JSONapi serializer and unserializer based on the Schema.

class jsonapi.base.serializer.Unserializer(schema)[source]

Bases: object

Takes JSONapi documents and updates a resource.

Parameters:schema (jsonapi.base.schema.Schema) – The schema used to update resources
create_resource(db, resource_object)[source]

Creates a new resource using the JSONapi resource object resource object.

Parameters:
  • db (jsonapi.base.database.Session) – The database session used to query related resources.
  • resource_object (d) – A JSONapi resource object, containing the initial values for the attributes and relationships.
Seealso:

http://jsonapi.org/format/#document-resource-objects

update_resource(db, resource, resource_object)[source]

Updates the resource resource using the JSONapi resource object resource_object.

Parameters:
  • db (jsonapi.base.database.Session) – The database session used to query related resources.
  • resource – The resource, which is updated
  • resource_object (dict) – A JSONapi resource object containing the new attribute and relationship values.
Seealso:

http://jsonapi.org/format/#document-resource-objects

Seealso:

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

update_attributes(resource, attributes_object)[source]

Updates the attributes of the resource resource using the JSONapi attributes object attributes_object.

Parameters:
  • resource – The resource, whichs attributes are updated.
  • attributes_object (dict) – A JSONapi attributes object, containing the new attribute values.
Seealso:

http://jsonapi.org/format/#document-resource-object-attributes

update_relationship(db, resource, relationship_name, relationship_object)[source]

Updates the relationship with the name relationship_name of the resource resource using the JSONapi relationship object relationship_object.

Parameters:
  • db (jsonapi.base.database.Session) – The database session used to query related resources.
  • resource – The resource, whichs relationships are updated.
  • relationship_name (str) – The name of the relationship, which is updated.
  • relationship_object (dict) – A JSONapi relationship object, containing the new relationship values.
Seealso:

http://jsonapi.org/format/#document-resource-object-relationships

Seealso:

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

extend_relationship(db, resource, relationship_name, relationship_object)[source]

Extends the to-many relationship with the name relationship_name of the resource resource using the JSONapi relationship object relationship_object.

Parameters:
  • db (jsonapi.base.database.Session) – The database session used to query related resources.
  • resource – The resource, whichs relationship is extended
  • relationship_name (str) – The name of the relationship, which is extended
  • relationship_object (dict) – A JSONapi relationship object, containing identifiers of the new relatives.
Seealso:

http://jsonapi.org/format/#document-resource-object-relationships

Seealso:

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

clear_relationship(resource, relationship_name)[source]

Removes all relatives from the relationship with the name relationship_name of the resource resource.

Parameters:
  • resource – The resource, whichs relationship is cleared.
  • relationship_name (str) – The name oof the relationship, which is cleared.
Seealso:

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

class jsonapi.base.serializer.Serializer(schema)[source]

Bases: object

A serializer takes a resource and creates a JSONapi document.

Parameters:schema (jsonapi.base.schema.Schema) – The schema used to serialize resources
serialize_resource(resource, fields=None)[source]

Creates the JSONapi resource object.

Parameters:
  • resource
  • fields (list) – A list with the names of the fields, which should be included.
Seealso:

http://jsonapi.org/format/#document-resource-objects

serialize_identifier(resource)[source]

Creates the JSONapi resource identifier object.

Parameters:resource
Seealso:http://jsonapi.org/format/#document-resource-identifier-objects
serialize_attributes(resource, fields=None)[source]

Creates the JSONapi attributes object.

Parameters:
  • resource
  • fields (list) – A list with the names of the fields, which should be included.
Seealso:

http://jsonapi.org/format/#document-resource-object-attributes

serialize_relationships(resource, fields)[source]

Creates the JSONapi relationships object.

Parameters:
  • resource
  • fields (list) – A list with the names of the fields, which should be included.
Seealso:

http://jsonapi.org/format/#document-resource-object-relationships

serialize_relationship(resource, name)[source]

Creates the JSONapi relationship object for the relationship with the name name.

Parameters:
  • resource
  • name (str) –
Seealso:

http://jsonapi.org/format/#document-resource-object-relationships

jsonapi.base.utilities

This module contains some helpers, which are frequently needed in different modules.

jsonapi.base.utilities.ensure_identifier_object(obj)[source]

Returns the identifier object for the resource:

{
    "type": "people",
    "id": "42"
}

The object obj can be a two tuple (typename, id), a resource document which contains the id and type key {"type": ..., "id": ...} or a real resource object.

Parameters:obj
jsonapi.base.utilities.ensure_identifier(obj)[source]

Does the same as ensure_identifier_object(), but returns the two tuple identifier object instead of the document:

# (typename, id)
("people", "42")
Parameters:obj
jsonapi.base.utilities.collect_identifiers(d, include_meta=False)[source]

Walks through the document d and saves all type identifers. This means, that each time a dictionary in d contains a type and id key, this pair is added to a set and later returned:

>>> d = {
...     "author": {
...         "data": {"type": "User", "id": "42"}
...     }
...     "comments": {
...         "data": [
...             {"type": "Comment", "id": "2"},
...             {"type": "Comment", "id": "3"}
...         ]
...     }
... }
>>> collect_identifiers(d)
{("User", "42"), ("Comment", "2"), ("Comment", "3")}
Parameters:
  • d (dict) –
  • include_meta (bool) – If true, we also look for (id, type) keys in the meta objects.
jsonapi.base.utilities.relative_identifiers(relname, resource)[source]

Returns a list with the ids of related resources.

Parameters:
  • relname (str) – The name of the relationship
  • resource
Raises:

jsonapi.base.errors.RelationshipNotFound

jsonapi.base.validators

This module contains validators for the different JSONapi document types. If a request contains an invalid document, a validator detects the error source and creates a verbose error with a source-pointer.

All validators only assert the correct document structure, e.g.: An identifier object must contain an id and a type attribute. However, the validator does not check, if the type is correct or even exists.

jsonapi.base.validators.assert_resource_object(d, source_pointer='/')[source]

Asserts, that d is a JSONapi resource object.

Seealso:

http://jsonapi.org/format/#document-resource-objects

Parameters:
  • d
  • source_pointer (str) –
Raises:

InvalidDocument

jsonapi.base.validators.assert_attributes_object(d, source_pointer='/')[source]

Asserts, that d is a JSONapi attributes object.

Seealso:

http://jsonapi.org/format/#document-resource-object-attributes

Parameters:
  • d
  • source_pointer (str) –
Raises:

InvalidDocument

jsonapi.base.validators.assert_relationships_object(d, source_pointer='/')[source]

Asserts, that d is a JSONapi relationships object.

Seealso:

http://jsonapi.org/format/#document-resource-object-relationships

Parameters:
  • d
  • source_pointer (str) –
Raises:

InvalidDocument

jsonapi.base.validators.assert_relationship_object(d, source_pointer='/')[source]

Asserts, that d is a relationship object.

Seelso:

http://jsonapi.org/format/#document-resource-object-relationships

Parameters:
  • d
  • source_pointer (str) –
Raises:

InvalidDocument

jsonapi.base.validators.assert_resource_linkage(d, source_pointer='/')[source]

Asserts, that d is a resource linkage.

Seealso:

http://jsonapi.org/format/#document-resource-object-linkage

Parameters:
  • d
  • source_pointer (str) –
Raises:

InvalidDocument

jsonapi.base.validators.assert_resource_identifier_object(d, source_pointer='/')[source]

Asserts, that d is a resource identifier object.

Seealso:

http://jsonapi.org/format/#document-resource-identifier-objects

Parameters:
  • d
  • source_pointer (str) –
Raises:

InvalidDocument

Asserts, that d is a JSONapi links object.

Seealso:

http://jsonapi.org/format/#document-links

Parameters:
  • d
  • source_pointer (str) –
Raises:

InvalidDocument

Asserts, that d is a JSONapi link object.

Seealso:

http://jsonapi.org/format/#document-links

Parameters:
  • d
  • source_pointer (str) –
Raises:

InvalidDocument

jsonapi.base.validators.assert_meta_object(d, source_pointer='/')[source]

Asserts that d is a meta object.

Seealso:

http://jsonapi.org/format/#document-meta

Parameters:
  • d
  • source_pointer (str) –
Raises:

InvalidDocument