Documenting an ASP.NET Core API with OpenAPI / Swagger





3.00/5 (3 votes)
How to document ASP.NET Core API using OpenAPI / Swagger
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
- Conclusion
- References
- History
What is Swagger/ OpenAPI and Why Use it to Document Your API
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.
Getting Started
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.
Introduction of ASP.NET Core API Demo
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.
Using the Code
Installing the Swashbuckle.AspNetCore Package and Registering
Add the below nuget library SwaggerDemo
:
Swashbuckle.AspNetCore
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"
});
});
}
// This method gets called by the runtime.
// Use this method to configure the HTTP request pipeline.
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
Adding Swagger UI
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 = ""; // To available at root
});
//...
}
Once it is registered, open the below URL and check in below URL:
http://localhost:53456/index.html
Including XML Documentation on Action and Classes
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:
/// <summary>
/// Get customer detail by id
/// </summary>
///<param name="id" />This id is unique/primary key of customer
/// <returns>Customer details with id,
/// customername and cutomer code fields
[HttpGet]
[Route("{id}", Name = "GetCustomer")] public ActionResult<customer> Get(int id) {
//... }
Summary will look as shown below:
To Ignore XML Warning
Go to property of project and suppress XML warning (i.e., 1591) as shown below:
Adding API Information and Details
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);
});
API Explorer and Its Usage
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());
});
//...
}
Working with Multiple OpenAPI
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
{
// ...
}
References
- https://github.com/OAI/OpenAPI-Specification
- https://github.com/domaindrivendev/Swashbuckle.AspNetCore
History
- 10th July, 2020: Initial version