QA AND TEST AUTOMATION · PART 4 · API TESTING · TECHNIQUE · 43 OF 112

JSON Schema Validation in API Testing (Java and Python)

Checking the shape of every API response at once with JSON Schema: types, required fields, ranges, patterns and enums, a real schema for ShopRung's cart validated with Python's jsonschema and in Java, the clear error a type change produces, additionalProperties trade-offs, and schemas from an OpenAPI spec.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
  46. 46
  47. 47
  48. 48
  49. 49
  50. 50
  51. 51
  52. 52
  53. 53
  54. 54
  55. 55
  56. 56
  57. 57
  58. 58
  59. 59
  60. 60
  61. 61
  62. 67
  63. 68
  64. 69
  65. 70
  66. 71
  67. 72
  68. 73
  69. 74
  70. 75
  71. 76
  72. 77
  73. 78
  74. 79
  75. 80
  76. 81
  77. 82
  78. 83
  79. 84
  80. 85
  81. 86
  82. 87
  83. 88
  84. 89
  85. 90
  86. 91
  87. 92
  88. 93
  89. 94
  90. 95
  91. 96
  92. 97
  93. 98
  94. 99
  95. 100
  96. 101
  97. 102
  98. 103
  99. 104
  100. 105
  101. 106
  102. 107
  103. 108
  104. 109
  105. 110
  106. 111
  107. 112
1 / 12

Press play to hear the narration, or step through at your own pace.

Key takeaways

  • Shape vs value checks
  • type, required, ranges, patterns, enums
  • jsonschema and Java
  • strictness
  • OpenAPI

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.

Values vs shape
  • 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.

Schema keywords
"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.

cart.schema.json (part)
"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.

pytest + jsonschema
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.

Real validator output
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.

Java options
// 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.

Choosing strictness
  • 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.

Do not hand-write twice
  • 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.

Avoid these
  • 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.

In the interview
  • "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."

Interview questions

Q1What is JSON Schema?

A JSON vocabulary that describes the structure of JSON documents: types, required properties, ranges, patterns, enums and nested objects and arrays.

Q2Why validate API responses against a schema?

To check the whole contract at once: missing fields, wrong types or unexpected values are caught even when no test asserts on that field.

Q3Does schema validation replace value assertions?

No. A response can have the right shape and wrong values; use both.

Q4What does additionalProperties: false do?

It makes any property not listed in "properties" a validation error, catching leaked or unexpected fields but failing on harmless additions.

Q5How do you validate a schema in REST Assured?

Add the json-schema-validator module and use .body(matchesJsonSchemaInClasspath("schema.json")); for newer drafts, a separate validator library may be needed.

Q6How do you validate JSON Schema in Python?

With the jsonschema library: jsonschema.validate(instance, schema), which raises ValidationError with the failing path.

Q7What is the relationship between OpenAPI and JSON Schema?

OpenAPI specs describe request and response bodies with (a dialect of) JSON Schema, so tests can reuse those schemas.

Q8What would a schema catch that a status code check misses?

A 200 response with a missing field, a number turned into a string, an out-of-range value or an unexpected sensitive field.