DEV Community

2x lazymac
2x lazymac

Posted on

JSON Schema Validation API: Automate Your API Contract Testing

Your API tests pass. Your consumers still send malformed requests. JSON Schema validation via API closes the gap — here's how to automate your contract testing.

The Problem with Unit Tests Alone

Unit tests verify your code. They don't verify what your API consumers are actually sending. Schema validation catches the difference.

Define Once, Validate Everywhere

// user-schema.json
{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": "object",
  "required": ["email", "name", "age"],
  "properties": {
    "email": {
      "type": "string",
      "format": "email"
    },
    "name": {
      "type": "string",
      "minLength": 1,
      "maxLength": 100
    },
    "age": {
      "type": "integer",
      "minimum": 0,
      "maximum": 150
    },
    "role": {
      "type": "string",
      "enum": ["user", "admin", "viewer"]
    }
  },
  "additionalProperties": false
}
Enter fullscreen mode Exit fullscreen mode

Validate via API (No Dependencies)

import requests, json

schema = json.load(open('user-schema.json'))
payload = {"email": "test@example.com", "name": "Alice", "age": "thirty"}  # Bug: age is string

resp = requests.post("https://api.lazy-mac.com/json-schema/validate", json={
    "schema": schema,
    "data": payload
})

result = resp.json()
# {
#   "valid": false,
#   "errors": [
#     {"path": "$.age", "message": "Value must be of type integer", "value": "thirty"}
#   ]
# }
Enter fullscreen mode Exit fullscreen mode

CI/CD Integration

#!/bin/bash
# validate-api-contract.sh

SCHEMA_FILE="schemas/user-create.json"
EXAMPLE_FILE="tests/fixtures/valid-user.json"

RESULT=$(curl -s -X POST "https://api.lazy-mac.com/json-schema/validate" \
  -H "Content-Type: application/json" \
  -d "{\"schema\": $(cat $SCHEMA_FILE), \"data\": $(cat $EXAMPLE_FILE)}")

VALID=$(echo $RESULT | jq -r '.valid')

if [ "$VALID" != "true" ]; then
  echo "❌ Contract validation failed:"
  echo $RESULT | jq '.errors'
  exit 1
fi

echo "✅ Contract validation passed"
Enter fullscreen mode Exit fullscreen mode

Add this to your CI pipeline. Breaking API contracts surfaces immediately.

JSON Schema Validation API | Full API store

Top comments (0)