17
votes

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

4
Are you use ServiceStack ? - Sidron
@Sidron: No. I use plain asp.net core with swashbuckle - Liero
Why you want to have orderDirection nullable and nullable at same time... ? - OrcusZ
The title and answered are talking about parameter, but in the question’s body you asked default value for property in the class. - Michael Freidgeim
@MichaelFreidgeim: whether they are implemented as properties in class, or parameters in method, they are still just the operation's parameters in swagger - Liero

4 Answers

9
votes

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

4
votes

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);
}
1
votes

This is applicable for ASP.net MVC5, code is not valid for .Net Core

1- Define a custom attribute as following

public class SwaggerDefaultValueAttribute: Attribute
{
   public SwaggerDefaultValueAttribute(string param, string value)
   {
      Parameter = param;
      Value = value;
   }
   public string Parameter {get; set;}
   public string Value {get; set;}
}

2- Define a Swagger OperationFilter class

public class AddDefaulValue: IOperationFilter
{
   void IOperationFilter.Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
   {
      if (operation.parameters == null || !operation.parameters.Any())
      {
         return;
      }
      var attributes = apiDescription.GetControllerAndActionAttributes<SwaggerDefaultValueAttribute>().ToList();

      if (!attributes.Any())
      {
         return;
      }
      
      foreach(var parameter in operation.parameters)
      {
         var attr = attributes.FirstOrDefault(it => it.Parameter == parameter.name);
         if(attr != null)
         {
            parameter.@default = attr.Value;
         }
      }
   } 
}

3- Register the OperationFilter at SwaggerConfig file

c.OperationFilter<AddDefaultValue>();

4- Decorate your controller method with attributes

[SwaggerDefaultValue("param1", "AnyValue")]
public HttpResponseMessage DoSomething(string param1)
{
   return Request.CreateResponse(HttpStatusCode.OK);
}
-2
votes

In the YAML file, you can define which properties should be required. This example is from a NSwag configuration.

/SearchPendingCases:
    post:
      summary: Search pending cases
      description: Searches for pending cases and orders them
      parameters:
        - in: body
          name: SearchQuery 
          required: true
          schema:
            type: object
            required:
              - OrderBy
              # do not include OrderDirection here because it is optional
            properties:
              OrderBy:
                description: Name of property for ordering
                type: string
                # you can remove the following two lines 
                # if you do not want to check the string length
                minLength: 1    
                maxLength: 100
              OrderDirection:
                description: Optional order direction, default value: Descending
                type: string
                enum: [Ascending, Descending] # valid enum values
                default: Descending           # default value

Swagger - Enums

Swagger - Unlocking the Spec: The default keyword