Infer a JSON Schema from a sample API response
Admin ·
A listing API returns an array of records. Three representative records show a contact object, an explicit null contact and a missing contact. Those differences lead to distinct rules in a generated schema.
Generate the schema from three listing records
Choose Load example and Draft 2020-12, then choose Generate schema. The outer items schema describes objects where id and labels are required. Contact is optional because the third record omits it. When contact is present it can be an object or null, which the tool writes as anyOf.
The labels items schema uses anyOf with string and integer branches. The empty labels array in the second record contributes no item type. If every labels array were empty, the items schema would be an empty object.
[
{"id": 41, "contact": {"email": "one@example.com"}, "labels": ["new"]},
{"id": 42, "contact": null, "labels": []},
{"id": 43, "labels": [1, "sale"]}
]JSON Schema Draft 2020-12 CoreJSON Schema Draft 2020-12 Validation
Match your validator's schema draft
Select Draft-07 if the consuming validator expects that draft. The schema declares its draft through $schema. Turn on Add string format hints to see the email hint for contact.email. The option annotates recognized formats when observed strings at a position agree.
Validator settings determine whether format is enforced. Try both passing and failing payloads using the same validator configuration that will read the schema.
JSON Schema Draft 2020-12 ValidationJSON Schema Draft-07 Validation
Add constraints from your actual contract
The sample shows integer IDs and several label types. Check your API contract for supported types and missing fields. Then add any known ranges, enumeration values, length limits or conditions between fields.
The inferred schema permits additional object properties and merges observed shapes at the same position. If two record kinds have different required properties, model each kind separately in the reviewed schema.
JSON Schema Draft 2020-12 CoreJSON Schema Draft 2020-12 Validation
Common questions
Does a property with null count as present?
Yes. An explicit null contributes the null type. A missing key affects whether the property appears in required.
Does the generator copy example values into the schema?
It uses values to infer types and optional format hints. It does not include example payloads, default values or enumerations in the generated schema.
Sources
Put it into practice.
Related guides
- How to Turn JSON Records into TypeScript Types
- How to Format and Validate JSON
- Merge Two JSON Objects and Resolve Conflicts
- Find and Reuse JSONPath Matches
- Test a Zod Schema Against JSON Inventory
- Format a Catalog Query and Check Its Structure
- Validate CSV Rows Against Mapped JSON Types
- Check Model JSON Before Passing It On
- Generate and Check an OpenAPI Example