How to generate a swagger.json file on build in .NET core, .NET 5 and above

Wouter
3 min readFeb 5, 2021

Swagger is a powerful tool to create Web APIs in .NET Core (and .NET 5). When your API is online there is a swagger.json file that contains the entire definition of your API. But did you know that there is a way to generate this swagger.json file on build time?

What is a swagger file?

A swagger file (nowadays known as a OpenAPI specification file) is a JSON file that contains the entire definition of your API. All endpoints, input- and response types are documented in it. If you are using the swagger nuget package in your project, this file is automatically created for you.

example of a swagger specification

You can simply access this file by navigation to your API and adding /swagger.json and the end of the url.

Generate the file on build time

Now why would you need this swagger.json file on build time? If you are using an API gateway this file is used to configure the endpoints of your gateway. In this case you would need the file before your API is published online.

You could also add a Devops pipeline task that is going to validate the file for you. You could even set up a quality gate that requires a valid swagger file before your API can be deployed!

--

--