Skip to main content

incoming: JSON validation framework for Python

incoming is a JSON validation framework.

Build Status Coverage Status

Overview

Validating anything can get really messy. JSON being one of the most used formats for data exchange, incoming aims at solving the problem of validating JSON with structure and ease.

incoming is a small framework for validating JSON. It’s up to you where and how to use it. A common use-case (and the primary reason why I wrote this framework) is validating incoming JSON when writing HTTP servers.

Features

  • Classes that can be sub-classed for writing structured validators.

  • Basic validators (or datatypes) for performing common validations, like string, numbers, booleans, lists, nested JSON, etc.

  • Allows extending validators (datatypes) to write your own.

  • Allows writing callables for validating values.

  • Captures errors during validation and returns a complete report of errors.

  • Allows reporting different errors for different validation test failures for the same value.

Installation

Installation is simple.

pip install incoming

Basic Usage

import json

from datetime import date
from incoming import datatypes, PayloadValidator


class MovieValidator(PayloadValidator):
    name = datatypes.String()
    rating = datatypes.Function(
        'validate_rating',
        error='Rating must be in between 1 and 10.',
    )
    actors = datatypes.Array()
    is_3d = datatypes.Boolean()
    release_year = datatypes.Function(
        'validate_release_year',
        error='Release year must be in between 1800 and current year.',
    )

    # validation method can be a regular method
    def validate_rating(self, val, *args, **kwargs):
        return isinstance(val, int) and val >= 1 and val <= 10

    # validation method can be a staticmethod as well
    @staticmethod
    def validate_release_year(val, *args, **kwargs):
        return all((
            isinstance(val, int),
            val >= 1800,
            val <= date.today().year,
        ))

payload = {
    'name': 'Avengers',
    'rating': 5,
    'actors': [
        'Robert Downey Jr.',
        'Samuel L. Jackson',
        'Scarlett Johansson',
        'Mark Ruffalo'
    ],
    'is_3d': True,
    'release_year': 2012
}
result, errors = MovieValidator().validate(payload)
assert result and errors is None, 'Validation failed.\n%s' % json.dumps(errors, indent=2)

payload = {
    'name': 'Avengers',
    'rating': 11,
    'actors': [
        'Robert Downey Jr.',
        'Samuel L. Jackson',
        'Scarlett Johansson',
        'Mark Ruffalo'
    ],
    'is_3d': 'True',
    'release_year': 9000
}
result, errors = MovieValidator().validate(payload)
assert result and errors is None, 'Validation failed.\n%s' % json.dumps(errors, indent=2)

If you run the above script, you will get:

Traceback (most recent call last):
  File "code.py", line 67, in <module>
    assert result and errors is None, 'Validation failed.\n%s' % json.dumps(errors, indent=2)
AssertionError: Validation failed.
{
  "rating": [
    "Rating must be in between 1 and 10."
  ],
  "is_3d": [
    "Invalid data. Expected a boolean value."
  ],
  "release_year": [
    "Release year must be in between 1800 and current year."
  ]
}

Documentation

Documentation is available on Read The Docs.

Tests

Simply run:

python setup.py test

or:

py.test incoming

Contributors

Licence

See LICENCE.

The MIT License (MIT)

Copyright (c) 2013 Vaidik Kapoor

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

CHANGELOG

Development Version

0.3.1

  • Documentation changes on using Nested JSON validators. Passing name of nested class to incoming.datatypes.JSON is now discouraged. This means that the inner class has to be correctly scoped. Read more here.

0.3.0

  • Pass only the error list of a field in payload to its validator method.

  • Pass errors and payload as keyword arguments.

  • For fields that are not required and have Function as their type, call the validation method/function even if the field is missing in payload.

0.2.6

  • Support Python 3.

0.2.5

  • Abstract out datatypes that perform just Python type checks to reduce code.

0.2.4

  • Fix tests for Python 2.5 and 2.6. Fix README.

0.2.3

  • Package setup changes - added classifiers and manifest file.

0.2.1

  • First public release of Incoming.

Metadata

Release files for incoming 0.3.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for incoming 0.3.1
File Size Uploaded Provenance Actions
incoming-0.3.1.tar.gz 11.7 kB Without provenance Details for incoming-0.3.1.tar.gz

Release files / incoming-0.3.1.tar.gz

Download URL incoming-0.3.1.tar.gz
Size 11.7 kB
Tags Source
SHA-256 checksum
How to use checksums
9bbc3f2b3c7f450c1c283ac2368edfe9b07d54406de8b809416d9e62f9f457b4
BLAKE2b-256 checksum
How to use checksums
ee478befa5b32a8d3ac402574f997f310d6747133c21605ffa00eb3229541be8
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No

Security for incoming 0.3.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page