DEV Community

Bùi Quang
Bùi Quang

Posted on

Building a Zero-Dependency JSON Validator SDK in Python

Building a Zero-Dependency JSON Validator SDK in Python

When building lightweight microservices, configuration parsers, or API endpoints, validating incoming JSON payloads against a schema is a common requirement. While heavy validation libraries exist, sometimes you just need a fast, zero-dependency, pure Python solution.

In this post, we'll walk through building a clean JSON Schema Validator SDK in Python with robust type checking and required field validation.


1. The Core Design

Our SDK validates Python dictionaries against a schema definition specifying:

  • properties: Field names and their expected types (string, integer, number, boolean, array, object).
  • required: Mandatory fields that must be present in the payload.

Implementation (json_validator/validator.py)

import json

def validate_json(data, schema):
    errors = []

    properties = schema.get("properties", {})
    required = schema.get("required", [])

    # Check required fields
    if isinstance(data, dict):
        for req in required:
            if req not in data:
                errors.append(f"Missing required field: '{req}'")

        # Check property types
        for key, value in data.items():
            if key in properties:
                prop_schema = properties[key]
                expected_type = prop_schema.get("type")

                if expected_type == "string":
                    if not isinstance(value, str):
                        errors.append(f"Field '{key}' must be of type string, got {type(value).__name__}")
                elif expected_type == "integer":
                    # In Python bool is subclass of int, so check bool explicitly
                    if not isinstance(value, int) or isinstance(value, bool):
                        errors.append(f"Field '{key}' must be of type integer, got {type(value).__name__}")
                elif expected_type == "number":
                    if not isinstance(value, (int, float)) or isinstance(value, bool):
                        errors.append(f"Field '{key}' must be of type number, got {type(value).__name__}")
                elif expected_type == "boolean":
                    if not isinstance(value, bool):
                        errors.append(f"Field '{key}' must be of type boolean, got {type(value).__name__}")
                elif expected_type == "array":
                    if not isinstance(value, list):
                        errors.append(f"Field '{key}' must be of type array, got {type(value).__name__}")
                elif expected_type == "object":
                    if not isinstance(value, dict):
                        errors.append(f"Field '{key}' must be of type object, got {type(value).__name__}")
    else:
        errors.append(f"Root data must be an object, got {type(data).__name__}")

    return errors
Enter fullscreen mode Exit fullscreen mode

2. Writing Unit Tests

To ensure reliability, we use Python's built-in unittest framework:

import unittest
from json_validator.validator import validate_json

class TestJsonValidator(unittest.TestCase):
    def setUp(self):
        self.schema = {
            "properties": {
                "name": {"type": "string"},
                "age": {"type": "integer"},
                "score": {"type": "number"},
                "active": {"type": "boolean"},
                "tags": {"type": "array"},
                "metadata": {"type": "object"}
            },
            "required": ["name", "age"]
        }

    def test_valid_data(self):
        data = {
            "name": "Alice",
            "age": 30,
            "score": 95.5,
            "active": True,
            "tags": ["python", "sdk"],
            "metadata": {"version": 1}
        }
        errors = validate_json(data, self.schema)
        self.assertEqual(errors, [])

    def test_missing_required(self):
        data = {"name": "Bob"}
        errors = validate_json(data, self.schema)
        self.assertIn("Missing required field: 'age'", errors)

    def test_type_mismatch(self):
        data = {
            "name": "Charlie",
            "age": "thirty",  # Should be integer
            "active": "yes"   # Should be boolean
        }
        errors = validate_json(data, self.schema)
        self.assertEqual(len(errors), 2)

if __name__ == "__main__":
    unittest.main()
Enter fullscreen mode Exit fullscreen mode

3. Running Tests

Execute tests seamlessly via unittest:

python3 -m unittest json_validator/test_validator.py
Enter fullscreen mode Exit fullscreen mode

Conclusion

This zero-dependency JSON validator provides a robust, lightweight foundation for validating API requests or configuration files without bloating your project dependencies.

Support crypto development: base:0x551a468628F6F35546E11dAcDa3d99EE75E61A8D

Top comments (0)