Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swagger default value for parameter

How do I define default value for property in swagger generated from following API?

public class SearchQuery
{
        public string OrderBy { get; set; }

        [DefaultValue(OrderDirection.Descending)]
        public OrderDirection OrderDirection { get; set; } = OrderDirection.Descending;
}


public IActionResult SearchPendingCases(SearchQuery queryInput);

Swashbuckle generates OrderDirection as required parameter. I would like to be it optional and indicate to client the default value (not sure if swagger supports this).

I don't like making the property type nullable. Is there any other option? Ideally using built in classes...

I use Swashbuckle.AspNetCore - https://docs.microsoft.com/en-us/aspnet/core/tutorials/web-api-help-pages-using-swagger?tabs=visual-studio

like image 742
Liero Avatar asked Jan 11 '18 15:01

Liero


2 Answers

I've always set the default on the param itself like this:

public class TestPostController : ApiController
{
    public decimal Get(decimal x = 989898989898989898, decimal y = 1)
    {
        return x * y;
    }
}

Here is how that looks like on the swagger-ui:
http://swashbuckletest.azurewebsites.net/swagger/ui/index#/TestPost/TestPost_Get


UPDATE

Following the discussion on the comments I updated Swagger-Net to read the DefaultValueAttribute via reflection Here is the sample class I'm using:

public class MyTest
{
    [MaxLength(250)]
    [DefaultValue("HelloWorld")]
    public string Name { get; set; }
    public bool IsPassing { get; set; }
}

and here is how the swagger json looks like:

"MyTest": {
  "type": "object",
  "properties": {
    "Name": {
      "default": "HelloWorld",
      "maxLength": 250,
      "type": "string"
    },
    "IsPassing": {
      "type": "boolean"
    }
  },
  "xml": {
    "name": "MyTest"
  }
},

The Source code of Swagger-Net is here:
https://github.com/heldersepu/Swagger-Net

And the source code for the test project is here:
https://github.com/heldersepu/SwashbuckleTest

like image 191
Helder Sepulveda Avatar answered Sep 28 '22 02:09

Helder Sepulveda


Setting the default parameter value works like this if you can do it in your controller

// GET api/products
[HttpGet]
public IEnumerable<Product> Get(int count = 50)
{
    Conn mySqlGet = new Conn(_connstring);
    return mySqlGet.ProductList(count);
}
like image 43
Colbs Avatar answered Sep 28 '22 02:09

Colbs