Skip to main content

JSON validation framework for Python.

Project description

incoming is a JSON validation framework.

https://travis-ci.org/vaidik/incoming.png

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. Its up to you where and how to use it. A common use-case (and the primary reason why I wrote this framework) was using it for writing HTTP servers to validate incoming JSON payload.

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):
        if not isinstance(val, int):
            return False

        if val < 1 or val > 10:
            return False

        return True

    # validation method can be a staticmethod as well
    @staticmethod
    def validate_release_year(val, *args, **kwargs):
        if not isinstance(val, int):
            return False

        if val < 1800 or val > date.today().year:
            return False

        return True

payload = {
    'name': 'Avengers',
    'rating': 5,
    'actors': [
        'Robert Downey Jr.',
        'Samual 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.',
        'Samual L. Jackson',
        'Scarlett Johansson',
        'Mark Ruffalo'
    ],
    'is_3d': 'True',
    'release_year': 2014
}
result, errors = MovieValidator().validate(payload)
assert result and errors is None, 'Validation failed.\n%s' % json.dumps(errors, indent=2)

Run the above script, you shall get a response like so:

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

Run tests like so:

python setup.py test

or:

py.test incoming

Licence

See LICENCE.

CHANGELOG

Development Version

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.

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.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

incoming-0.2.5.tar.gz (10.8 kB view details)

Uploaded Source

File details

Details for the file incoming-0.2.5.tar.gz.

File metadata

  • Download URL: incoming-0.2.5.tar.gz
  • Upload date:
  • Size: 10.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No

File hashes

Hashes for incoming-0.2.5.tar.gz
Algorithm Hash digest
SHA256 2a5c6fa77044c223a2c52dd3010b373e47d13711dbcf11096b7e90b8e0efd268
MD5 1a13e6784f3b023abbc7d6d856e22acc
BLAKE2b-256 12bc3f93d22a23b7445fd14e28526016e2cd475799ab7a3f5d14d0adb9c1f779

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page