Introduction
Documentation plays a very important role to understand how the application works. In terms of Web API, a mobile developer or frontend developer needs to understand how the endpoint works and what are the dependencies to use any endpoint in a correct way. Generally, Web API documentation is a more technical explanation. There are many ways to create documentation of Web API. XML comments is one of them. This article demonstrates how to use XML comments as documentation and integrate it with Swagger.
Pre-requisites
All the demonstration and code example used in this article is based on Visual Studio 2022 and .NET 7.0. So, I assume you are familiar with using Microsoft Visual Studio along with C#.
XML Comments
XML comments are used to add human readable descriptions in the source code. It makes it easy to understand what the code is dealing with. C# offers three different comments, single-line, multiline, and documentation comments.
Single Line Comments
Single line comments start with a double slash (//
). The compiler ignores everything on the line that starts with //
. This can be used to add some description or to ignore some lines of code from the compiler.
private void SomeMethod() {
//This is single line comment
//This is another line of single line comment
//var message = "This is testing message";
var moreMessage = "This is more message";
var data = Enumerable.Range(1, 5).Select(index => new WeatherForecast {
Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
}).ToArray();
}
Multi-Line Comment
Multi-line comments starts with /*
and ends with */
. Multi-line comments can span over multiple lines or can be a single line as well starting with /*
and ends with */
. All the content that is inside /*
and */
will ignore by compiler. This is also used to add some description or to ignore some lines of code from compiler.
private void SomeMethod() {
/*This is multi line comment in one line*/
/*This is multi line comment in multiple line
This is another line of comment
var message = "This is testing message";
var moreMessage = "This is more message";*/
var data = Enumerable.Range(1, 5).Select(index => new WeatherForecast {
Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
}).ToArray();
}
Documentation Comment
Documentation comment starts with triple slashes (///
). Documentation comments use XML elements to define the structure of output. You can add them above a class, methods, operators, indexers, constructors, and properties. C# compiler collects documentation comments from the entire application, verifies, and outputs into an XML file.
/// <summary>
/// Post weather forecast
/// </summary>
/// <param name="forecast">WeatherForeCast object</param>
/// <returns>Returns string response</returns>
[HttpPost]
public IActionResult Post(WeatherForecast forecast)
{
//Post business logic here
return Ok();
}
Swagger
Swagger (OpenAPI) is an open-source tool for creating interactive API documentation. It interacts with REST API using the Swagger UI. In Swagger UI you can see the explanation from documentation, and it also gives you an overview of what are the parameters needed and how the API responds. Responses can be in JSON or XML format. Basically, you can use Swagger UI for API testing tool as well.
Project Setup
In this article, I am using default ASP.NET Core Web API project and its default controller and model to explain. To use Swagger in your project, you have to check Enable OpenAPI support while creating a Web API project.
You can install Swagger manually also. To install manually, you can do it from NuGet Package Manager or using NuGet command in Package Console Manager. You can use below command.
PM> Install-Package Swashbuckle.AspNetCore
After installing this package, look at Program.cs
. You will find Swagger service is registered and middleware is added for development environment. With manual installation, you have to register service and add middleware code manually.
If you run the application without doing anything then you will see the UI as in the screenshot.
Output Documentation Comments into XML
To output documentation comment in an XML file you have to enable option to generate API documentation. For that you have to follow below steps
- Right click on project in solution explorer
- Select Properties
- Expand Build
- Select Output
- Check on Generate a file containing API documentation and save changes.
Integration in Swagger
To integrate comment documentation output file into Swagger, you have to update the Swagger service registration. Below code shows how to add XML documentation file with Swagger
builder.Services.AddSwaggerGen(c =>
{
c.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory,
$"{Assembly.GetExecutingAssembly().GetName().Name}.xml"));
});
Now let’s add XML comments. I changed WeatherForeCast.cs
class and WeatherForeCastController.cs
controller as below.
WeatherForecast.cs
/// <summary>
/// Weather forecast object
/// </summary>
public class WeatherForecast {
/// <summary>
/// Date of the weather recorded
/// </summary>
public DateOnly Date {
get;
set;
}
/// <summary>
/// Temperature in celcius
/// </summary>
public int TemperatureC {
get;
set;
}
/// <summary>
/// Temperature in farenheit
/// </summary>
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
/// <summary>
/// Summary of the weather forecast
/// </summary>
public string ? Summary {
get;
set;
}
}
WeatherForeCastController.cs
/// <summary>
/// This api handles all the logic for weather forecast.
/// </summary>
[ApiController]
[Route("[controller]")]
public class WeatherForecastController: ControllerBase {
private static readonly string[] Summaries = new [] {
"Freezing",
"Bracing",
"Chilly",
"Cool",
"Mild",
"Warm",
"Balmy",
"Hot",
"Sweltering",
"Scorching"
};
private readonly ILogger < WeatherForecastController > _logger;
/// <summary>
///
/// </summary>
/// <param name="logger"></param>
public WeatherForecastController(ILogger < WeatherForecastController > logger) {
_logger = logger;
}
/// <summary>
/// Gets weather forecast information
/// </summary>
/// <param name="parameter1">This is parameter 1</param>
/// <param name="parameter2">This is parameter 2</param>
/// <returns>Returns list of <see cref="WeatherForecast"/>WeatherForecast</returns>
[HttpGet(Name = "GetWeatherForecast")]
public IEnumerable < WeatherForecast > Get(string parameter1, string parameter2) {
return Enumerable.Range(1, 5).Select(index => new WeatherForecast {
Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
}).ToArray();
}
/// <summary>
/// Post weather forecast
/// </summary>
/// <param name="forecast">WeatherForeCast object</param>
/// <returns>Returns string response</returns>
[HttpPost]
public IActionResult Post(WeatherForecast forecast) {
//Post business logic here
return Ok();
}
}
Now run the application and you will see the Swagger UI with all XML comments added in the code file. If you expand GET or POST methods then you will see more information including parameters, response hints and option to test API endpoints.
Summary
In this article, I explained about various ways of adding XML comment and generate Web API documentation from the XML comment. This article also shows how to integrate documentation generated from XML comment with Swagger.
I hope you will find this article helpful. If you have any suggestions, then please feel free to ask into the comment section.
Thank you for reading the article