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.
Enabling Swagger documentation in ASP.NET Core Web API app
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.
To setup the project in Azure, we must run the setup script in our Azure Shell.
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:
Go into the Startup.cs file and add the following statement to the top of the file:
In the method ConfigureServices(IServiceCollection services), add the following highlighted Swagger/API versioning to configuration.
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.
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:
Data annotations are a another useful addition to SwaggerUI depending on the model used.
The code above will add the following to the SwaggerUI:
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!