PREP WITH PROOF
Menu
APIS & DATA VALIDATION / PRACTICAL GUIDE

JSON Schema: Required, Null and Additional Properties Explained

Separate missing fields from null values, close objects correctly and avoid allOf extension traps. Includes Draft 2020-12 schemas and a runnable Python test matrix.

THE QUICK ANSWER

required controls whether a property is present. A property’s type controls which values it accepts, including whether null is allowed. additionalProperties controls otherwise unmatched property names within its schema location. These are separate decisions; combine them deliberately and test missing, null, empty, mistyped and unexpected values.

A field can exist and still carry no value

An API accepts a profile containing a nickname. One client omits the field, another sends null, and a third sends an empty string. Treating these as interchangeable can change an update from leave unchanged to clear the value, or turn a required acknowledgement into an accidental omission. The schema should express the intended distinction before application code tries to infer it.

This guide builds a small profile contract and tests its boundaries. The examples use the Draft 2020-12 dialect, Python 3.12.14 and jsonschema 4.26.0. They were executed locally against original fixtures; no API server, serializer or production input pipeline was involved.

Start by deciding what each state means in your application. Validation can distinguish shapes, but it cannot decide whether a missing nickname means inherit, unknown or invalid. That meaning belongs in the API contract and the code that applies an accepted request.

required asks whether the key is there

A properties entry describes a value when that named property appears. It does not, by itself, require the property to appear. Put property names in required to enforce their presence. Declare type: object when the overall instance must be an object; object-specific keywords alone are not a substitute for that type restriction.

Requirement and value validity remain independent. If nickname is required and its schema accepts only strings, a missing nickname fails required and a present null fails type. If the type allows string or null, the present null can pass while the missing key still fails.

For a nested object, place the nested required list inside that object’s schema. Requiring preferences at the root does not automatically require digest inside it. Conversely, requiring digest inside an optional preferences object only constrains preferences when that object is supplied.

Source: JSON Schema Draft 2020-12: validation vocabulary, type and required ↗

null is a value, not a missing property

JSON null is distinct from false, zero, an empty string and the string "null". In Python, parsed JSON null becomes None. Check key membership when presence matters: a lookup that returns None for both a missing key and an explicit null loses the distinction before validation or update logic can use it.

To accept either a string or null, use a type array containing both names. That does not accept arbitrary numbers or booleans. An empty string is still a string, so rejecting it requires a separate constraint such as minLength. A required nullable field is therefore a meaningful contract, not a contradiction.

Be precise about normalization as well. A minimum length of one does not trim whitespace or verify an account exists. If the business rule rejects whitespace-only identifiers, enforce that rule explicitly and test it. Do not describe a shape constraint as a complete business validation policy.

Nickname statePresent?Required string-or-null field
Key omittedNoFails required
nullYesAllowed
Empty stringYesAllowed without a length constraint
String "null"YesAllowed as ordinary text
Number 7YesFails type

Source: JSON Schema: null and absence ↗

A complete profile schema with separate decisions

Save the following as profile.schema.json in a learning directory. account_id must be a nonempty string. nickname must be present but may be a string or null. preferences is optional; if supplied, it must be an object containing only the optional boolean digest field.

The root and nested objects each have their own additionalProperties rule. Closing the root does not recursively close every object below it. This explicit structure makes it possible to see which level rejects an unexpected field.

The nickname default annotation is included intentionally for the next experiment. It documents a suggested default but does not satisfy the required list or repair an instance during validation. Keep this file unchanged while running the matrix so that each observed result has one stable contract.

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "type": "object",
  "properties": {
    "account_id": {"type": "string", "minLength": 1},
    "nickname": {"type": ["string", "null"], "default": "Guest"},
    "preferences": {
      "type": "object",
      "properties": {"digest": {"type": "boolean"}},
      "additionalProperties": false
    }
  },
  "required": ["account_id", "nickname"],
  "additionalProperties": false
}

Source: JSON Schema: object properties and additionalProperties ↗

Choose where unknown properties are allowed

additionalProperties: false rejects properties not covered by properties or patternProperties in the same subschema. Without that restriction, additional properties are allowed by default. A misspelled alias can therefore pass a permissive schema even when the documented property list looks exhaustive.

