Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make parameters in swashbuckle optional(not required)

I want to make param in my controller as optional but swagger shows it as required.

my controller looks like:

[HttpGet("{name}")]
[SwaggerResponse((int)HttpStatusCode.OK)]
[SwaggerResponse((int)HttpStatusCode.BadRequest)]
public async Task<IActionResult> GetPolicy(string name)
 {
     if (string.IsNullOrEmpty(name))
     {
         return BadRequest("Name is empty");
     }
     try
     {
         CRUDPolicyResponse crudPolicyResponse = await _managementOperations.CRUDPolicy(CRUDType.Read, name, null);
         if (!crudPolicyResponse.OperationSucceeded)
         {     
            return StatusCode((int)HttpStatusCode.BadRequest, crudPolicyResponse.Message);
         }
         if (crudPolicyResponse.FileMetadataPolicy == null)
         {
             return NotFound($"Policy name doesn't exists NAME: {name}");
         }
         return Ok(crudPolicyResponse.FileMetadataPolicy);
     }
     catch (Exception ex)
     {
        _log.Error("Error while trying to save file meta data policy", ex);
            return StatusCode((int)HttpStatusCode.InternalServerError, ex);
     }
 }

I tried to change to default value like this: string name = null but not working/ swashbuckle looks like this

So the name string is required and i can't make get with name as empty.

I tried to solve my problem with this solution make int as nullable

like image 750
Max.Futerman Avatar asked Oct 01 '17 09:10

Max.Futerman


People also ask

Are path parameters optional?

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

What is optional parameter in REST API?

Optional Parameters in Web API Attribute Routing and Default Values: You can make a URI parameter as optional by adding a question mark (“?”) to the route parameter. If you make a route parameter as optional then you must specify a default value by using parameter = value for the method parameter.


2 Answers

Change your param using FromQuery like this :

public async Task<IActionResult> GetPolicy([FromQuery] string name)
like image 159
Terai Avatar answered Oct 21 '22 18:10

Terai


Add the default value to your controller parameter

[HttpGet("{name}")]
[SwaggerResponse((int)HttpStatusCode.OK)]
[SwaggerResponse((int)HttpStatusCode.BadRequest)]
public async Task<IActionResult> GetPolicy(string name = "")
 {
...
}
like image 32
ToDevAndBeyond Avatar answered Oct 21 '22 18:10

ToDevAndBeyond