Lesson 4: Arrays & Items
The "items" keyword defines the schema that every element in the array must satisfy — you can require that all items are strings, numbers, or even complex objects. "minItems" and "maxItems" set lower and upper bounds on the number of elements in the array, helping enforce non-empty lists or caps. Setting "uniqueItems" to true forbids duplicate values anywhere in the array. The "contains" keyword is different from "items": it only requires that at least one element in the array matches the given schema.
Why This Matters
Arrays back nearly every "list of things" in an API — order line items, tags, notification recipients, permission scopes — and bugs around them are notoriously easy to miss in testing because an empty array or a duplicate entry often "just works" until it silently breaks a total, a UI render, or a permission check in production. Bounding size and uniqueness at the schema level turns those edge cases into an explicit validation error at the boundary, and "contains" lets you express requirements that "items" alone can't, like "at least one line item must be marked primary" or "at least one tag must be from an approved list."
Common Mistakes
- ✕ Reaching for "items" when the actual requirement is "at least one element matches"."items" validates every element against the same schema. Use "contains" (optionally with minContains/maxContains) when you only need to guarantee that one or more elements — not all of them — satisfy a condition.
- ✕ Copying Draft-07 tuple syntax, where "items" was an array of schemas for positional validation.In Draft 2020-12, positional (tuple) validation moved to the "prefixItems" keyword, while "items" now always means "every element must match this one schema." Using an array under "items" no longer does tuple validation in the new draft.
- ✕ Leaving out "minItems": 1 on an array that should never logically be empty, like an order's line items.An array with no explicit minItems accepts []. If an empty list is never valid business data, say so in the schema rather than trusting application code to catch it.
- ✕ Expecting "uniqueItems" to be cheap for arrays of large nested objects."uniqueItems" performs a deep equality check between every pair of elements, which can be slow for large arrays of complex objects — for high-volume data, consider deduplicating in application code instead.
Challenge
Add a duplicate tag (e.g. add "json" again) and see uniqueItems enforce the constraint.