Skip to content

Swashbuckle Integration

Chris Martinez edited this page Nov 16, 2021 · 14 revisions

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. 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

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 )
  {
    if ( apiDescription is VersionedApiDescription versionedApiDescription )
    {
      operation.deprecated |= versionedApiDescription.IsDeprecated;
    }

    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 or ASP.NET Core with OData

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

using static Microsoft.AspNetCore.Mvc.Versioning.ApiVersionMapping;

public class SwaggerDefaultValues : IOperationFilter
{
  public void Apply( Operation operation, OperationFilterContext context )
  {
    var apiDescription = context.ApiDescription;

    operation.Deprecated |= apiDescription.IsDeprecated();

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

    foreach ( var parameter in operation.Parameters.OfType<NonBodyParameter>() )
    {
      var description = apiDescription.ParameterDescriptions
                                      .First( p => p.Name == parameter.Name );
            
      if ( parameter.Description == null )
      {
        parameter.Description = description.ModelMetadata?.Description;
      }

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

      parameter.Required |= description.IsRequired;
    }
  }
}

Examples

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

Clone this wiki locally