Notes
Two kinds of check
There are two kinds of response check. Value checks ask whether the logic is right: is the discount exactly five hundred cents? Shape checks ask whether the contract is kept: is every expected field there, with the right type, in a sensible range? Value checks look at a few fields; a schema looks at all of them. They catch different bugs, so good API suites use both.
- value checks discountCents == 500 total == "$49.99" → is the logic right?
- shape checks (schema) every field present? right types? in range? → is the contract kept?
- use both
The vocabulary
A JSON schema is a JSON document that describes other JSON. Type says object, array, string, integer and so on. Required lists the fields that must be present. Properties gives a rule per field, and items gives the rule for every element of an array. Minimum and maximum limit numbers, pattern is a regular expression for strings, enum lists the allowed values, and additional properties controls unexpected fields. The dollar schema line names the version, here twenty twenty twelve.
"type": "object" | "array" |
"string" | "integer" | ...
"required": ["totalCents", ...]
"properties": { field: rule }
"items": rule for array items
"minimum" / "maximum"
"pattern": "^[A-Z]{2}-[0-9]{3}$"
"enum": [0, 499]
"additionalProperties": false
"$schema": ".../2020-12/schema" ShopRung's cart
Here is part of a real schema for ShopRung's cart. Six fields are required. Items is an array, and each item has a sku matching two capital letters, a dash and three digits, and a quantity between one and ten, straight from the requirements. Shipping must be zero or four ninety nine. The total is a string, and in the full file a pattern checks it looks like a dollar sign, digits, a dot and two digits. Notice the schema encodes rules too, not just types.
"required": ["items", "subtotalCents",
"discountCents", "shippingCents",
"totalCents", "total"],
"properties": {
"items": {"type": "array", "items": {
"sku": {"pattern":
"^[A-Z]{2}-[0-9]{3}$"},
"quantity": {"type": "integer",
"minimum": 1, "maximum": 10}}},
"shippingCents": {"enum": [0, 499]},
"total": {"type": "string", ...}} In Python
In Python, the jsonschema library does the work. Load the schema file once. In the test, put something in Alice's cart, get the cart, and call validate with the response and the schema. If the response matches, nothing happens and the test passes. We ran this against ShopRung and it passed. One line checked every field of the cart, including every item in the array.
import json, pathlib
from jsonschema import validate
SCHEMA = json.loads(pathlib.Path(
"cart.schema.json").read_text())
def test_cart_schema(alice):
alice.post("/api/cart/items",
json={"productId": 1, "quantity": 4})
r = alice.get("/api/cart")
validate(r.json(), SCHEMA) A failure
Now imagine a developer changes total cents from the number four nine nine nine to the string four nine nine nine. Every value check that compares text might still pass, but a mobile app expecting a number would crash. We made exactly that change to a real response and validated it. The error says: four nine nine nine in quotes is not of type integer, in the total cents property, and shows the value. Precise and fast to fix.
ValidationError:
'4999' is not of type 'integer'
Failed validating 'type' in
schema['properties']
['totalCents']
On instance:
['totalCents']: '4999' In Java
In Java, REST Assured has a JSON schema validator module. Put the schema on the test classpath, and in the then section, check that the body matches the JSON schema in the classpath. It reads like any other check. One caution: that module understands older schema versions, such as draft four. If your schemas use twenty twenty twelve, many teams use a separate validator library, such as the networknt one, and assert on its list of errors.
// io.rest-assured:
// json-schema-validator
given().spec(shop).auth().oauth2(t)
.when().get("/api/cart")
.then().body(
matchesJsonSchemaInClasspath(
"cart.schema.json"));
// older drafts (draft 4); for
// 2020-12 many teams use the
// networknt json-schema-validator Strict or loose?
One design choice: should extra fields fail the test? With additional properties false, any unexpected field fails. That catches leaks, like a password hash suddenly appearing in a user response, but it also fails when the API adds a harmless new field. Allowing extra fields, the default, keeps tests stable as the API grows but misses surprises. A practical rule: strict on sensitive objects like users and payments, looser elsewhere.
- additionalProperties: false + catches leaked fields (passwordHash in a user!)
- fails when the API adds a harmless new field
- allowed (the default) + tests survive new fields
- misses unexpected data
- tip: strict on sensitive objects, loose elsewhere
From OpenAPI
Many APIs publish an OpenAPI specification, sometimes called Swagger, which already contains a schema for every request and response. If yours does, reuse those schemas in tests instead of copying them by hand, so tests and documentation cannot drift apart. Tools like Schemathesis go further and generate many tests from the spec automatically. ShopRung has no spec, so we wrote the schema from the requirements and real responses.
- OpenAPI (Swagger) specs hold a schema for every response
- reuse them in tests instead of copying by hand
- tools can generate many tests from a spec (e.g. Schemathesis)
- ShopRung has no spec: write the schema from requirements and real responses
Common mistakes
Schema testing mistakes. Using only schemas and no value checks, so a wrong total with the right type passes. A schema with no required list, where an empty object passes every rule. Everything typed as string, which checks almost nothing. Copying a schema once and never updating it. And making everything strict, then disabling the tests when harmless new fields break them.
- schema only, no value checks
- schema with no "required" (an empty {} passes!)
- everything typed "string"
- copying a schema once, never updating it
- strict everywhere, then disabling the flaky tests
Say it like this
In the interview: a JSON schema describes the shape of a response: required fields, types, ranges and patterns. One validate call checks the whole body, which catches contract breaks like a number becoming a string or a field disappearing. I combine schema checks with value checks, reuse OpenAPI schemas when they exist, and keep sensitive objects strict so leaked fields fail the build.
- "A schema describes the shape
- of a response: required fields, types, ranges, patterns. One validate call checks it all, catching contract breaks like
- a number becoming a string.
- I combine it with value checks, reuse OpenAPI schemas when available, and keep sensitive
- objects strict."