required in OpenAPI (or Swagger)
The meaning of required
in OpenAPI (or Swagger) is consistent across all major versions: it specifies that a property must be present in the data payload. However, how you use and apply the keyword has evolved between versions.
OpenAPI 2.0 (Swagger 2.0)
In Swagger 2.0, the required
keyword is applied at the schema level, not directly on the property itself. It's a list that enumerates all required properties within that schema.
Example:
swagger: '2.0'
info:
title: User API
version: 1.0.0
definitions:
User:
type: object
properties:
id:
type: integer
name:
type: string
email:
type: string
required:
- id
- name
In this example, both id
and name
are required properties, but email
is optional.
OpenAPI 3.0.0
OpenAPI 3.0.0 maintains the same behavior for required
but keeps the keyword within the properties
block.
Example:
openapi: 3.0.0
info:
title: User API
version: 1.0.0
paths: {}
components:
schemas:
User:
type: object
properties:
id:
type: integer
name:
type: string
email:
type: string
required:
- id
- name
The key difference here is a structural one: required
is still a list of strings, but it's now nested under the components.schemas
path, which is where schemas are defined in OA 3.0.
OpenAPI 3.1.0
OpenAPI 3.1.0 aligns with the JSON Schema specification, so the meaning and placement of the required
keyword are identical to the previous version. It's still a list within the schema definition.
Example:
openapi: 3.1.0
info:
title: User API
version: 1.0.0
paths: {}
components:
schemas:
User:
type: object
properties:
id:
type: integer
name:
type: string
email:
type: string
required:
- id
- name
The distinction between OA 3.0 and 3.1 for required
is minimal; the core concept and implementation remain the same, reflecting a continued commitment to standard JSON Schema behavior.
In summary, the functionality of required
has been consistent: a property must be present in the payload. The main evolution has been the structural location of the required
keyword as the specification matured from Swagger 2.0 to OpenAPI 3.x.