API Reference

Core

class marshmallow_jsonapi.Schema(*args, **kwargs)[source]

Schema class that formats data according to JSON API 1.0. Must define the type_ class Meta option.

Example:

from marshmallow_jsonapi import Schema, fields

def dasherize(text):
    return text.replace('_', '-')

class PostSchema(Schema):
    id = fields.Str(dump_only=True)  # Required
    title = fields.Str()

    author = fields.HyperlinkRelated(
        '/authors/{author_id}',
        url_kwargs={'author_id': '<author.id>'},
    )

    comments = fields.HyperlinkRelated(
        '/posts/{post_id}/comments',
        url_kwargs={'post_id': '<id>'},
        # Include resource linkage
        many=True, include_resource_linkage=True,
        type_='comments'
    )

    class Meta:
        type_ = 'posts'  # Required
        inflect = dasherize
class Meta[source]

Options object for Schema. Takes the same options as marshmallow.Schema.Meta with the addition of:

  • type_ - required, the JSON API resource type as a string.

  • inflect - optional, an inflection function to modify attribute names.

  • self_url - optional, URL to use to self in links

  • self_url_kwargs - optional, replacement fields for self_url. String arguments enclosed in < > will be interpreted as attributes to pull from the schema data.

  • self_url_many - optional, URL to use to self in top-level links when a collection of resources is returned.

OPTIONS_CLASS

alias of marshmallow_jsonapi.schema.SchemaOpts

check_relations(relations)[source]

Recursive function which checks if a relation is valid.

format_error(field_name, message, index=None)[source]

Override-able hook to format a single error message as an Error object.

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

format_errors(errors, many)[source]

Format validation errors as JSON Error objects.

format_item(item)[source]

Format a single datum as a Resource object.

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

format_items(data, many)[source]

Format data as a Resource object or list of Resource objects.

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

format_json_api_response(data, many, **kwargs)[source]

Post-dump hook that formats serialized data as a top-level JSON API object.

See: http://jsonapi.org/format/#document-top-level

generate_url(link, **kwargs)[source]

Generate URL with any kwargs interpolated.

Hook for adding links to a resource object.

Hook for adding links to the root of the response data.

inflect(text)[source]

Inflect text if the inflect class Meta option is defined, otherwise do nothing.

on_bind_field(field_name, field_obj)[source]

Schema hook override. When binding fields, set data_key to the inflected form of field_name.

wrap_response(data, many)[source]

Wrap data and links according to the JSON API

class marshmallow_jsonapi.SchemaOpts(meta, *args, **kwargs)[source]

Fields

Includes all the fields classes from marshmallow.fields as well as fields for serializing JSON API-formatted hyperlinks.

class marshmallow_jsonapi.fields.BaseRelationship(*, load_default: Any = <marshmallow.missing>, missing: Any = <marshmallow.missing>, dump_default: Any = <marshmallow.missing>, default: Any = <marshmallow.missing>, data_key: Optional[str] = None, attribute: Optional[str] = None, validate: Optional[Union[Callable[[Any], Any], Iterable[Callable[[Any], Any]]]] = None, required: bool = False, allow_none: Optional[bool] = None, load_only: bool = False, dump_only: bool = False, error_messages: Optional[Dict[str, str]] = None, metadata: Optional[Mapping[str, Any]] = None, **additional_metadata)[source]

Base relationship field.

This is used by marshmallow_jsonapi.Schema to determine which fields should be formatted as relationship objects.

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

class marshmallow_jsonapi.fields.DocumentMeta(**kwargs)[source]

Field which serializes to a “meta object” within a document’s “top level”.

Examples:

from marshmallow_jsonapi import Schema, fields

class UserSchema(Schema):
    id = fields.String()
    metadata = fields.DocumentMeta()

    class Meta:
        type_ = 'product'

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

class marshmallow_jsonapi.fields.Relationship(related_url='', related_url_kwargs=None, *, self_url='', self_url_kwargs=None, include_resource_linkage=False, schema=None, many=False, type_=None, id_field=None, **kwargs)[source]

Framework-independent field which serializes to a “relationship object”.

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

Examples:

author = Relationship(
    related_url='/authors/{author_id}',
    related_url_kwargs={'author_id': '<author.id>'},
)

comments = Relationship(
    related_url='/posts/{post_id}/comments/',
    related_url_kwargs={'post_id': '<id>'},
    many=True, include_resource_linkage=True,
    type_='comments'
)

This field is read-only by default.

