96

How to I define in OpenAPI/Swagger if a field is optional or required and what is the default?

Helen
  • 87,344
  • 17
  • 243
  • 314
user79074
  • 4,937
  • 5
  • 29
  • 57

3 Answers3

130

By default, fields in a model are optional unless you put them in the required list. Below is an example - id, category are optional fields, name is required. Note that required is not an attribute of fields, but an attribute of the object itself - it's a list of required properties.

type: object
required:  # List the required properties here
  - name
properties:
  id:
    type: integer
    format: int64
  category:
    $ref: '#/definitions/Category'
  name:
    type: string
    example: doggie

Ref: https://github.com/swagger-api/swagger-codegen/blob/master/modules/swagger-codegen/src/test/resources/2_0/petstore.yaml#L658

If this is the model for the request body, you'll probably also need to mark the body itself as required:

# swagger: '2.0'

parameters:
  - in: body
    name: body
    required: true  # <----
    schema:
      $ref: '#/definitions/Pet'

# openapi: 3.x.x

requestBody:
  required: true  # <----
  content:
    ...

To specify the default value of optional fields, you can use the default attribute. Here is an example:

type: object
properties:
  huntingSkill:
    type: string
    description: The measured skill for hunting
    default: lazy
Helen
  • 87,344
  • 17
  • 243
  • 314
William Cheng
  • 10,137
  • 5
  • 54
  • 79
102

Fields are optional unless marked as required.

You list required fields like this:

SomeObject:
    type: object
    required:
      - name
      - fartingPower
    properties:
      name:
        type: string
      fartingPower:
        type: integer
Pang
  • 9,564
  • 146
  • 81
  • 122
Bohdan
  • 16,531
  • 16
  • 74
  • 68
8

An alternative syntax:

Response:
  type: object
  required: [id, title]
  properties:
    id:
      type: string
    title:
      type: string
Krishna
  • 6,107
  • 2
  • 40
  • 43
Graham
  • 81
  • 2
  • 2