Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swagger - hide api version parameters

Is it possible to hide the 'api-version' and 'x-api-version' parameters?

        services.AddApiVersioning(config =>
        {
            config.ReportApiVersions = true;
            config.DefaultApiVersion = new ApiVersion(1, 0);
            config.AssumeDefaultVersionWhenUnspecified = true;

            config.ApiVersionReader = ApiVersionReader.Combine(
             new QueryStringApiVersionReader(),
             new HeaderApiVersionReader()
             {
                 HeaderNames = { "x-api-version" }
             });
        });

        services.AddVersionedApiExplorer(
            options =>
            {
                // note: the specified format code will format the version as "'v'major[.minor][-status]"
                options.GroupNameFormat = "'v'VVV";

                options.DefaultApiVersionParameterDescription = "Do NOT modify api-version!";
            });

I already checked how-to-set-up-swashbuckle-vs-microsoft-aspnetcore-mvc-versioning which implements a 'RemoveVersionFromParameter' method, but in that case the Swagger page would loose the api version and always uses the default v1.0. As shown in the code snippet, I am using the QueryStringApiVersionReader and HeaderApiVersionReader, but I don't want to support the url api versioning.

Note: The API does have multiple swagger json pages for all versions (e.g. V1, V1.1, V2.0)

enter image description here

like image 767
Odrai Avatar asked Mar 21 '20 19:03

Odrai


2 Answers

You can try an operation filter. This is similar to Helder's solution, but the implementation doesn't have to be at the document level, so it seems simpler:

public void Configure(SwaggerGenOptions options)
{
    // Filter out `api-version` parameters globally
    options.OperationFilter<ApiVersionFilter>();
}

internal class ApiVersionFilter : IOperationFilter
{
    public void Apply(OpenApiOperation operation, OperationFilterContext context)
    {
        var parametersToRemove = operation.Parameters.Where(x => x.Name == "api-version").ToList();
        foreach (var parameter in parametersToRemove)
            operation.Parameters.Remove(parameter);
    }
}
like image 78
Paweł Bulwan Avatar answered Oct 31 '22 05:10

Paweł Bulwan


You can add your own custom CSS and use it to hide those elements (and do any other customisation you want).

app.UseSwaggerUI(c =>
{
    ...
    c.InjectStylesheet("/swagger-ui/custom.css");
    ...
});

Edit - example:

Suppose you're trying to hide - in my example; you can easily adapt it to yours - the tenantId parameter in this "Remove Basket" operation:

enter image description here

This would do that:

div#operations-baskets-remove tr[data-param-name="tenantId"] {
    display: none;
}
like image 43
sellotape Avatar answered Oct 31 '22 05:10

sellotape