This guide walks you through the process of documenting your ASP.NET Core Web API using Swagger tools. From setup to advanced configurations, learn how to leverage Swagger to create detailed and interactive API documentation for your ASP.NET Core projects.
What is OpenAPI?
OpenAPI is a specification used for describing REST APIs. It’s language agnostic, and enables you to describe your entire API including:
- Available endpoints
- Operation parameters
- Authentication methods
- Contact and other information
You can write API specifications in YAML or JSON. With the OpenAPI specification, humans and computers can understand the capabilities of your API without having access to its source code.
What is Swagger?
Swagger is a set of open-source tools built around the OpenAPI specification. These tools can help you design, build, and document REST APIs. Swagger uses the OpenAPI specification of your API to understand its structure.
For example, Swagger UI is a tool that can visually render documentation in a browser for an API defined with the OpenAPI specification. Swagger Codegen can take the same OpenAPI specification of an API and generate client SDKs.
What is Swashbuckle?
Swashbuckle is an open-source Swagger implementation used for generating Swagger documentation for .NET Core APIs using .NET reflection.
There are three main components to Swashbuckle:
- Swashbuckle.AspNetCore.Swagger: This component is the Swagger object model and middleware to expose
SwaggerDocument
objects as JSON endpoints. - Swashbuckle.AspNetCore.SwaggerGen: This library is a Swagger generator that builds
SwaggerDocument
objects directly from your routes, controllers, and models. The library is typically combined with the Swagger endpoint middleware to automatically expose Swagger JSON. - Swashbuckle.AspNetCore.SwaggerUI: This package is an embedded version of the Swagger UI tool. It interprets Swagger JSON to build a rich, customizable experience for describing the web API functionality. It includes built-in test harnesses for the public methods.
Additionally, there’s the Swashbuckle CLI, a .NET global tool. Once installed, it empowers the generation of OpenAPI specifications during build/publish processes. You can find a link to download Swashbuckle CLI at the conclusion of this module.
By incorporating these libraries into your application, they dynamically generate and visualize your API documentation, ensuring it remains aligned with the latest version of your API. This creates a form of living documentation that evolves alongside your codebase.
Enable OpenAPI documentation in an ASP.NET Core Web API app
Before we dive into Swagger integration, let’s set up a basic ASP.NET Core Web API project. Follow these steps:
- Create a new ASP.NET Core Web API project.
- Define your API endpoints and models.
- Implement controller logic to handle HTTP requests
After that open the Program.cs and follow the below steps.
using Microsoft.OpenApi.Models;
using System.Reflection;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
//builder.Services.AddSwaggerGen();
builder.Services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "My XML Documentation Web API", Version = "v1" });
});
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My XML Documentation Web API V1");
});
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
The following figure illustrates an example of Swagger UI for an API, presenting essential information.
Enrich your OpenAPI documentation with XML comments and annotations
XML documentation comments provide additional context and information about your API endpoints, parameters, and models. By adding XML documentation and annotations to your code, you can enhance the quality of your Swagger documentation. Here’s how:
Add XML comments to your API
1.Configure Swagger to include XML comments in the generated documentation.
using Microsoft.OpenApi.Models;
using System.Reflection;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "My XML Documentation Web API", Version = "v1" });
// Set the comments path for the Swagger JSON and UI.
var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
c.IncludeXmlComments(xmlPath);
});
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My XML Documentation Web API V1");
});
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
2.Enable XML documentation generation in your project settings.
To enable the GenerateDocumentationFile
option as true we should follow the below steps.
- Right-click the project in
Solution Explorer
and selectEdit Project File
. - Add the following PropertyGroup section (or include the options in an existing PropertyGroup).
3.Add XML documentation comments to your code.
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace OpenAPI_documentation.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ItemsController : ControllerBase
{
private static List<Item> _items = new List<Item>
{
new Item { Id = 1, Name = "Item 1", Price = 10.5m },
new Item { Id = 2, Name = "Item 2", Price = 20.75m }
};
/// <summary>
/// Gets all items.
/// </summary>
/// <returns>A list of items.</returns>
[HttpGet]
public ActionResult<IEnumerable<Item>> Get()
{
return Ok(_items);
}
/// <summary>
/// Gets an item by ID.
/// </summary>
/// <param name="id">The ID of the item to retrieve.</param>
/// <returns>The item with the specified ID.</returns>
[HttpGet("{id}")]
public ActionResult<Item> Get(int id)
{
var item = _items.Find(i => i.Id == id);
if (item == null)
{
return NotFound();
}
return Ok(item);
}
/// <summary>
/// Creates a new item.
/// </summary>
/// <param name="item">The item to create.</param>
/// <returns>The newly created item.</returns>
[HttpPost]
public IActionResult Post([FromBody] Item item)
{
_items.Add(item);
return CreatedAtAction(nameof(Get), new { id = item.Id }, item);
}
/// <summary>
/// Updates an existing item.
/// </summary>
/// <param name="id">The ID of the item to update.</param>
/// <param name="item">The updated item data.</param>
/// <returns>No content.</returns>
[HttpPut("{id}")]
public IActionResult Put(int id, [FromBody] Item item)
{
var index = _items.FindIndex(i => i.Id == id);
if (index < 0)
{
return NotFound();
}
_items[index] = item;
return NoContent();
}
/// <summary>
/// Deletes an item by ID.
/// </summary>
/// <param name="id">The ID of the item to delete.</param>
/// <returns>No content.</returns>
[HttpDelete("{id}")]
public IActionResult Delete(int id)
{
var index = _items.FindIndex(i => i.Id == id);
if (index < 0)
{
return NotFound();
}
_items.RemoveAt(index);
return NoContent();
}
}
}
Here’s the XML nodes in use:
- summary: A high-level summary of what the method/class/field is or does.
- remarks: More detail about the method/class/field.
- param: A parameter to the method, and what it represents.
- returns: A description of what the method returns.
Once you enable XML comments, the Swashbuckle tooling can include your XML documentation comments in the OpenAPI documentation, and allows you to view it in Swagger UI.
Add Swashbuckle annotations to your API
So far, our API returns the status code 200 when it can get the items. In the description of the Get all items
method, note the case when a not able to get the items.
A more robust way to tell developers the response types and error codes is through the following XML comments and data annotations. Swashbuckle and the Swagger tooling use these values to clearly generate an OpenAPI description of the expected HTTP response codes. Follow the steps below to achieve this more comprehensive approach.
1.In ItemsController.cs, replace Gets all items
with the following code and comment.
/// <summary>
/// Gets all items.
/// </summary>
/// <returns>A list of items.</returns>
[HttpGet]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public ActionResult<IEnumerable<Item>> Get()
{
return Ok(_items);
}
Conclusion
In conclusion, leveraging Swagger tools like Swashbuckle can greatly enhance the documentation process for ASP.NET Core Web APIs. By integrating Swashbuckle’s components into your project, you can generate interactive API documentation effortlessly, ensuring that it remains in sync with your codebase. With the ability to customize the appearance and behavior of Swagger UI, as well as enriching your documentation with XML comments ,you can create comprehensive and user-friendly API documentation that facilitates communication and adoption among developers, clients, and stakeholders. Embracing Swagger tools not only streamlines the documentation workflow but also contributes to the overall quality and accessibility of your ASP.NET Core Web API.
References
- https://www.dotnetnakama.com/blog/all-about-web-api-versioning-in-asp-dotnet-core/
- https://devblogs.microsoft.com/dotnet/asp-net-core-updates-in-net-6-preview-7/#minimal-host-and-template-improvements
- https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/xmldoc/
- https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/xmldoc/recommended-tags
No Comment! Be the first one.