Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default model example in Swashbuckle (Swagger)

I'm running ASP WebAPI 2 and successfully installed Swashbuckle. I am trying to figure out how one defines what the default schema values are?

For example, on the Swagger live demo site they changed the default value of pet to "doggie". They also defined the allowable values for status. (Live Demo)

Example 1Example 2

like image 537
ElPresidente Avatar asked Mar 07 '15 03:03

ElPresidente


People also ask

How do I set the default value in Swagger?

Use the default keyword in the parameter schema to specify the default value for an optional parameter. The default value is the one that the server uses if the client does not supply the parameter value in the request. The value type must be the same as the parameter's data type.

What is the default Swagger URL?

json). The Swagger UI can be found at https://localhost:<port>/swagger .

What is documentName in Swagger?

The {documentName} refers to the name you specify in the AddSwaggerGen() method. The following code uses myapi as the name for a swagger document. builder.Services.AddSwaggerGen(options => options.SwaggerDoc("myapi", new OpenApiInfo { Title = "My API", Version = "v1" }) );

What is difference between NSwag and swashbuckle?

NSwag not only provides the functionality of Swashbuckle (Swagger generation) but also code generators. This way we can avoid incompatibilities and offer more features and a more streamlined toolchain.


1 Answers

I managed to get this working by following what's on this link:

https://github.com/domaindrivendev/Swashbuckle/issues/69#issuecomment-53953785

In short this is what needs to be done:

  1. Create the classes SwaggerDefaultValue and AddDefaultValues as described in the link. Some changes that I did:

    public class SwaggerDefaultValue : Attribute
    {
        public string Name { get; set; }
        public string Value { get; set; }
    
        public SwaggerDefaultValue(string value)
        {
            this.Value = value;
        }
    
        public SwaggerDefaultValue(string name, string value) : this(value)
        {
            this.Name = name;
        }
    }
    
    public class AddDefaultValues : IOperationFilter
    {
        public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
        {
            IDictionary<string, object> parameterValuePairs =
            GetParameterValuePairs(apiDescription.ActionDescriptor);
    
            foreach (var param in operation.parameters)
            {
                var parameterValuePair = parameterValuePairs.FirstOrDefault(p => p.Key.IndexOf(param.name, StringComparison.InvariantCultureIgnoreCase) >= 0);
                param.@default = parameterValuePair.Value;
            }
        }
    
        private IDictionary<string, object> GetParameterValuePairs(HttpActionDescriptor actionDescriptor)
        {
            IDictionary<string, object> parameterValuePairs = new Dictionary<string, object>();
    
            foreach (SwaggerDefaultValue defaultValue in actionDescriptor.GetCustomAttributes<SwaggerDefaultValue>())
            {
                parameterValuePairs.Add(defaultValue.Name, defaultValue.Value);
            }
    
            foreach (var parameter in actionDescriptor.GetParameters())
            {
                if (!parameter.ParameterType.IsPrimitive)
                {
                    foreach (PropertyInfo property in parameter.ParameterType.GetProperties())
                    {
                        var defaultValue = GetDefaultValue(property);
    
                        if (defaultValue != null)
                        {
                             parameterValuePairs.Add(property.Name, defaultValue);
                        }
                    }
                }
            }
    
            return parameterValuePairs;
        }
    
        private static object GetDefaultValue(PropertyInfo property)
        {
            var customAttribute = property.GetCustomAttributes<SwaggerDefaultValue>().FirstOrDefault();
    
            if (customAttribute != null)
            {
                return customAttribute.Value;
            }
    
            return null;
        }
    }
    
    1. Edit your SwaggerConfig and add the AddDefaultValues class to the OperationFilters:

      GlobalConfiguration.Configuration
          .EnableSwagger(c => {
                ...
                c.OperationFilter<AddDefaultValues>()
                ...
           });
      
    2. Now for the parameters I want default values I just add the following:

      public IHttpActionResult Put([FromBody]Pet pet)
      {
         ...
         return Ok();
      }
      
      public class Pet {
          [SwaggerDefaultValue("doggie")]
          public string Name { get; set; }
      
          [SwaggerDefaultValue("available")]
          public string Status;
      
          ...
      }
      
like image 55
vgaspar.travix Avatar answered Sep 20 '22 15:09

vgaspar.travix