document-microservice-with-swagger

Document Microservice with Swagger

Swagger is an open-source toolset that can be easily integrated into your solution and which helps you to document and test your APIs. It is so simple that even none technical people can use it. In my last post, I created  Product Microservice and today I will explain how I integrated Swagger.

What is Swagger?

Swagger is an open-source toolset from Smartbear and is based on the OpenAPI specification. For .NET Core, you can install Swagger easily as NuGet package and configure it in the Startup class of your solution. In simple words, Swagger wraps the XML comments of your API in a nice looking functional GUI which shows your the available actions and models and also lets you send requests to the actions. You can even attach authentication objects like a JWT.

Install Swagger

You can find the code of  the finished demo on GitHub.

To implement Swagger, you should to installed the Swashbuckle.AspNetCore NuGet package in the API project via Tools-> NuGet Package Manager.

Next, you should added the path to the XML file which contains all the XML comments of the actions and models in the ConfigureServices method in the Startup class.

services.AddSwaggerGen(c =>
{
var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
c.IncludeXmlComments(xmlPath);
});

The next step is to tell ASP .NET Core to use Swagger and its UI. You can add  in the Configure method of the Startup class,  following code.

app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "Product API V1");
c.RoutePrefix = string.Empty;
});
This code configured Swagger to load the the GUI when starting your solution.

That’s all you have to configure in Swagger. Now I only have to make two adjustments to the starting project. First, I tell the project to create the XML file by opening the properties of the project. Go to the Build tab and check XML documentation file. It is important that you use All Configurations as Configuration in the dropdown on top All Configurations.

document-microservice-with-swagger-1-1.png
Configuration of Swagger

Create the XML documentation file

After you configured your project to create the XML documentation file, you will get warnings that an XML comment is missing on top of your actions. I find these warnings pretty annoying, so I suppress them by adding 1591 in the text box for Suppress warnings in the Build tab (see screenshot above).

The last step is to remove the launch URL from the launchSettings.json file in section profile. You can just remove the line, otherwise, the Swagger GUI won’t be loaded when the application is started and you have to call its URL.

That’s all you have to do to set up Swagger. Before I test it, I will add some XML comments to the actions, attributes to my model and some more configuration.

Adding XML comments to API Actions

The XML comment on an action describes what the action does, what the parameters are, what it returns and what return codes it can produce. Usually, I have the opinion that the name of the method and parameter should describe themselves but in this case, we need a comment for the Swagger GUI. To create an XML comment write three / on top of an action. This will give you the template of the comment.

Additionally, you can add the response codes and the ProducesResponseType attribute which will help users of the GUI to understand what return codes can be expected from the API.

The following is added to the public IActionResult Post([FromBody] Product product) in the ProductController.

/// <summary>
/// Action to create a new product in the database.
/// </summary>
/// <param name="product">Model to create a new Product</param>
/// <returns>Returns the created product</returns>
/// <response code="200">Returned if the product was created</response>
/// <response code="400">Returned if the model couldn't be parsed or the product couldn't be saved</response>
/// <response code="422">Returned when the validation failed</response>
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status422UnprocessableEntity)]
[HttpPost]

Adding Attributes to the Model

The Swagger UI for .NET Core also includes the models of your application. The UI shows which models are available, what properties they have including their data type and their attributes, e.g. if the property is required. To use this feature, you only have to add the attribute to the property of your models. Swagger creates everything out of the box by itself.

public class Product
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string Description { get; set; }
[Required]
public decimal Price { get; set; }
[Required]
public int CategoryId { get; set; }
}

Personalize the Swagger UI

Swagger is also easily extensible. You can load your own CSS, or change the headline or information displayed on top of the page. For now, I will add my contact information so developers or customers can contact me if they have a problem. To add your contact information use the SwaggerDoc extension and pass an OpenApiInfo object inside the AddSwaggerGen extension in the Startup.cs class.

services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo
{
Version = "v1",
Title = "Product Api",
Description = "A simple API to create a product",
Contact = new OpenApiContact
{
Name = "Mehrdad Zandi",
Email = "mehrdad.zandi@softsolutionsahand.com",
Url = new Uri("http://www.softsolutionsahand.com/")
}
});
var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
c.IncludeXmlComments(xmlPath);
});
Testing Swagger

Everything is set up and when you start the application, you should see the Swagger UI.

Swagger UI is uploaded

On top of the page, you can see headline and  contact information. Then you can see actions, even in different colors for the different HTTP verbs they use and then you can see the models. Next to the post action, you can see the XML comment I added to describe the method. The other actions doesn’t have an XML comment yet, therefore no text is displayed.

When you click on an action, it opens and shows you information about the parameter, and also shows the responses which I added previously in the XML comment.

SwaggerGUIWithDetails.gif
Swagger UI information about an action

When you click on the Try it out button in the top right corner, Swagger will already create a request for you with all parameters. You can edit them and then send the request (by pressing to the Execute) to the server and the UI will show you the reply.

SwaggerGUITryOut.gif
Testing an action of the API

After clicking on Try it out, you can define the format of your request on the top right. I leave the default application/json and also leave the created model as it is. When you click on Execute, the response and also the sent request and the request URL will be shown below. In my case, the response is a code 200 and a Customer JSON object. On the bottom right is a button where you can even download the result. This might be useful if you have a test document and want to attach the result to it.

SwaggerResponse.gif
Result of testing Swagger UI toward to Database

Conclusion

In this section we have talked about Swagger, and NuGet packages. Swagger can be used to document and test your application and make this information easily accessible even for none technical people. Swagger is also very easy to set up and can be extended and modify to fit your needs.

You can find the code of  the finished demo on my GitHub.

In my next post, I will implement dockerize of Microservice in ASP.NET Core.

This post is part of Microservices-Step by step”.

Back to home page