This article will discuss about implementing Open API (Swagger) for ASP.NET Core 6.0 minimal API. Today I saw one video from Maria Naggaga about Minimal APIs. She was showing a demo of Web API with swagger support. So thought I will implement the same. But it was not working for me. I was getting a lot of errors - both compile time and runtime. Then I looked into the ASP.NET Core source code and found one extension method which was not available in the runtime I was using. So I upgraded the version and installed the - 6.0.100-preview.6.21357.52 version and it started working. If you’re not using this version the code in this blog post will not work. You can download the latest version of .NET SDK from here - https://github.com/dotnet/installer#installers-and-binaries
To get started you need to create an ASP.NET Core empty project with .NET 6.0. This will be something like this.
Then you need to add reference of Swashbuckle.AspNetCore package to the project. And once you add the reference you can modify the code to use swagger middleware and swagger UI like this.
Now if you run this code, you will get a runtime exception like this - Some services are not able to be constructed.
To fix this you need to configure ApiExplorer with Endpoint metadata. You can do this by adding - builder.Services.AddEndpointsApiExplorer(); before the builder.Services.AddSwaggerGen(); method, like this.
And now if you run again, it will work properly. And you can browse the /swagger endpoint to view the Open API specification. You will get something like this.
Now it is running properly. So I thought of modifying my existing minimal API code from this blog post and enable Open API for the same. But it didn’t worked for me. I tried with few other endpoints it was working properly. Then I modified my code a little bit and used one helper class from David Fowler’s Github project. And it started working properly. Here is the minimal todo web api with entity framework in memory provider.
And if you run this, you will be able to see something like this.
This way you will be able to document minimal web api using Open API or Swagger. Currently this code will work only if you’re using Asp.Net Core SDK - 6.0.100-preview.6.21357.52 version. As I mentioned in my earlier blog posts you can make it more compact if you’re using C# 10 features.