Schemas and Data Types

By Phil Sturgeon
Last update on July 18, 2024

One of the most important parts of OpenAPI is the schema object. Schema objects are used to describe HTTP request and response bodies, parameters, headers, and all sorts of other data, whether its JSON, XML, or primitive types like integers and strings.

If you’re familiar with JSON Schema, you’ll be right at home here, because OpenAPI v3.1 uses JSON Schema (draft 2020-12). For those who have not used JSON Schema before, that’s ok, follow along.

The first thing to learn about a schema is the type keyword, which can be one or more of the following types:

You can also use “integer” for the sake of convenience, but “integer” and “number” are basically identical because JSON itself does not make that distinction. Since there is no distinct JSON integer type, JSON Schema defines integers mathematically. This means that both 1 and 1.0 are equivalent, and are both considered to be integers.

A schema object looks like this:

type: string

It can also define multiple types, for instance making a property nullable:

type: [string, null]

It also allows you to support properties that could be either a number or a numeric string.

type: [number, string]

Describing an object will often involve the use of properties to define what each of the objects properties should look like, and each of those properties will have a “subschema” that describes it.

type: object
required:
- name
properties:
  name:
    type: string
  age:
    type: integer

Arrays work in a similar way, with an items keyword allowing each item in the array to be described.

type: array
items:
  type: string

Arrays of objects can be described by combining the two concepts:

type: array
items:
  type: object
  required:
  - name
  properties:
    name:
      type: string
    age:
      type: integer

Data Formats #

The type keyword sets out the basic data type, but knowing something is a string or an integer is just the first step to understanding what that data is all about.

First of all there’s the format keyword, which covers a predefined set of common formats:

type: array
items:
  type: object
  required:
  - name
  properties:
    name:
      type: string
    email:
      type: string
      format: email
    age:
      type: integer
      format: int32

The full list of formats defined in the JSON Schema Validation that OpenAPI v3.1 relies upon: