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
}
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"}
# ]
# }
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"
Add this to your CI pipeline. Breaking API contracts surfaces immediately.
Top comments (0)