DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 967,611 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Yao-Ching Huang
Yao-Ching Huang

Posted on • Updated on

Python :: Validate JSON Schema using marshmallow

Marshmallow is the Python package that can serialize, deserialize and validate JSON data.

It's useful for web services when processing the incoming JSON data and responses in JSON format.

Installation

python3 -m venv .venv
source .venv/bin/activate
python3 -m pip install marshmallow
Enter fullscreen mode Exit fullscreen mode

Examples

Simple Example

This example demonstrates the following features:

  • Validation and deserialization using Schema.load().
  • Preprocess the input data using @post_load.
from marshmallow import Schema, fields, validate, post_load


class Person(Schema):
    name = fields.Str(required=True)
    gender = fields.Str(required=True, validate=validate.OneOf({"male", "female", "other"}))
    email = fields.Email(required=True)
    registration_datetime = fields.DateTime("%Y-%m-%dT%H:%M:%S%z")

    @post_load
    def convert_to_utc_datetime(self, data, **kwargs):
        data["registration_datetime"] = data["registration_datetime"].astimezone(datetime.timezone.utc)
        return data

person_schema = Person()
Enter fullscreen mode Exit fullscreen mode
>>> person_data = {"name": "Tommy", "gender": "male", "email": "tommy@example.com", "registration_datetime": "2022-07-06T08:00:00+08:00"}
>>> person_schema.load(person_data)

{'gender': 'male',
 'name': 'Tommy',
 'registration_datetime': datetime.datetime(2022, 7, 6, 0, 0, tzinfo=datetime.timezone.utc),
 'email': 'tommy@example.com'}
Enter fullscreen mode Exit fullscreen mode
>>> invalid_person_data = {"name": "Tommy", "gender": "mmale", "email": "tommy@example.com", "registration_datetime": "2022-07-06T08:00:00+08:00"}
>>> person_schema.load(invalid_person_data)

ValidationError: {'gender': ['Must be one of: female, other, male.']}
Enter fullscreen mode Exit fullscreen mode

Latest comments (0)

🌚 Life is too short to browse without dark mode