Closing an input object is useful when rejecting typos is part of the contract. It is also a compatibility decision: a producer that adds a new field can break a consumer that rejects all unknown fields. Decide separately for each boundary rather than applying one policy to every message in the system.

For controlled extension data, consider a dedicated object with its own documented policy. This separates a stable top-level command from intentionally extensible metadata. Make sure validation policy and persistence policy agree; accepting an unknown field does not imply the application stores or acts on it.

Source: JSON Schema: object properties and additionalProperties ↗

Run a matrix instead of trusting one valid example

Install jsonschema==4.26.0 in an isolated learning environment, save this code as schema_lab.py beside profile.schema.json, then run python3 -B schema_lab.py with that environment’s interpreter. Draft202012Validator.check_schema checks the schema before a validator is reused for the fixtures.

The matrix parses each fixture from JSON text, checks the expected outcome and verifies that validation did not mutate the parsed instance. It covers missing keys, nulls, empty strings, wrong types, unknown root properties and nested restrictions. The final line reports fifteen cases.

The displayed locations are escaped JSON Pointers, with an explicit root label for an empty pointer. A required error points to the containing object because the missing child has no instance location. The keyword and schema location can help explain the rule; avoid relying on a library’s English error sentence as a stable machine-readable contract.

# Python 3; install jsonschema==4.26.0 in your learning environment.
from copy import deepcopy
import json
from pathlib import Path
from jsonschema import Draft202012Validator

schema = json.loads(Path('profile.schema.json').read_text(encoding='utf-8'))
Draft202012Validator.check_schema(schema)
validator = Draft202012Validator(schema)

cases = [
    ('required string', '{"account_id":"a7","nickname":"Ada"}', True),
    ('required null', '{"account_id":"a7","nickname":null}', True),
    ('empty nickname', '{"account_id":"a7","nickname":""}', True),
    ('missing nickname', '{"account_id":"a7"}', False),
    ('missing account', '{"nickname":null}', False),
    ('empty account', '{"account_id":"","nickname":null}', False),
    ('null account', '{"account_id":null,"nickname":null}', False),
    ('numeric nickname', '{"account_id":"a7","nickname":7}', False),
    ('string null', '{"account_id":"a7","nickname":"null"}', True),
    ('unknown key', '{"account_id":"a7","nickname":null,"alias":"A"}', False),
    ('nested valid', '{"account_id":"a7","nickname":null,"preferences":{"digest":true}}', True),
    ('nested extra', '{"account_id":"a7","nickname":null,"preferences":{"digest":true,"zone":"UTC"}}', False),
    ('nested null', '{"account_id":"a7","nickname":null,"preferences":null}', False),
    ('not object', 'null', False),
    ('empty object', '{}', False),
]


def pointer(parts):
    return ''.join('/' + str(p).replace('~', '~0').replace('/', '~1') for p in parts)


for label, raw, expected in cases:
    instance = json.loads(raw)
    before = deepcopy(instance)
    errors = sorted(validator.iter_errors(instance),
                    key=lambda e: (pointer(e.absolute_path), str(e.validator)))
    valid = not errors
    assert valid == expected, label
    assert instance == before, 'Validation unexpectedly changed the instance'
    locations = ', '.join(
        f'{e.validator}@{pointer(e.absolute_path) or "(root)"}' for e in errors)
    print(f'{label}: {"VALID" if valid else "INVALID"} {locations}'.rstrip())

print(f'PASS: {len(cases)} cases; validation did not insert defaults.')

Source: python-jsonschema: schema validation API ↗

A default annotation does not insert the field

The missing-nickname fixture fails even though the schema contains default: Guest. JSON Schema’s default is an annotation, not an instruction to fill missing fields during validation. The lab also compares each instance with a copy to make any unexpected mutation visible.

If your application intentionally inserts defaults, treat that as a separate transformation. Specify whether it runs before or after validation, whether explicit null survives, and whether the transformed result is validated again. A form generator, API framework and database layer can each make different choices.