Parameters
  • related_url (str) – Format string for related resource links.

  • related_url_kwargs (dict) – Replacement fields for related_url. String arguments enclosed in < > will be interpreted as attributes to pull from the target object.

  • self_url (str) – Format string for self relationship links.

  • self_url_kwargs (dict) – Replacement fields for self_url. String arguments enclosed in < > will be interpreted as attributes to pull from the target object.

  • include_resource_linkage (bool) – Whether to include a resource linkage (http://jsonapi.org/format/#document-resource-object-linkage) in the serialized result.

  • schema (marshmallow_jsonapi.Schema) – The schema to render the included data with.

  • many (bool) – Whether the relationship represents a many-to-one or many-to-many relationship. Only affects serialization of the resource linkage.

  • type (str) – The type of resource.

  • id_field (str) – Attribute name to pull ids from if a resource linkage is included.

deserialize(value, attr=None, data=None, **kwargs)[source]

Deserialize value.

Raises

ValidationError – If the value is not type dict, if the value does not contain a data key, and if the value is required but unspecified.

extract_value(data)[source]

Extract the id key and validate the request structure.

serialize(attr, obj, accessor=None)[source]

Pulls the value for the given key from the object, applies the field’s formatting and returns the result.

Parameters
  • attr – The attribute/key to get from the object.

  • obj – The object to access the attribute/key from.

  • accessor – Function used to access values from obj.

  • kwargs – Field-specific keyword arguments.

class marshmallow_jsonapi.fields.ResourceMeta(**kwargs)[source]

Field which serializes to a “meta object” within a “resource object”.

Examples:

from marshmallow_jsonapi import Schema, fields

class UserSchema(Schema):
    id = fields.String()
    meta_resource = fields.ResourceMeta()

    class Meta:
        type_ = 'product'

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

Flask

Flask integration that avoids the need to hard-code URLs for links.

This includes a Flask-specific schema with custom Meta options and a relationship field for linking to related resources.

class marshmallow_jsonapi.flask.Relationship(related_view=None, related_view_kwargs=None, *, self_view=None, self_view_kwargs=None, **kwargs)[source]

Field which serializes to a “relationship object” with a “related resource link”.

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

Examples:

author = Relationship(
    related_view='author_detail',
    related_view_kwargs={'author_id': '<author.id>'},
)

comments = Relationship(
    related_view='posts_comments',
    related_view_kwargs={'post_id': '<id>'},
    many=True, include_resource_linkage=True,
    type_='comments'
)

This field is read-only by default.

Parameters
  • related_view (str) – View name for related resource link.

  • related_view_kwargs (dict) – Path kwargs fields for related_view. String arguments enclosed in < > will be interpreted as attributes to pull from the target object.

  • self_view (str) – View name for self relationship link.

  • self_view_kwargs (dict) – Path kwargs for self_view. String arguments enclosed in < > will be interpreted as attributes to pull from the target object.

  • **kwargs – Same keyword arguments as marshmallow_jsonapi.fields.Relationship.

class marshmallow_jsonapi.flask.Schema(*args, **kwargs)[source]

A Flask specific schema that resolves self URLs from view names.

class Meta[source]

Options object that takes the same options as marshmallow-jsonapi.Schema, but instead of self_url, self_url_kwargs and self_url_many has the following options to resolve the URLs from Flask views:

  • self_view - View name to resolve the self URL link from.

  • self_view_kwargs - Replacement fields for self_view. String attributes enclosed in < > will be interpreted as attributes to pull from the schema data.

  • self_view_many - View name to resolve the self URL link when a collection of resources is returned.

self_url = None
self_url_kwargs = None
self_url_many = None
OPTIONS_CLASS

alias of marshmallow_jsonapi.flask.SchemaOpts

generate_url(view_name, **kwargs)[source]

Generate URL with any kwargs interpolated.

class marshmallow_jsonapi.flask.SchemaOpts(meta, *args, **kwargs)[source]

Options to use Flask view names instead of hard coding URLs.

Exceptions

Exception classes.

exception marshmallow_jsonapi.exceptions.IncorrectTypeError(message=None, actual=None, expected=None)[source]

Raised when client provides an invalid type in a request.

property messages

JSON API-formatted error representation.

exception marshmallow_jsonapi.exceptions.JSONAPIError[source]

Base class for all exceptions in this package.

Utilities

Utility functions.

This module should be considered private API.

marshmallow_jsonapi.utils.resolve_params(obj, params, default=<marshmallow.missing>)[source]

Given a dictionary of keyword arguments, return the same dictionary except with values enclosed in < > resolved to attributes on obj.

marshmallow_jsonapi.utils.tpl(val)[source]

Return value within < > if possible, else return None.