Writing the documentation is quite similar to unit testing – you know it should exist, but usually, it doesn’t. There are a few reasons for that. First, writing documentation isn’t fun, is it? Who cares about some stupid XML above each class and method when you can focus more on the architecture and some “serious” code. Another reason is that in many projects, the documentation is just not required by the client. So, if it’s not, why should we care about that since we perfectly know all the code? Well, there are a lot of scenarios when this might help you a lot such as:

joining a new project

reading code written by an unknown developer

integrating with another system

Of course, it’s not that easy to convince business to start documenting the code because this cost money, but maybe you can focus just on the most important code? Let’s consider which part of the web application should be documented at first? Many folks would say that it’s the business layer. No doubt, that’s the heart of the entire application and it should be done well. But looking from the perspective of the client-side app or another system it’s not that important since we care only about the API which gives an access to all business functionalities. Moreover, the API is in most cases the layer which changes and grows most often, so it’s important to be up-to-date with it all the time. If you’re doing your API using ASP.NET Core, I’ve got good news for you. There’s a framework which might help you to create great and powerful documentation. It’s called Swagger.

What is Swagger?

As described on the official site:

Swagger is the world’s largest framework of API developer tools for the OpenAPI Specification(OAS), enabling development across the entire API lifecycle, from design and documentation, to test and deployment.

The swagger Team provides dedicated tools for different part of the development:

Swagger Editor – enables to design your API in the editor using syntax which is very easy to understand. You can try it out online here.

– enables to design your API in the editor using syntax which is very easy to understand. You can try it out online here. Swagger Codegen – generates boilerplate servers from the API definition in 20 different programming languages.

– generates boilerplate servers from the API definition in 20 different programming languages. Swagger UI – visualizes and interacts with the API, so there no need to create example client app or use Postman/Fiddler.

You know what Swagger is, so let’s finally dive into the code and play with it.

Installation and basic configuration

In order to install the Swagger, you should open Package Manager Console and type the following command:

Install-Package Swashbuckle.AspNetCore

Alternatively, you can add this NuGet package using the UI. Having this done, go to the Startup class and modify it as follows:

public void ConfigureServices(IServiceCollection services) { // Add framework services. services.AddMvc(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Version = "v1", Title = "My API", }); }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); app.UseMvc(); app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1"); }); }

For this example, I’m using standard ASP.NET Core Web API project which contains default controller defined, called ValueController. Now, run the application and go to the address:

{host_address}/swagger

In my case, it’s http://localhost:50466/swagger. Here’s what has been generated:

Notice, one thing. I haven’t already written any comments above my API’s actions, but even though some documentation has been generated. It presents all actions in ValueController, including method type (POST, GET etc.) and endpoints with parameters. Things start beeing more interesting when you click on chosen block:

Expanded block presents example model returned from the action on success (so with the 200 HTTP status code). Notice the button below the text area. By clicking it, you can call the specific action and see the result in a format specified in “Response Content Type” dropdown box, so it might be JSON, XML or plain text. Let’s see the result of the presented action:

So, not only it presents the response body and the status code, but also generates the command for Curl and shows all the headers. Not bad for writing just a few lines, right? Let’s inspect the DELETE action which requires an id parameter in the path:

Here we’ve got all needed information to call the action – the id is required (kinda obvious) and it’s an integer. We also have an information that action returns a response with 200 HTTP status code on success.

Using XML comments with Swagger

Let’s see how can we provide more details to our documentation by introducing XML comments above each action in ValueController. The first thing we need to do is enabling XML documentation in project options. Since I’m using Visual Studio for Mac, I’ll present steps in that IDE, but as far as I remember that’s very similar in Visual Studio (for Windows). So, right click on your project and go to Options. Next, go to the Build -> Compiler. Here, you need to check “Generate xml documentation”:

Having this done, close the window, and go back to the Startup class and modify the code as presented below:

public void ConfigureServices(IServiceCollection services) { // Add framework services. services.AddMvc(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Version = "v1", Title = "My API", }); var basePath = PlatformServices.Default.Application.ApplicationBasePath; var xmlPath = Path.Combine(basePath, "SwaggerProject.xml"); c.IncludeXmlComments(xmlPath); }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); app.UseMvc(); app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1"); }); }

All we’ve done here was adding three lines of code which include generated XML file to our documentation. Let’s move to the ValuesController and add the example code above the GET method:

/// <summary> /// Gets string array with two values. /// </summary> /// <param name="query">Query model containing Id and Param.</param> /// <returns>String array</returns> /// <response code="200">String array with two values</response> /// <response code="400">Error model</response> [HttpGet] [ProducesResponseType(typeof(string[]), 200)] [ProducesResponseType(typeof(ErrorModel), 400)] public IEnumerable<string> Get(ExampleQueryModel query) { return new string[] { "value1", "value2" }; } public class ExampleQueryModel { /// <summary> /// Some id /// </summary> public Guid Id { get; set; } /// <summary> /// Some param /// </summary> public string Param { get; set; } } public class ErrorModel { /// <summary> /// Error message /// </summary> public string Message { get; set; } /// <summary> /// Error reason /// </summary> public string Reason { get; set; } }

Notice that in addition to XML comments we’ve also included attributes which present data type returned from the action on failure and success. Let’s run the app and look what changed in Swagger’s documentation:

As you can see, documenting your API doesn’t have to take a lot of time. Swagger makes it much easier and provides some extra feature which will increase your productivity for sure. Of course, this is just a sample of its capabilities, so I encourage you to visit the official site and explore more.

What are your experiences with documenting code? Do you know other tools that might help us? Share your thoughts in the comment section!