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