John
John

Reputation: 331

Swashbuckle versioning choose default API version to appear in Swagger

I am versioning my API and I would like to display the newest API version in Swagger as the default. For example, my API has 2 versions, when someone chooses to display the Swagger, the version that appears first is the V1.0. The user has to manually choose the newest version to display.

In the image below we can see that the default version that appears to the user when the application starts is the V1.0.

API Versioning Swagger

I would like to know if it is possible to display the newest API version to the user by default.

Upvotes: 5

Views: 3111

Answers (2)

Hugo Hilário
Hugo Hilário

Reputation: 2908

The solution for me was to add an OrderByDescending clause into the following block of code:

// build a swagger document and endpoint for each discovered API version
c.MultipleApiVersions(
    (apiDescription, version) => apiDescription.GetGroupName() == version,
    info =>
    {
        foreach (var group in apiExplorer.ApiDescriptions.OrderByDescending(p => p.ApiVersion))
        {
            var description = "My Company API";
    
            info.Version(group.Name, $"My Company API {group.ApiVersion}")
                .Contact(ca => ca.Name("My Company).Email("[email protected]"))
                .Description(description)
                .License(l => l.Name("My Company").Url("https://mycompany.com"))
                .TermsOfService("");
        }
    });

On my case, I also use that iteration to apply some UI specifics, according to my needs.

Upvotes: 1

John
John

Reputation: 331

First I added the IApiVersionDescriptionProvider in the Configure class in Startup.cs as shown below:

Configure Method in Startup.cs

After that, I had to reverse the list that contained the versions available for the api in the app.UseSwaggerUI().

The order in which you configure Swagger UI in Startup.cs Configure method determines the dropdown list order.

        app.UseSwaggerUI(c =>
        {
            foreach (var description in apiVersionDescriptionProvider.ApiVersionDescriptions.Reverse())
            {
                // Create the Swagger endpoints for each version
                c.SwaggerEndpoint($"/swagger/" +
                    $"LibraryOpenAPISpecification{description.GroupName}/swagger.json",
                    description.GroupName.ToUpperInvariant());
            }
            c.RoutePrefix = ""; // swagger UI at the root index.html
        });

The following answer by @Bob Ash was very helpful - How can i specify the default opening version of swagger?

By doing so, I successfully have now the V2.0 displayed as the default version for the api:

enter image description here

Upvotes: 8

Related Questions