How to specify if a field is optional or required in OpenAPI/Swagger?
Asked Answered
B

4

105

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

Bakki answered 18/10, 2016 at 16:4 Comment(0)
G
145

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
Guayaquil answered 18/10, 2016 at 16:33 Comment(1)
we usually want to mark what properties of the body object are requiredMedic
G
104

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
Gentleness answered 13/8, 2018 at 20:22 Comment(1)
this doesnt work in v2Medic
T
10

An alternative syntax:

Response:
  type: object
  required: [id, title]
  properties:
    id:
      type: string
    title:
      type: string
Trochilus answered 16/4, 2021 at 19:45 Comment(0)
S
0

All fields are optional, unless marked specifically as required.

Additionally, and probably an important distinction, non-declared model fields are technically optional too, optional without validation.

Using the additionalProperties: false declaration, will allow you to throw up a 400 where additional properties are supplied.

Snippet supplied:

YourSchemaModel:
  type: object
  required:
  - customer_name
  - customer_signup_date
  additionalProperties: false
  properties:
    customer_name:
      type: string
    customer_signup_date:
      type: string
      format: date-time
    opted_in_for_emails:
      type: bool
Sidwel answered 30/1 at 23:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.