marshmallow-jsonapi

0.24.0 · active · verified Fri Apr 17

marshmallow-jsonapi provides JSON:API 1.0 (https://jsonapi.org) formatting capabilities on top of the popular marshmallow serialization/deserialization library. It helps developers create schemas that comply with the JSON:API specification for building REST APIs. The current version is 0.24.0, and it generally follows the release cadence of its core dependency, marshmallow, with releases typically tied to marshmallow updates or bug fixes.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart defines two JSON:API compliant schemas for 'authors' and 'books'. It demonstrates the use of `marshmallow_jsonapi.Schema` for the base schema, standard `marshmallow.fields`, and `marshmallow_jsonapi.fields.Relationship` for defining JSON:API relationships. The crucial `Meta.type_` attribute is set, which is required for JSON:API resource objects. It then serializes example data for both.

import datetime as dt
from marshmallow import fields
from marshmallow_jsonapi import Schema


class AuthorSchema(Schema):
    id = fields.Str(dump_only=True)
    first_name = fields.Str(required=True)
    last_name = fields.Str(required=True)
    date_created = fields.DateTime(dump_only=True)

    class Meta:
        type_ = 'authors'
        strict = True


class BookSchema(Schema):
    id = fields.Str(dump_only=True)
    title = fields.Str(required=True)
    pages = fields.Int()
    author = fields.Relationship(
        related_url='/authors/{author_id}',
        related_url_kwargs={'author_id': '<author.id>'}, 
        attribute='author', 
        type_='authors'
    )

    class Meta:
        type_ = 'books'
        strict = True


# Example Usage
author_data = {
    'id': '1',
    'first_name': 'John',
    'last_name': 'Doe',
    'date_created': dt.datetime.now()
}
author_schema = AuthorSchema()
serialized_author = author_schema.dump(author_data)
print('Serialized Author:')
print(serialized_author)

book_data = {
    'id': '101',
    'title': 'The Great Book',
    'pages': 300,
    'author': author_data # Pass the entire author object for relationship handling
}
book_schema = BookSchema()
serialized_book = book_schema.dump(book_data)
print('\nSerialized Book:')
print(serialized_book)

view raw JSON →