Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Swashbuckle Integration

Although the API explorers for API versioning provide all of the necessary information, there is select information that OpenAPI (formerly Swagger) and Swashbuckle will not wire up for you. This includes iterating through all the available API versions so that they don’t have to be imperatively declared and changed one at a time. 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.

Remember to add the necessary references to one or both of the following:

public class SwaggerDefaultValues : IOperationFilter
{
    public void Apply(
        Operation operation,
        SchemaRegistry schemaRegistry,
        ApiDescription apiDescription )
    {
        operation.deprecated |= apiDescription.IsDeprecated();

        if ( operation.parameters == null )
        {
            return;
        }

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

            parameter.description ??= description.Documentation;
            parameter.@default ??= description.ParameterDescriptor?.DefaultValue;
        }
    }
}

Use MultipleApiVersions to iterate over each ApiDescription and collate them by their corresponding group. The default group name for each ApiDescription is the formatted API version that is associated with it.

configuration.EnableSwagger(
    "{apiVersion}/swagger",
    swagger =>
    {
        swagger.MultipleApiVersions(
            ( apiDescription, version ) => apiDescription.GetGroupName() == version,
            info =>
            {
                foreach ( var group in apiExplorer.ApiDescriptions )
                {
                    info.Version( group.Name, $"Example API {group.ApiVersion}" )
                        .Description( "An example API" );
                }
            } );
        swagger.OperationFilter<SwaggerDefaultValues>();
    } )
    .EnableSwaggerUi( swagger => swagger.EnableDiscoveryUrlSelector() );

Examples

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