Document an ASP.NET Core API, using Swashbuckle, Swagger/OpenAPI, and Swagger UI.

0
754

Is it possible to use an API without any documentation? Yes, theoretically speaking, that is possible. With extensive and accurate documentation, however, you can understand the API’s technical content and integration instructions much better.

API documentation is crucial for a variety of reasons, one of which is to boost API adoption. The experience of those who use your APIs is improved by comprehensive documentation on all of the functionality, how to utilize and integrate it successfully, and updates on the API lifecycle.

There are lots of advantages to documenting the software you create. Solid documentation not only makes your code easier to maintain over time, but it also makes it easier for others to consume. When you have an API that others wish to use, it’s extremely important to make your code more usable. Thankfully, there are tools and frameworks that can help you produce high-quality documentation at a lower cost.

In this article, we’ll look at how to use Swashbuckle, Swagger, Swagger UI, and OpenAPI to document an existing ASP.NET Core API. And for that, we need some kind of knowledge of these things,

  • Experience with REST API design and implementation, 
  • Experience developing basic ASP.NET Core apps and 
  • Local installations of .NET SDK, Visual Studio Code, and the C# extension for Visual Studio Code.

Document an ASP.NET Core Web API with Swagger tools

Good API documentation supports a developer’s understanding of the API’s capabilities and how to use it, resulting in more efficient integration. Until recently, all documentation explaining an API and how to use it had to be written by hand.But now we have tools and frameworks for that.

We heard the words OpenAPI,Swagger and Swashbuckle. Let’s understand the meanings of these.

What is OpenAPI?

REST APIs are described using the OpenAPI definition. It works with any language and allows you to describe your complete API including:

  • Available endpoints
  • Operation parameters
  • Authentication methods
  • Contact and other information

It enables humans and computers to discover and understand a service’s capabilities without having access to source code, extra documentation, or network traffic analysis.

What is Swagger?

Swagger is a set of rules, definitions, and tools for creating and defining RESTful APIs that is open source. Developers can use the Swagger framework to build interactive, machine and human-readable API documentation. And it is built around the OpenAPI specification.

Swagger UI lets anyone (your development team or your end users) to visualize and interact with the API’s resources without needing to know how the API works.

What is Swashbuckle?

Swashbuckle is more of a package (or library) for usage in.NET Web API projects. Its goal is to create a Swagger specification for your project. Additionally, the Swagger UI is included in Swashbuckle, so if you’re writing an API in that language, you can use it.

There are three main elements:

  • AspNetCore.SwaggerGen – generates JSON Swagger documents that explain objects, methods, and return types, among other things.
  • AspNetCore.SwaggerUI – A version of the Swagger UI tool that may be embedded.
  • AspNetCore.Swagger – A middleware and object paradigm for exposing SwaggerDocument objects as JSON endpoints.
  • Swashbuckle CLI – A .NET global tool that, once installed, allows you to generate OpenAPI specifications throughout the build/publish process. From here, you can download this tool.

Now we have a basic understanding of what we are talking about. So let’s do an exercise to make it clear.

Exercise

Consider the following API as an example:

Your organization has a PrintFramerAPI API that calculates the price of a photo frame based on the dimensions of the frame. The internal staff knows how to use the API. However, in order for the API to be used by third parties, it must be documented. Because this is an ASP.NET Core API, you choose to make the API documentation available through OpenAPI.

So here we are going to document an ASP.NET Core Web API with OpenAPI and try out Swagger UI and Swashbuckle.

As the first step we need to download the sample web API project to Visual Studio Code.

  • Open a new instance of Visual Studio Code.
  • Open the terminal window by selecting the Terminal option from the View menu.
  • (Optional) Change to a directory you want to copy the files to, such as c:\MyProjects.
  • To clone the sample Web API Project from GitHub, in the terminal window, run the following git clone command.
git clone https://github.com/MicrosoftDocs/mslearn-improve-api-developer-experience-with-swagger  && cd mslearn-improve-api-developer-experience-with-swagger/PrintFramerAPI
  • Open the project in Visual Studio Code with the following terminal command.
code -a .

Run the web API for the first time

  • In the terminal window of Visual Studio Code type the following command:
dotnet run
  • Once the output from the command is complete, navigate to: http://localhost:5000/api/priceframe/6/17

When you navigate to the address in the browser, it should respond with the message The cost of a 6x17 frame is $20.00.

Add the Swagger library to the solution

  • Add Swashbuckle to our project by running the dotnet add package command.
dotnet add package Swashbuckle.AspNetCore
  • Open the Startup.cs file.
  • At the top of the file, add another using entry:
using Microsoft.OpenApi.Models;
  • To add the Swagger generator to the services collection. replace the method ConfigureServices(IServiceCollection services) with the following implementation.
public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers();

    services.AddSwaggerGen(c =>
    {
        c.SwaggerDoc("v1", new OpenApiInfo { Title ="My API", Version = "v1" });
    });
}
  • In the Configure method in Startup.cs, enable middleware for the Swagger UI by adding useSwagger and useSwaggerUI, as shown in the following code snippet.
public void  Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseSwagger();
    app.UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
    });

    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseHttpsRedirection();

    app.UseRouting();

    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    }); 
}
  • Save these changes in the editor.
  • To see these changes run the ASP.NET application locally. Type the following in the terminal window in Visual Studio Code:
dotnet run
  • In a browser, navigate to http://localhost:5000/swagger/v1/swagger.json.

The response we get in the browser this time is a document describing the endpoints of the API, similar to the following response.

{
  "swagger": "2.0",
  "info": {
      "version":"v1",
      "title": "My API"
},
 "paths": {
   "/api/PriceFrame/{Height}/{Width}":{
	"get":{
	  "tags":[
	     "PriceFrame"
	],
	"opearionId": "GetPrice",
	"consumes": [],
	"produces":[
	   "text/plain",
	   "application/json",
	   "text/json"
	],
	"parameters": [
	  {
	    "name": "Height",
	    "in": "path",
	    "required": true,
	    "type": "string"
	},
	{
	    "name": "Width",
	    "in": "path",
	    "required": true,
	    "type": "string"
	}
	],
	"responses": {
	  "200": {
	     "description": "Success",
	     "schema": {
	        "type": "string"
		}
	      }
	    }
	  }
	}
     },
     "definitions":{}
}

Congratulations!! you did document an ASP.NET Core Web API with OpenAPI and tried out Swagger UI and Swashbuckle.

 

Comments

comments

LEAVE A REPLY

Please enter your comment!
Please enter your name here