Add/Hide OpenAPI Swagger based on Environment (DEV, TEST, PROD)
Today in this article, We shall see how to enable Swagger OpenAPI documentation and Add/Hide OpenAPI Swagger based on Environment (DEV, TEST, PROD)
You might get this requirement on a few occasions where you may want to control the display of API methods based on the environment example DEV, TEST, PROD.
There could be multiple requirements like hide or exclude routes API, endpoint, or Controller for Swagger OpenAPI documentation based on the environment your API running.
This customization could be of use to many of you as swagger is not just an API description tool.
It also allows you to test any of your APIs by passing inputs and getting the required results.
Today in this article, we will cover below aspects,
Today we will control how to display API based on a selected environment i.e. if you are running your swagger in the “TEST” environment then it will not display API that is in DEV or in progress and not meant to be used in a higher environment.
ASP.NET Core uses OpenAPI V3.0 specifications which are guidelines and specifications around how the API documentation should be.
In today’s article, we shall cover below,
- Adding OpenAPI V3 documentation specification to API
- Enabling Swagger based on the Environment
Create ASP.NET Core API
Create ASP.NET Core 3.1 or .NET 5.0 API
Add Swashbuckle.AspNetCore NuGet package
Please add below Nuget package to your API using a Command prompt or PMC(package manager console) or Nuget Package Manager
PM> Install-Package Swashbuckle.AspNetCore -Version 5.6.3
Note: Please use the version to the latest available.
This NuGet package shall add all other required components as shown below and you need not have to add them explicitly,
- Swashbuckle.AspNetCore.SwaggerUI
- Swashbuckle.AspNetCore.Swagger
- Swashbuckle.AspNetCore.SwaggerGen
Let’s talk about a simple scenario where I have new API development going on and that API swagger definition I don’t want to be available to the TEST region yet.
Below are the two APIs that I would like to control the display based on the environment.
Let’s assume below the sample API route and I have already released it for DEV and then moved it to TEST environment.
[HttpGet]
[Route("US")]
public IEnumerable<WeatherForecastUS> GetWatherUSA()
{
var rng = new Random();
return Enumerable.Range(1, 5).Select(index => new
WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = rng.Next(-20, 55),
Summary = Summaries[rng.Next(Summaries.Length)]
})
.ToArray();
}
Now let’s assume, I have a new route as below for UK which I would like to display for DEV alone but not the TEST or PROD region.
[HttpGet]
[Route("UK")]
public IEnumerable<WeatherForecastUK> 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();
}
Currently, you shall see the swagger API definition generated as below,
Please see the below article on enabling basic Swagger API documentation,
Adding IDocumentFilter implementation
Please add the IDocumentFilter implementation as below,
public class CustomEnviornmentFilter : IDocumentFilter { public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context) { // Add your implementation here } }
Below is the complete implementation for Apply method,
Remove or Hide API routes from the Swagger API definition
Below is the implementation for removing the required routes from API documentation.
private static void RemoveOtherRoutes(OpenApiDocument swaggerDoc, string kepath)
{
var removeRoutes = swaggerDoc.Paths.Where(
x => x.Key.ToLower().Contains(kepath.ToLower()))
.ToList();
removeRoutes.ForEach(x => { swaggerDoc.Paths.Remove(x.Key); });
}
Update ConfigureServices() method
You need to enable the above CustomDocument filter within AddSwaggerGen,
c.DocumentFilter<CustomEnviornmentFilter>();
Please here for more details on the configuration.
Enabling Custom Attributes on Method or Controller
I see custom attribute annotation as the easiest way of managing the method environment.
Let’s create three Custom Attributes for Dev , Test and Prod as below,
/// <summary> /// /// </summary> public class DevApiAttribute : ActionFilterAttribute { } /// <summary> /// /// </summary> public class TestApiAttribute : ActionFilterAttribute { } /// <summary> /// /// </summary> public class ProdApiAttribute : ActionFilterAttribute { }
Next, you need to just enable these attributes for each Controller or API route to specify the environment.
Let’s execute the Swagger definition in DEV environment,
That’s all, with the above arrangements, the above routes for TEST or PROD will be removed/hidden from generated swagger documentation.
I found this way we get better control on what API to show or hide.
The above settings can be applied at the Controller or Individual method/route level.
Likewise please decorate your Routes/Methods or Controller as required.
Feature Toggle for swagger routes
The above way of hiding or removing the swagger route will also resemble feature toggling.
The good thing about this approach is you can very much integrate this logic with your existing feature toggle architecture if any.
Do you have any comments or suggestions or any better approach to deal with this?
Please sound off your comments below.
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.