Use paired tests to make that policy concrete: one request omits nickname and another supplies null. Assert the accepted or rejected shape first, then assert the application’s resulting state. A validator test alone cannot prove the endpoint’s update semantics or the database value that will be stored.

Source: JSON Schema: default and other annotations ↗

allOf combines assertions; it does not reopen a closed base

If a reusable base schema contains additionalProperties: false, a sibling allOf branch cannot simply introduce a new property that the base did not permit. Every branch must validate the instance. The new role field can fail the base even if another branch describes role correctly.

For Draft 2020-12 composition, an outer unevaluatedProperties: false can close the combined object after properties have been evaluated through the applicable schemas. The example below deliberately keeps its component branches open and closes the result at the outside. It is a separate account-and-role contract, not an extension of the earlier closed profile schema.

Test the extension together with the base. The combined example accepts an account_id plus role reader or writer, rejects a missing role, and rejects an unrelated extra key. Do not replace unevaluatedProperties with additionalProperties at that outer location and assume the two keywords see the same set of declarations.

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "type": "object",
  "allOf": [
    {
      "properties": {
        "account_id": {
          "type": "string",
          "minLength": 1
        }
      },
      "required": [
        "account_id"
      ]
    },
    {
      "properties": {
        "role": {
          "enum": [
            "reader",
            "writer"
          ]
        }
      },
      "required": [
        "role"
      ]
    }
  ],
  "unevaluatedProperties": false
}

Source: JSON Schema Draft 2020-12: core and unevaluatedProperties ↗

Keep the dialect and implementation behavior explicit

The $schema declaration identifies the dialect. Match it with a validator that supports the keywords you use; a schema accepted under one draft does not establish identical behavior under another. Check schema validity separately from instance validity so that a malformed required list is not mistaken for bad user data.

The Python library leaves format checking off by default. If another contract adds format: email or format: date, verify the configured checker and its dependencies rather than assuming the annotation rejects malformed values. The profile lab avoids format so that its conclusions concern presence, types and property boundaries only.

Run the same acceptance fixtures through every implementation that matters to deployment. A gateway, generated client and application service can disagree because of draft support or configuration. Preserve expected decisions and useful error paths, rather than assuming identical message wording across languages.

Source: python-jsonschema: format-checking and default behavior FAQ ↗

Validate the shape that reaches the boundary

A serializer may omit null-valued fields, rename properties or convert numbers to strings. Inspect the actual parsed payload at the validation boundary when a client’s in-memory object appears correct but the server rejects it. Keep diagnostic examples redacted and small; the rule location usually matters more than the complete request body.

If a nullable required field disappears during serialization, the server correctly sees an absence. If an unknown property is silently stripped before validation, a closed schema is no longer testing the original request shape. Document any preprocessing and test both its input and its output.

When evolving the contract, compare old and new fixtures deliberately. Adding a required field, removing null from an allowed type, tightening a length constraint or closing an object can turn previously valid data invalid. Plan compatibility and migration at the same time as the schema change.

Write one contract for each distinction you need

Use required for presence, type and other constraints for values, and property-boundary keywords for unknown names. Keep normalization and default insertion visible as application behavior. Once those responsibilities are separated, a validation error becomes easier to explain and a schema change becomes easier to review.

Before release, exercise missing, null, empty, wrong-type, extra-property and nested cases. For composed schemas, include the intended extension and a forbidden extra key. Reuse those cases at the actual application boundary so that the contract remains true after serialization, preprocessing and persistence.

KEEP THESE THREE THINGS

Your next steps

  1. Specify presence and nullability independently; do not infer required fields from properties.
  2. Test object closure at every relevant level and test composed schemas with real extension fields.
  3. Keep dialect selection, default insertion and format-checking configuration explicit at the actual validation boundary.

Sources & official resources

Linked resources checked on 2026-10-27. Technical behavior and provider guidance can change; check the documentation for the version you use.

About this guide and its recommendations

Published by Prep With Proof with AI-assisted drafting. Study routines and examples are editorial suggestions, not official exam instructions or claims of a learner's personal results. Cited provider facts are linked; ownership of recommended Prep With Proof products is disclosed. No competitor endorsement or guaranteed certification outcome is implied.

Suggest a correction →