Introduction into using .NET Core with Swagger Documentation

Author by Sonny Darji

Over the past week I have been inspired to learn a new way to document API rest points. The tool I discovered is called SwaggerUI. It specifically allows for anyone whether it’s the development team or the end consumer, to test and manage API resources. Swagger UI uses REST API calls that displays the resources without the logic. Below is a template example of a pet store visualized with all its API REST endpoints.

Blog1.png

Enabling Swagger documentation in ASP.NET Core Web API app

Step 1: 

Using a created template ASP.NET Core App using a sample .NET clone template written by Dalton Smith.

To get started, open a command prompt and enter this command:

   Git clone https://github.com/smitdalt/ApiTemplate.git

This will clone the sample .NET template. Next, we will navigate to the directory where new project is stored. Run the following command to create the project.

Run `dotnet new <swaggerapi> -n <Swagger_Netapp> --namespace <Swagger_Netapp> --fileRename < Swagger_Netapp >`

Next, go into the directory where the project has been created.

    Cd ~\src\Concurrency\SwaggerExample

Step 2:

  To setup the project in Azure, we must run the setup script in our Azure Shell.

 bash setup-exercise.sh

  Then add the desired packages to the project like Swashbuckle, using the dotnet add command.

 dotnet add package Swashbuckle.AspNetCore

  Open the project in Visual Studio Code where we can use the following command in our terminal:

      Code .

  Go into the Startup.cs file and add the following statement to the top of the file:

                     using Swashbuckle.AspNetCore.Swagger;

 

In the method ConfigureServices(IServiceCollection services), add the following highlighted Swagger/API versioning to configuration.

blog1-1.png

In the Configure() method in the app for IApplicationBuilder, add the following highlighted code which links the SwaggerUI to the provider as well as the configuration.

blog1-2.png

Step 3:

Enrich your SwaggerUI and add more documentation to allow XML comments which come usually right before the code.

               XML nodes in use:

Summary: A concise summary of what the method/class/field is or does

Remarks:  Additional details for the method class etc.

Params:    A parameter to the method, and what it represents

Returns:    Shows what the method is returning

Below is an XML documented dog example:

Blog1-3.png

Data annotations are a another useful addition to SwaggerUI depending on the model used. 

[Produces("application/xml")

The code above will add the following to the SwaggerUI:

blog1-4.png

I hope this introduction to SwaggerUI with ASP.NET Core has provided uselful knowledge to enrich your applications with SwaggerUI. I would love to hear how others are managing API resources. Happy Swagging!