Skip to content
JSON Schema Draft v7 (http://json-schema.org/) formatting with marshmallow
Python Makefile
Branch: master
Clone or download
fuhrysteve Merge pull request #86 from yeralin/number-field-support
Add support for marshmallow.fields.Number
Latest commit b29a8af Aug 14, 2019
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
example Use black to format source code. Jul 15, 2019
marshmallow_jsonschema Add support for marshmallow.fields.Number Aug 14, 2019
tests Test the opposite whether UnsupportedValueError is thrown on unknown … Aug 9, 2019
.coveragerc Provide `additionalProperties` value either in `Meta` or deduce it au… Jul 17, 2019
.gitignore big rework to incorporate named defs and therefore support recursive … Jul 18, 2017
.pre-commit-config.yaml Use black to format source code. Jul 15, 2019
.travis.yml update coveralls (attempt to fix the build) Aug 10, 2019
CHANGES add some details to the 0.6.0 changelog Jun 16, 2019
CONTRIBUTING.md Use black to format source code. Jul 15, 2019
LICENSE remove unused file & update license Mar 16, 2016
MANIFEST.in Use tox to test for different versions of Python and marshmallow 2 and 3 Jul 13, 2019
Makefile Use tox to test for different versions of Python and marshmallow 2 and 3 Jul 13, 2019
README.md Update README.md Jul 20, 2019
pyproject.toml Use black to format source code. Jul 15, 2019
requirements-test.txt Move INCLUDE, RAISE, EXCLUDE to `compat` and `UnsupportedValueError` … Jul 20, 2019
requirements-tox.txt Use tox to test for different versions of Python and marshmallow 2 and 3 Jul 13, 2019
requirements.txt Move requirements to txt files and read them from setup.py Jul 13, 2019
setup.py Use black to format source code. Jul 15, 2019
tox.ini

README.md

marshmallow-jsonschema: JSON Schema formatting with marshmallow

Build Status Coverage Status Code style: black

marshmallow-jsonschema translates marshmallow schemas into JSON Schema Draft v7 compliant jsonschema. See http://json-schema.org/

Why would I want my schema translated to JSON?

What are the use cases for this? Let's say you have a marshmallow schema in python, but you want to render your schema as a form in another system (for example: a web browser or mobile device).

Installation

pip install marshmallow-jsonschema

Some Client tools can render forms using JSON Schema

Simple Example

from marshmallow import Schema, fields
from marshmallow_jsonschema import JSONSchema

class UserSchema(Schema):
    username = fields.String()
    age = fields.Integer()
    birthday = fields.Date()

user_schema = UserSchema()

json_schema = JSONSchema()
json_schema.dump(user_schema).data

Yields:

{'properties': {'age': {'format': 'integer',
                        'title': 'age',
                        'type': 'number'},
                'birthday': {'format': 'date',
                             'title': 'birthday',
                             'type': 'string'},
                'username': {'title': 'username', 'type': 'string'}},
 'required': [],
 'type': 'object'}

Nested Example

from marshmallow import Schema, fields
from marshmallow_jsonschema import JSONSchema
from tests import UserSchema


class Athlete(object):
    user_schema = UserSchema()

    def __init__(self):
        self.name = 'sam'


class AthleteSchema(Schema):
    user_schema = fields.Nested(JSONSchema)
    name = fields.String()

    
athlete = Athlete()
athlete_schema = AthleteSchema()

athlete_schema.dump(athlete).data

Complete example Flask application using brutisin/json-forms

![Screenshot] (http://i.imgur.com/jJv1wFk.png)

This example renders a form not dissimilar to how wtforms might render a form.

However rather than rendering the form in python, the JSON Schema is rendered using the javascript library brutusin/json-forms.

from flask import Flask, jsonify
from marshmallow import Schema, fields
from marshmallow_jsonschema import JSONSchema

app = Flask(__name__)


class UserSchema(Schema):
    name = fields.String()
    address = fields.String()


@app.route('/schema')
def schema():
    schema = UserSchema()
    return jsonify(JSONSchema().dump(schema).data)


@app.route('/')
def home():
    return '''<!DOCTYPE html>
<head>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/brutusin.json-forms/1.3.0/css/brutusin-json-forms.css"><Paste>
<script src="https://code.jquery.com/jquery-1.12.1.min.js" integrity="sha256-I1nTg78tSrZev3kjvfdM5A5Ak/blglGzlaZANLPDl3I=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.string/3.3.4/underscore.string.min.js"></script>
<script src="https://cdn.jsdelivr.net/brutusin.json-forms/1.3.0/js/brutusin-json-forms.min.js"></script>
<script>
$(document).ready(function() {
    $.ajax({
        url: '/schema'
        , success: function(data) {
            var container = document.getElementById('myform');
            var BrutusinForms = brutusin["json-forms"];
            var bf = BrutusinForms.create(data);
            bf.render(container);
        }
    });
});
</script>
</head>
<body>
<div id="myform"></div>
</body>
</html>
'''


if __name__ == '__main__':
    app.run(host='0.0.0.0', debug=True)

Custom Type support

Simply add a _jsonschema_type_mapping method to your field so we know how it ought to get serialized to JSON Schema.

A common use case for this is creating a dropdown menu using enum (see Gender below).

class Colour(fields.Field):

    def _jsonschema_type_mapping(self):
        return {
            'type': 'string',
        }

    def _serialize(self, value, attr, obj):
        r, g, b = value
        r = hex(r)[2:]
        g = hex(g)[2:]
        b = hex(b)[2:]
        return '#' + r + g + b 

class Gender(fields.String):
    def _jsonschema_type_mapping(self):
        return {
            'type': 'string',
            'enum': ['Male', 'Female']
        }


class UserSchema(Schema):
    name = fields.String(required=True)
    favourite_colour = Colour()
    gender = Gender()

schema = UserSchema()
json_schema = JSONSchema()
json_schema.dump(schema).data
You can’t perform that action at this time.