Use references in JSON Schema

How JSON Schema references work: $ref, $defs, anchors, pointer escaping, version differences, recursion, and what breaks when schemas are copied or shared.

Short answer: are references right for your schema?

References are usually worth using when the same structure appears more than once, when the data is recursive, or when several schemas need to share one definition. The main benefit is a single source of truth: you change an address or identifier definition in one place, and every schema that points to it picks up the change. The decisive tradeoff is that a referenced schema can no longer be read or validated in isolation. Its meaning depends on where the reference resolves, which depends on the document's base URI, the draft you declare, and how your validator loads schemas.

Writing the subschema inline is often the better choice in these cases:

  • The structure is used only once and is short.
  • The schema will be pasted into places that have no schema loader, such as documentation, a ticket or a configuration field.
  • A downstream tool, such as a form generator or code generator, does not document full reference support.
  • Readers need to understand the whole contract from one screen without jumping between definitions.

What a reference is

A reference is the $ref keyword. Its value is a URI reference that points to another schema. The validator resolves that value against the current base URI and then applies the target schema at that point. The most common pattern keeps reusable pieces under $defs in the same document and points to them with a JSON Pointer fragment.

{
  "$id": "urn:example:order",
  "type": "object",
  "properties": {
    "billing": { "$ref": "#/$defs/address" },
    "shipping": { "$ref": "#/$defs/address" }
  },
  "$defs": {
    "address": {
      "type": "object",
      "properties": {
        "street": { "type": "string" },
        "city": { "type": "string" }
      },
      "required": ["street", "city"]
    }
  }
}

$defs is the standard location for reusable definitions in drafts 2019-09 and 2020-12. Schemas written for draft-07 and earlier conventionally use definitions instead. Pointers work the same way in both cases because they address a position in the document. Keep the name that matches the draft declared in your $schema keyword so that readers and tools are not surprised.

What changes when you refactor to references

Moving an inline subschema into $defs and replacing it with $ref changes how the schema is organized. It does not change the instance data, and it is meant to leave the set of valid documents unchanged. In practice that equivalence holds only if three things are true:

  • The moved subschema does not depend on its old location. A nested $id, or relative references inside it, can resolve differently once the subschema sits elsewhere.
  • No keywords sit next to $ref in a draft that ignores them. This is covered in its own section below.
  • You do not rely on the exact text of error output. The standard output formats in 2019-09 and 2020-12 report both the evaluation path through $ref and the absolute location of the referenced keyword. Error paths shift after a refactor even when the pass or fail result does not.

Running the same set of valid and invalid sample documents against the schema before and after the refactor is the most direct way to confirm that nothing changed.

Ways to point at a schema

Form | Example value | Notes
JSON Pointer fragment | #/$defs/address | Tied to the target's position. It breaks if the definition is renamed or moved.
Plain-name anchor | #address | Declared with $anchor in 2019-09 and later. Older drafts used an $id whose value is a fragment. It survives moves within the document.
Relative reference | address.schema.json | Resolved against the base URI. The validator must already know the target or be able to load it.
Absolute URI | urn:example:address | Matches a schema whose $id is that URI. The schema must be registered with the validator.
Document root | # | Points to the whole current schema resource. Useful for recursion.

Escaping characters in pointer fragments

JSON Pointer uses the slash as a separator, so definition names that contain special characters must be escaped. Because the pointer sits inside a URI fragment, it may also need percent-encoding.

  • A tilde in a name is written as ~0.
  • A slash in a name is written as ~1.
  • Characters that are not allowed in a URI fragment, such as spaces or the percent sign, are percent-encoded. A space becomes %20.
  • The simplest way to avoid these rules is to use names made of letters, digits, hyphens and underscores.

Keywords next to $ref: the main version difference

In draft-07 and earlier, any keyword placed alongside $ref in the same object is ignored. Draft 2019-09 changed this: $ref became an ordinary applicator, so sibling keywords are evaluated together with the referenced schema. The same schema text can therefore accept different data depending on the declared draft. OpenAPI 3.0 schema objects follow the older ignore-siblings rule, while OpenAPI 3.1 aligns with draft 2020-12.

{
  "$ref": "#/$defs/address",
  "required": ["postalCode"]
}

Under 2020-12, this object requires the address fields and also postalCode. Under draft-07, the required keyword is skipped. If you need the combined behavior in an older draft, wrap both parts in allOf:

{
  "allOf": [
    { "$ref": "#/definitions/address" },
    { "required": ["postalCode"] }
  ]
}

Recursive structures

Recursive data, such as trees, nested comments or menus, can only be described with references. An inline copy would have to repeat itself forever.

{
  "$defs": {
    "node": {
      "type": "object",
      "properties": {
        "name": { "type": "string" },
        "children": {
          "type": "array",
          "items": { "$ref": "#/$defs/node" }
        }
      }
    }
  },
  "$ref": "#/$defs/node"
}

Draft 2020-12 also provides $dynamicRef and $dynamicAnchor, which replace the $recursiveRef and $recursiveAnchor keywords from 2019-09. They let an extending schema change what a recursive reference resolves to. They are mainly useful for extensible meta-schemas and generic containers. For ordinary reuse, plain $ref is easier to read and more widely supported.

Will the schema still work after copying or sharing?

References are the part of a schema most likely to break when text moves between environments.

  • Copied fragments. A subschema containing "#/$defs/address" resolves against whatever document it is pasted into. Copying it out alone leaves the pointer dangling, or pointing at an unrelated definition.
  • External references. The specification does not require validators to download schemas from the addresses in references. Many implementations expect you to register or preload referenced schemas, and they report an unresolved reference otherwise. How loading works is specific to each implementation, so check your validator's documentation.
  • Bundling. Draft 2020-12 describes bundling, where external schemas are embedded under $defs with their own $id. References keep working inside a single shareable file.
  • Full dereferencing. Some tools replace each $ref with a copy of its target. This produces a self-contained schema for tools without reference support. It cannot represent recursion, and it can greatly enlarge schemas that reuse definitions heavily.
  • Human readability. A reader has to follow each reference to understand the contract. Descriptive definition names and a title or description on each definition reduce that cost.
  • Other tooling. Editors, documentation renderers and code generators differ in which drafts and reference forms they handle. Success in one tool does not show that another will behave the same.

The usual safe pattern is to keep the referenced source as the canonical schema and to generate a bundled or dereferenced copy for each consumer that cannot resolve references.

Evidence gap: this article includes no tests of specific validators or tools. Before relying on one, test it with your actual schemas, including external references, a recursive case and keywords placed next to $ref.

Checklist before relying on references

  • Declare the draft with $schema so that sibling-keyword behavior and $defs or definitions conventions are unambiguous.
  • Give the root schema an absolute $id when other schemas will reference it.
  • Prefer $anchor names over long pointers for definitions that may be reorganized.
  • Register or bundle every external schema instead of assuming network retrieval.
  • Run sample valid and invalid documents before and after any refactor.
  • Produce a self-contained copy for documentation and for tools that do not resolve references.