How to Hide Swagger API or Action Method from Controller – Guidelines
In this article, we will see how to Swagger Hide API or route Method. We shall see a few approaches for achieving the same.
Today in this article, we will cover below aspects,
IOperationFilter and IDocumentFilter in ASP.NET Core services introduced based on OpenAPI specification i.e swagger v3.0. Same interfaces have also existed for swagger v2.0.
Swagger or Open API specification provides the advantage of understanding the REST services easily (especially if developers are consuming any new web API ) plus helps provide easily ready documentation and details of capabilities given service owns.
The approach I – A swagger definition can be customized at the Service or Operation level using two basic interfaces IOperationFilter and IDocumentFilter interfaces based on OpenAPI specification i.e swagger v3.0.
Approach II– We shall leverage the Swashbuckle-provided ApiExplorerSettings attributes. This attribute ApiExplorerSettings when added to the controller class or individual controller methods can ignore the given method and its metadata when generating the documentation.
Getting Started
Create ASP.NET Core 3.1or 5.0 API
Enable Swagger in API
Kindly follow the basic steps as detailed in the below article to enable swagger documentation,
After following the above article below the swagger definition generated for API,
Above I have two GET routes out of which I would like to show or hide per need basis.
Approach 1- Swagger hide endpoint using Custom attribute
Let’s see a requirement where I need to hide all methods or actions using a combination of custom attribute and IDocumentFilter interfaces.
This approach is simple and effective for performing hide or exclude controller or hide endpoint or hide API or ignore the controller.
Let’s create a custom attribute called IgnoreApi as below,
Below is how I am annotating the attribute on one of the methods,
[HttpGet]
[Route("UK")]
[IgnoreApi]
public IEnumerable<WeatherForecastNew> GetWeatherUK()
{
var rng = new Random();
return Enumerable.Range(1, 5).Select(index => new WeatherForecastNew
{
DateOfForcast = DateTime.Now.AddDays(index),
Temperature = rng.Next(-20, 55),
Summary = Summaries[rng.Next(Summaries.Length)]
})
.ToArray();
}
Let’s now implement the IDocumentFilter interface. Here we shall try to get method metadata programmatically. We will search for available attributes i.e IgnoreAPI on the method. Once attributes are found we shall remove such method route from the generated documentation.
Below is the complete implementation of the custom IDocumentFilter implementation.
Please enable DocumentFilter to Swagger UI as below,
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddSwaggerGen(c =>
{
c.DocumentFilter<CustomSwaggerDocFilter>();
c.SwaggerDoc("v1", new OpenApiInfo { Title ="TheCodeBuzzService", Version = "v1", });
var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
c.IncludeXmlComments(xmlPath);
});
}
The above steps are explained in detail in the article: Add Swagger API Documentation in ASP.NET Core
Now generated Swagger documentation will ignore the other method and will show only 1 route.
With this approach, you get better control over what methods you would like to hide and show in the swagger definition which you can extend further by showing or hiding the API definition based on the environment.
Approach – II – Using ApiExplorerSettings attribute
Another simple approach is to use the ApiExplorerSettings attribute on all the methods for which documentation needs not to be created.
You can apply ApiExplorerSettings on the Controller also to be able to ignore all methods under that Controller.
[HttpGet]
[Route("UK")]
[ApiExplorerSettings(IgnoreApi = true)]
public IEnumerable<WeatherForecastNew> GetWeatherUK()
{
var rng = new Random();
return Enumerable.Range(1, 5).Select(index => new WeatherForecastNew
{
DateOfForcast = DateTime.Now.AddDays(index),
Temperature = rng.Next(-20, 55),
Summary = Summaries[rng.Next(Summaries.Length)]
})
.ToArray();
}
The generated swagger definition will be as below,
This approach is however very generic and does not provide you full control based on your need.
That’s all. Hope you find this article useful.
Do you have any comments or ideas or any better suggestions to share?
Please sound off your comments below.
Happy Coding !!
References:
Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.
This confused me for a bit but there is a typo at the end in the Apply function,
it should be removeRoutes.ForEach(x => { swaggerDoc.Paths.Remove(x.Key); })
Hello Jonathan- Appreciate your inputs. I corrected the typo in the code. Thank you
notes on approach #1:
1) you can get ‘devAttributes’ in a single line: description.ActionDescriptor.EndpointMetadata.OfType()
2) using ‘.Contains()’ to filter ‘swaggerDoc.Paths’ is incorrect: there could be ‘/api/name’ and ‘/api/name/subname’
3) ‘.Remove(kepath)’ instead of ‘Remove(x.Key)’ is also does not seem correct
Hi Constantin Tokarev, Thanks for your inputs. Appreciate that. Yes absolutely, One can extend/tweak the above logic as required. I liked a few of your suggestions too.Thanks !