toolgarden.xyz
中文
JSON SchemaAPI validationJSON validationAPI

What Is JSON Schema and How Do You Validate API Data?

JSON Schema is a rules document for JSON data. It can describe required fields, value types, arrays, string formats, and nested object structures.

ToolGarden tools prioritize browser-local processing, so files and text do not need to be uploaded to a server.

Published July 2, 2026Updated August 3, 20267 min readBy ToolGarden

JSON Schema is a structural contract for JSON: it describes required fields, field types, arrays, nested objects, and optional format rules.

It is useful for API debugging, config validation, low-code forms, and data imports because it catches shape problems before data reaches business logic.

Start With a JSON Sample

{
  "id": 1001,
  "email": "user@example.com",
  "roles": ["admin"],
  "active": true
}

This object contains a number, a string, an array, and a boolean. A Schema can describe each field and decide which fields are required.

{
  "type": "object",
  "required": ["id", "email", "roles", "active"],
  "properties": {
    "id": { "type": "number" },
    "email": { "type": "string", "format": "email" },
    "roles": {
      "type": "array",
      "items": { "type": "string" }
    },
    "active": { "type": "boolean" }
  }
}

Common JSON Schema Keywords

KeywordPurposeExample
typeRestricts the base value typeobject, array, string, number
propertiesDescribes fields in an objectemail, roles, active
requiredLists fields that must existid, email
itemsDescribes array item typeseach role is a string
formatAdds semantic hints for stringsemail, uri, date-time

How to Use It for API Validation

  1. Generate a first Schema from a realistic API sample.
  2. Refine required, format, enum, minLength, and other constraints from the API contract.
  3. Validate real request or response JSON against the Schema.
  4. Use the error path to locate the exact field that needs attention.

A generated Schema is only a starting point

A generator can observe only values present in the sample. It cannot know whether a field may be absent, whether a string is a closed enum, whether a number has limits, or what business type sits behind a lone null. Generated output is useful scaffolding, but the final constraints still need the API contract, database rules, and representative failure cases.

Sample observationWhat inference cannot knowManual decision
A field appears every timeThat does not prove it is requiredUse the contract to decide required
The value is paidOther states such as draft or failed are unseenAdd enum or oneOf
An array has one itemOther item shapes are unseenAdd more samples and review items
An object has no extra fieldsExtensibility is unknownChoose an additionalProperties policy

Passing validation does not prove business correctness

Schema primarily verifies structure and the constraints you declared. A syntactically valid email is not proof that the mailbox exists, and a positive amount does not prove that an order may be refunded. Whether format is asserted can also depend on validator configuration. Use Schema at the input boundary to reject malformed data early, while cross-field rules, authorization, and business state remain application logic.

A team should also pin the JSON Schema draft and validator version. Keywords and reference behavior differ across drafts, so declare $schema where possible and include validation rules in API tests. That prevents production and documentation tooling from interpreting the same file differently.

Summary

JSON Schema turns a data shape into executable validation rules. That makes API and data pipeline errors easier to catch and explain.

Frequently asked questions

Q.How is JSON Schema fundamentally different from a TypeScript interface?

A TypeScript interface exists only at compile time. At runtime nothing stops an invalid payload from entering your system. JSON Schema is a runtime contract, so you can validate every request before it reaches your database. Interfaces improve developer experience, schemas improve resilience. The two work best together: treat the schema as the source of truth, generate a TypeScript interface with json-schema-to-typescript, and validate at runtime with ajv. Docs, mocks, code generation and validation all derive from one file, so you never keep two definitions in sync by hand.

Q.When is JSON Schema the wrong tool, and you should write a custom validator instead?

JSON Schema is great at structural rules: field presence, primitive types, string length, numeric range, enum, pattern. It struggles with cross-field business rules such as end date must be after start date, coupon amount must not exceed order total, or the payer and recipient must share an ID. Encode those as explicit business functions, or extend the schema with custom keywords. A clean layering is: schema blocks malformed data, business functions block invalid business states, and only after both checks does the request reach core logic.

Q.There are many JSON Schema drafts (04, 07, 2019-09, 2020-12). Which one should I pick?

For a green-field project pick draft 2020-12, the current standard and the one OpenAPI 3.1 uses. draft-07 is still the safest default because virtually every language has a mature library for it. draft-04 is only worth using when maintaining an old system. When you upgrade, watch out for changes to items and additionalItems, and to how $ref and $id resolve. Always declare $schema at the top of your document so validators and tools know exactly which ruleset applies.

Q.How do I use JSON Schema for frontend form validation?

Popular options are react-jsonschema-form, Formily, or a custom renderer on top of ajv. The schema describes constraints, a UI schema describes widgets and layout, and separating the two lets business rules travel from frontend to backend unchanged. Validate on submit with ajv, surface friendly messages via the errorMessage keyword, then validate again on the server so no one can bypass the UI. Sharing one schema removes the common failure mode where the client accepts input the server later rejects.

Q.Ajv error messages are too verbose. How do I show something friendly to users?

By default ajv returns paths like /profile/0/email that end users cannot parse. Fix it in layers: add errorMessage in the schema (with ajv-errors) to override default text; write a formatError helper that maps JSON pointer paths to human field labels, so /orderItems/0/qty becomes quantity of item 1; collapse multiple errors on the same field into the single most important one; and load locale-specific message bundles for internationalized apps. Keep the raw payload in logs for debugging, but only show a short, actionable message in the UI.