With Swagger (OpenAPI) we can generate automatic interactive documentation of our Web APIs. Sometimes we will have versioned Web APIs which we want to document with Swagger. In this we will see how to do this.
- ASP.NET Core 3.1
- Swashbuckle.AspNetCore: 5.4.1
Suppose we have a versioned Web API, where we use folders to separate the different versions of our controllers. Thus, we have V1 and V2 folders inside our Controllers folder, and a WeatherForecastController in each folder:
Therefore, the namespace of each controller corresponds to its folder, like this:
If we configure Swagger like this:
And we go to the swagger user interface by accessing the endpoint: /swagger/index.html, we come across the following:
Which can be a problem, because your users will see each endpoint repeated by each version of the Web API.
The solution is to inform Swagger that our Web API is versioned. We must also write code to tell Swagger how to differentiate one version from another. In our case it is according to the namespace where the controller is located.
To tell Swagger that the Web API is versioned, we create a Swagger document for each version, and add an endpoint for each version:
The next task is to tell Swagger how to differentiate one version of a controller apart from another. For that we must create a convention.
With a convention we inform Swagger about our architecture. This way we can control how Swagger generates the Swagger document, and therefore, the UI.
Create the following class:
What we do is group controllers according to the last segment of their namespace. Thus, the controllers whose namespace ends in v1 will be grouped under the name “v1“, those that end in v2 are grouped as “v2“, etc.
Now we must apply the convention. For that we go to AddControllers in ConfigureServices and add the convention:
And this is it. With this we can see in the Swagger UI that we have our endpoints separated by versions in different Swagger Docs:
If you want to learn how to develop RESTful Web APIs with ASP.NET Core, get my udemy course today: