Now that .NET Core 3 is out I thought it would be a good time to revisit exposing API documentation using Swagger/OpenAPI. In the past, I have written posts on using Swashbuckle to expose Swagger documentation, but for this post, I’m going to try out NSwag.
What is OpenAPI vs Swagger?
To quote the Swagger docs:
OpenAPI Specification (formerly Swagger Specification) is an API description format for REST APIs. An OpenAPI file allows you to describe your entire API. API specifications can be written in YAML or JSON. The format is easy to learn and readable to both humans and machines.
Swagger is a set of open-source tools built around the OpenAPI Specification that can help you design, build, document and consume REST APIs.
What is NSwag?
Quoting the NSwag GitHub readme:
NSwag is a Swagger/OpenAPI 2.0 and 3.0 toolchain for .NET, .NET Core, Web API, ASP.NET Core, TypeScript (jQuery, AngularJS, Angular 2+, Aurelia, KnockoutJS and more) and other platforms, written in C#. The OpenAPI/Swagger specification uses JSON and JSON Schema to describe a RESTful web API. The NSwag project provides tools to generate OpenAPI specifications from existing ASP.NET Web API controllers and client code from these OpenAPI specifications.
One neat thing about NSwag is it also has the tooling to help generate the API consumer side in addition to the OpenAPI specs.
Sample Project
For this post, I created a new API project via the .NET CLI using the following command. Not that all this can be done via the Visual Studio UI if that is your preference.
dotnet new webapi
For me, this project is going to be the start of a new series of posts so I also added a solution file and added the project created above to it. These commands are optional.
dotnet add sln dotnet sln add src\ContactsApi\ContactsApi.csproj
Add NSwag
Using the CLI in the same directory as the project file use the following command to add a reference to NSwag.AspNetCore to the project.
dotnet add package NSwag.AspNetCore
Next, in your favorite editor open the project/directory we created and open the Startup.cs file. In the ConfigureServices function add services.AddOpenApiDoccument.
public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.AddOpenApiDocument(); }
Then at the end of the Configure function add calls to app.UseOpenApi and app.UseSwaggerUi3.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) app.UseDeveloperExceptionPage(); app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); app.UseOpenApi(); app.UseSwaggerUi3(); }
Note that NSwag also supports ReDoc if you prefer that over Swagger UI.
Sample Model and Controller
Now that we have NSwag installed let’s create a new endpoint for it to display. As per my norm, I will be doing this using contacts as an example. First I created a Models directory and then added the following Contact class to it.
public class Contact { public int Id { get; set; } public string Name { get; set; } public string Address { get; set; } public string City { get; set; } public string State { get; set; } public string PostalCode { get; set; } public string Phone { get; set; } public string Email { get; set; } }
Next, in the Controllers directory add a ContactsController, which in the following code returns a list of 5 generic contacts.
[ApiController] [Route("[controller]")] public class ContactsController : ControllerBase { private readonly ILogger<ContactsController> _logger; public ContactsController(ILogger<ContactsController> logger) { _logger = logger; } [HttpGet] public IEnumerable<Contact> Get() { return Enumerable.Range(1, 5).Select(index => new Contact { Id = index, Name = $"Test{index}", Address = $"{index} Main St.", City = "Nashville", State = "TN", PostalCode = "37219", Phone = "615-555-5555", Email = $"test{index}@test.com" }); } }
Results
Run your project and then in a browser navigate to your base URL /swagger. For example my for my project that is https://localhost:5001/swagger. You should see something like the following that will let you explore your API and even execute requests against your API using the Try it out button you see in the UI.
Wrapping Up
Just like with Swashbuckle, NSwag makes it very easy to get started providing API documentation. This post just covers the very basics and I’m looking forward to digging into some of the more advanced features that NSwag has such as client generation.
Microsoft has a great article on Getting Started with NSwag on their docs site that I recommend reading. This is a preview of something I plan to cover in the future, but there are attributes that can be added to controllers that help NSwag provide better details about what your API can return and Microsoft has a doc on Use web API conventions that makes it easy to apply some of the common conventions.
Also published on Medium.
Hi thanks for the article! I have problems with API versioning and nswag with .net core 3.0. Do you have an example ? I have found only deprecated examples so far.
Manlio
Your welcome, Manlio! I don’t have an example of versioning yet, not had the need yet. I will add it to my list of things to explorer for sure.
Hey Manlio
Can you create an issue on GitHub with some more information?
Thanks
Rico
Getting DI Error with this in ASP.NET Core 3:
System.InvalidOperationException: ‘API Explorer not registered in DI.’
Getting this error too
For those who are getting System.InvalidOperationException: ‘API Explorer not registered in DI.’
Adding line services.AddControllers(); solved my the problem. More details below
https://tpu.thinkpower.com.tw/tpu/articleDetails/1735
Hi Sajan, I’m afraid the link you posted is broken.