Documentation is always a tedious, but essential task. By using OpenAPI / Swagger, which integrates nicely with ASP.NET Core, you can take on this task.
Table of Contents
- What is Swagger/ OpenAPI and Why Use it to Document your API
- Getting Started
- Introduction of ASP.NET Core API Demo
- Using the Code
- Installing the Swashbuckle.AspNetCore Package and Registering
- Adding Swagger UI
- Including XML Documentation on Action and Classes
- To Ignore XML Warning
- Adding API Information and Details
- Working with Multiple OpenAPI
- Conclusion
- References
- History
Swagger is an open-source software framework backed by a large ecosystem of tools that helps developers design, build, document, and consume RESTful web services. While most users identify Swagger by the Swagger UI tool, the Swagger toolset includes support for automated documentation, code generation, and test-case generation.
Imagine in your company if your colleague Front end developer or other team using your API in same company, where you have to spend your time answering the same question, how to integrate with this API and specification. Through Swagger or OpenAPI, you can solve your problem.
OpenAPI Specification, originally known as the Swagger Specification. Both terms are interchangeable, but OpenAPI is the preferred term. Once you start surfing around for information on OpenAPI or Swagger, you will quickly encounter terms like Swagger UI, Swashbuckle, NSwag, and so on.
Swagger is a set of open source tools built around that OpenAPI specification.
Swashbuckle.AspNetCore
helps with working with OpenAPI in ASP.NET Core.
For this tutorial, I will work on an ASP.NET Core 3.1 API to demonstrate the features of the Swagger. I use Visual Studio 2019 Community as my IDE.
We are going to build Swagger on top of this API application, where it contains simple CRUD operation with Entity Framework Core using InMemory provider Sample Startup Project.
Add the below nuget library SwaggerDemo
:
Register swagger in ConfigureServices
and Configure
methods in Startup.cs file:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using SwaggerDemo.Data;
namespace SwaggerDemo
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddSwaggerGen(setupAction =>
{
setupAction.SwaggerDoc(
"OpenAPISpecification",
new Microsoft.OpenApi.Models.OpenApiInfo()
{
Title = "Customer API",
Version = "1"
});
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseRouting();
app.UseSwagger();
}
}
}
Once it is registered, open the below URL and check that it is working:
http://localhost:53456/swagger/OpenAPISpecification/swagger.json
Register swagger UI in Configure
methods in Startup.cs file as shown below:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseSwagger();
app.UseSwaggerUI(setupAction =>
{
setupAction.SwaggerEndpoint
("/swagger/OpenAPISpecification/swagger.json", "Customer API");
setupAction.RoutePrefix = "";
});
}
Once it is registered, open the below URL and check in below URL:
http://localhost:53456/index.html
Go to property of project and add XML document as shown below:
Incorporate this XML in ConfigureServices
:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddDbContext<customercontext>(opt =>
opt.UseInMemoryDatabase("InMemoryCustomerDB")
);
services.AddSwaggerGen(setupAction =>
{
var xmlCommentsFile =
$"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlCommentsFullPath =
Path.Combine(AppContext.BaseDirectory, xmlCommentsFile);
setupAction.IncludeXmlComments(xmlCommentsFullPath);
});
}
Add summary comment as shown below:
[HttpGet]
[Route("{id}", Name = "GetCustomer")] public ActionResult<customer> Get(int id) {
Summary will look as shown below:
Go to property of project and suppress XML warning (i.e., 1591) as shown below:
Add the below information details if required:
services.AddSwaggerGen(setupAction =>
{
setupAction.SwaggerDoc(
"OpenAPISpecification",
new Microsoft.OpenApi.Models.OpenApiInfo()
{
Title = "Customer API",
Version = "1",
Description ="Through this API you can access customer details",
Contact = new Microsoft.OpenApi.Models.OpenApiContact()
{
Email="amit.naik8103@gmail.com",
Name ="Amit Naik",
Url = new Uri("https://amitpnk.github.io/")
},
License = new Microsoft.OpenApi.Models.OpenApiLicense ()
{
Name ="MIT License",
Url =new Uri("https://opensource.org/licenses/MIT")
}
});
var xmlCommentsFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlCommentsFullPath =
Path.Combine(AppContext.BaseDirectory, xmlCommentsFile);
setupAction.IncludeXmlComments(xmlCommentsFullPath);
});
ApiExplorer
is an abstraction on top of ASP.NET Core MVC that exposes metadata about that application:
Will see how we can use it.
Add below nuget library SwaggerDemo
:
Microsoft.AspNetCore.Mvc.Api.Analyzers
Register in Startup.cs file for global level:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc(setupAction =>
{
setupAction.Filters.Add(
new ProducesResponseTypeAttribute(StatusCodes.Status400BadRequest));
setupAction.Filters.Add(
new ProducesResponseTypeAttribute(StatusCodes.Status406NotAcceptable));
setupAction.Filters.Add(
new ProducesResponseTypeAttribute
(StatusCodes.Status500InternalServerError));
setupAction.Filters.Add(
new ProducesDefaultResponseTypeAttribute());
});
}
If your API module is increasing and now you need to make it group in ConfigureService
and Configure
method as shown in the following steps:
services.AddSwaggerGen(setupAction =>
{
setupAction.SwaggerDoc(
"OpenAPISpecificationCustomer",
new Microsoft.OpenApi.Models.OpenApiInfo()
{
Title = "Customer API",
Version = "1",
Description = "Through this API you can access customer details",
Contact = new Microsoft.OpenApi.Models.OpenApiContact()
{
Email = "amit.naik8103@gmail.com",
Name = "Amit Naik",
Url = new Uri("https://amitpnk.github.io/")
},
License = new Microsoft.OpenApi.Models.OpenApiLicense()
{
Name = "MIT License",
Url = new Uri("https://opensource.org/licenses/MIT")
}
});
setupAction.SwaggerDoc(
"OpenAPISpecificationWeatherDefault",
new Microsoft.OpenApi.Models.OpenApiInfo()
{
Title = "Weather default API",
Version = "1",
Description = "Through this API you can access customer details",
Contact = new Microsoft.OpenApi.Models.OpenApiContact()
{
Email = "amit.naik8103@gmail.com",
Name = "Amit Naik",
Url = new Uri("https://amitpnk.github.io/")
},
License = new Microsoft.OpenApi.Models.OpenApiLicense()
{
Name = "MIT License",
Url = new Uri("https://opensource.org/licenses/MIT")
}
});
app.UseSwaggerUI(setupAction =>
{
setupAction.SwaggerEndpoint
("/swagger/OpenAPISpecificationCustomer/swagger.json", "Customer API");
setupAction.SwaggerEndpoint
("/swagger/OpenAPISpecificationWeatherDefault/swagger.json", "Weather default API");
setupAction.RoutePrefix = string.Empty;
});
[Route("api/[controller]")]
[ApiExplorerSettings(GroupName = "OpenAPISpecificationCustomer")]
[ApiController]
public class CustomerController : ControllerBase
{
}
- 10th July, 2020: Initial version