Using Swagger to Document DotNet Core APIs

Using Swagger to Document DotNet Core APIs

·

4 min read

What is swagger and why should I use it?

Swagger is a specification of rules/notation used to define how an API should be documented. As of Swagger version 2.0, it is now been renamed to the OpenApi specification. This reflects that the specification is now widely adopted in the software development world.
Swagger itself comprises of a number of tools developed by SmartBear. These tools can be combined to produce smart and standardised API documentation.
When adding Swagger documentation to ASP.net core API’s, Swashbuckle is the most commonly used tool.

What is Swashbuckle?

Swashbuckle is a a library that combines a number of Swagger libraries into one useful tool used to create documentation for ASP.net Core applications. This enables us to add Swagger documentation quickly and with minimal code. It is another open-source library and so can and is used in projects of all sizes.

Adding Swashbuckle to my DotNet Core API

To demonstrate the use of Swashbuckle and Swagger and how easy it can be used to document an API, I have created a quick step-by-step guide.

To start with, create an new ASP.net core Web API project in Visual Studio. You can remove everything from the ‘Controllers’ folder and create a new controller called ‘GreetingController’.

Add the following code to the controller:

\[Produces("application/json")\]
\[Route("api/Greeting")\]
public class GreetingController : Controller
{
  HttpGet("SayHello")\]
  public IActionResult SayHello(\[FromQuery\] string name)
  {
    return Ok($"Hello {name}");
  }
}

You can then add the Swashbuckle and Swagger libraries by adding the Swashbuckle package via Nuget. Use the following command in the Package Manager Console to install the latest version.

Install-Package Swashbuckle.AspNetCore

To the startup.cs file add the following code to the ConfigureServices method, below the services.AddMvc(); line. You may need to add a reference to the Microsoft.OpenApi.Models by adding ‘using Microsoft.OpenApi.Models;’ at the top of the startup.cs file.

services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "Talking I.T. Through Swagger Demo API", Version = "v1" });
});

and the following to the Configuration method under app.UseMvc();

app.UseSwagger();

The above should be enough to generate the API documentation for our API in Json format. To view the API documentation you can launch the application and navigate to localhost:[port]/swagger/v1/swagger.json and you should see something similar to the following:

swaggerjson.jpg

This in itself can be useful for sharing the the API definition with other code generation and testing tools, but where Swashbuckle really excels is that it can also build a nice user interface using Swagger UI that can be used to directly document and test the API functions through your web browser.
To do this, add the following code to our Configure method in the StartUp.cs file:

app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "Talking I.T. Through API V1");
});

Launch the application and navigate to localhost:[port]/swagger/index.html and you should see the single SayHello get API endpoint we created earlier.

SwaggerGet.jpg

You can select the endpoint, click ‘Try It Out’ and send requests to test the API is responding as expected.

SwaggerGetResponse.jpg

Note: It is recommended to put the app.UseSwaggerUI set-up code inside the env.IsDevelopment if statement wrapper, to prevent this being exposed in production environments. For development purposes you could also update the development profile in the launchSettings.json file to point directly at the Swagger UI to load the UI automatically when launching the API from Visual Studio.

Now add a second post endpoint to out Greetings controller as follows:

\[HttpPost("SayHelloByPost")\]
public IActionResult SayHelloByPost(\[FromBody\] string name)
{
return Ok($"Hello {name}");
}

And then re-launch the application and you should see the new endpoint is automatically picked up and added to the Swagger UI page.

SwaggerWithPost.jpg

Common Errors

If you get an error ‘Failed to load API definition’ or you are missing some of the expected endpoints from Swagger UI, make sure that you have specified HTTP decorators such as [HttpGet] or [HttpPost] on your API endpoint definitions inside you controllers or Swagger will not be able to document the endpoints.

Why This Article Now?

Two reasons. Whilst many people already know and use Swagger, many may not and if I can help just one person then I will be happy.

Secondly, many of my future posts around Asp.net Core development will focus on API development. Because of this, many of my demo’s may use Swagger UI as to show the API applications in action, so this post will always be here to refer people back to.

Hope it helps!

The complete code for this article is available here.

The post Using Swagger to Document DotNet Core APIs appeared first on Talking I.T. Through.

Did you find this article valuable?

Support Dave K by becoming a sponsor. Any amount is appreciated!