Ytsen de Boer
Ytsen de Boer

Reputation: 3107

Swagger editor how to specify which fields in request body (POST) are required?

I'm trying to define a POST method on a user class in the online Swagger editor.

I want to be able to specify multiple fields in the request body and I would like the generated documentation to reflect that only 2 fields are required, the others are optional.

What do I have to do/change to make that so?

I have tried various variations with the "required" key word (see picture below for one), but haven't been able to make that work, it doesn't show in the generated documentation (see picture below right side with my annotations in red).

Here is my POST definition in the editor:

enter image description here

Here is the generated documenation preview where I have indicated the things I should like to see changed.

enter image description here

PS. There are some more (olders) posts addressing this, but I really don't think this is a duplicate.

Upvotes: 8

Views: 20923

Answers (1)

Helen
Helen

Reputation: 97687

I want to be able to specify multiple fields in the request body and I would like the generated documentation to reflect that only 2 fields are required, the others are optional.

Your second example is correct. To specify the required object properties, add required: [prop1, prop2, ...] on the object level (i.e. alongside type: object). Properties not listed in the required list are optional. If the required list is not provided, all properties are optional.

type: object
required: [email, password]  # <--------
properties:
  email:
    type: string
  password:
    type: string
  name:
    type: string

In Swagger UI, operation-specific schema documentation is displayed on the Schema (or Model) tab. That's where the property descriptions, data types, "required" indicators, and other schema info is displayed.

enter image description here

Now I'll have to figure out how to have that "schema" shown as default

To make the Schema/Model tab active by default, configure Swagger UI with the defaultModelRendering option set to "model".

Upvotes: 13

Related Questions