Schemas with JSON Schema

OpenAPI · Practical · 15 min

Schemas drive validation, generated types and docs, so precision pays off everywhere.

In OpenAPI 3.1, the Schema Object is a superset of JSON Schema 2020-12, so any JSON Schema knowledge applies directly.

Core keywords:

  • type: string, number, integer, boolean, array, object, null.
  • properties and required (a list at the object level, not a flag on each property).
  • additionalProperties: false to forbid unknown fields, or a schema for map-like objects.
  • items for arrays, plus minItems, maxItems, uniqueItems.
  • String constraints: minLength, maxLength, pattern, and format (date-time, email, uuid, uri). Formats are annotations by default; validators may or may not enforce them.
  • Numbers: minimum, maximum, exclusiveMinimum, multipleOf.
  • enum and const; default; readOnly (in responses only, like id) and writeOnly (in requests only, like password).

Nullability changed in 3.1: write type: [string, 'null']. The 3.0 keyword nullable: true no longer exists. Also, 3.0's example in schemas gives way to JSON Schema examples (an array).

Tips: a property not listed in required is optional, which is different from nullable. Use integer with format: int64 for 64-bit ids, and remember some JavaScript clients lose precision above 2^53; many APIs send such ids as strings.

Example

components:
  schemas:
    Book:
      type: object
      required: [id, title, isbn]
      additionalProperties: false
      properties:
        id: { type: string, format: uuid, readOnly: true }
        title: { type: string, minLength: 1, maxLength: 200 }
        isbn: { type: string, pattern: '^\d{13}$' }
        pages: { type: integer, minimum: 1 }
        price: { type: number, multipleOf: 0.01 }
        subtitle: { type: [string, 'null'] }   # 3.1 nullability
        genre: { type: string, enum: [fiction, science, history] }
        tags:
          type: array
          items: { type: string }
          uniqueItems: true
        publishedAt: { type: string, format: date-time }

Remember

  • 3.1 schemas are JSON Schema 2020-12
  • required is a list on the object; optional differs from nullable
  • Nullable in 3.1: type: [string, 'null']
  • readOnly for server-set fields, writeOnly for secrets

Watch out for

  • Using nullable: true in a 3.1 document; it is silently ignored or rejected by tools.

Check yourself

  1. How is a nullable string written in OpenAPI 3.1?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: spec.openapis.org/oas/v3.1.1.html#schema-object