Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 735
user79074 Avatar asked Oct 18 '16 16:10

user79074


People also ask

How do you specify optional parameters in Swagger?

You can use the default key to specify the default value for an optional parameter. The default value is the one that the server uses if the client does not supply the parameter value in the request. The value type must be the same as the parameter's data type.

Can a path parameter be optional?

Hello, like described here (swagger-api/swagger-ui#380), path parameters are required and can't be optional.

What is the difference between OpenAPI and Swagger?

Although the terms once referred to the same thing, they can no longer be used interchangeably…even though some people still do. In 2021, OpenAPI refers to the industry-standard specification for RESTful API design. Swagger refers to a set of SmartBear tools.


1 Answers

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 
like image 61
William Cheng Avatar answered Sep 21 '22 11:09

William Cheng