Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swashbuckle Swagger UI: How to remove required from parameters in xml commenting

I would like to change the required attribute on a some of the parameters in my controllers. I used XML comments in order to link to Swagger.

Example image

like image 633
tdmiller Avatar asked May 31 '17 19:05

tdmiller


1 Answers

Before proceeding, think carefully about your parameter. Is the parameter truly required, and does your typing reflect that? Is there a sane default value, and what would be the expected behavior in that case? Depending on your answer, you may prefer one of these two solutions:

Option 1: Optional Parameters

If accessTokenID has a sane default value, you can specify that on the API signature and Swashbuckle will stop identifying the parameter as required.

For example, id in this example would resolve as optional in Swagger UI:

public HttpResponseMessage Get(int id = 0)

If your parameter is truly not required, a nullable type might make more sense (for example, if you list all values on null input):

public HttpResponseMessage Get(int? id = null)

Option 2: SwaggerDefaultValue Attribute

A solution in the Swashbuckle GitHub created an IOperationFilter to process SwaggerDefaultValue attributes and apply them to Swagger UI. You can use this solution if you would prefer to require the parameter, but would like to set some default in Swagger UI.

For example, this would show "0" in the Swagger UI text field instead of "(required)":

[SwaggerDefaultValue("id", "0")]
public HttpResponseMessage Get(int id)
like image 153
Anthony Neace Avatar answered Oct 21 '22 04:10

Anthony Neace