Skip to content

Swashbuckle Integration

Chris Martinez edited this page Jun 12, 2017 · 14 revisions

Although the API explorers for API versioning provide all of the necessary information, there is select information that Swagger and Swashbuckle will not wire up for you. Fortunately, bridging this gap is really easy to achieve using Swashbuckle's extensibility model. The following are simple IOperationFilter implementations that leverage the metadata provided by the corresponding API explorer to fill in these gaps. You can then add this filter to your configuration, according to the platform you're using, with:

swagger.OperationFilter<SwaggerDefaultValues>();

ASP.NET Web API or ASP.NET Web API with OData

public class SwaggerDefaultValues : IOperationFilter
{
    public void Apply(
        Operation operation,
        SchemaRegistry schemaRegistry,
        ApiDescription apiDescription )
    {
        if ( operation.parameters == null )
        {
            return;
        }

        foreach ( var parameter in operation.parameters )
        {
            var description = apiDescription.ParameterDescriptions
                                            .First( p => p.Name == parameter.name );

            if ( parameter.description == null )
            {
                parameter.description = description.Documentation;
            }

            if ( parameter.@default == null )
            {
                parameter.@default = description.ParameterDescriptor.DefaultValue;
            }
        }
    }
}

ASP.NET Core

public class SwaggerDefaultValues : IOperationFilter
{
    public void Apply( Operation operation, OperationFilterContext context )
    {
        foreach ( var parameter in operation.Parameters.OfType<NonBodyParameter>() )
        {
            var description = context.ApiDescription
                                     .ParameterDescriptions
                                     .First( p => p.Name == parameter.Name );
            
            if ( parameter.Description == null )
            {
                parameter.Description = description.ModelMetadata.Description;
            }

            if ( parameter.Default == null )
            {
                parameter.Default = description.RouteInfo.DefaultValue;
            }

            parameter.Required |= !description.RouteInfo.IsOptional;
        }
    }
}

Examples

There are end-to-end examples using API versioning and Swashbuckle:

Clone this wiki locally