Wednesday, November 2, 2016

Adding Swagger to ASP.NET Core 1.0 Web API app

Swagger is an API specification framework. It reminds me of WSDL in the SOAP days. In this article I will guide you in add Swagger documentation to an ASP.NET Core Web API app.

There are two components that we need to buckle-up in our Web API application. These are, not surprisingly, called Swashbuckle:
  1. Swashbuckle.SwaggerGen : provides functionality to generate JSON Swagger documents that describe the objects, methods, return types, etc.
  2. Swashbuckle.SwaggerUI : embedded version of Swagger UI tool which uses the above documents for a rich customizable experience for describing the Web API functionality and includes built in test harness capabilities for the public methods.
For starters, add the following package to your project.json:

"Swashbuckle": "6.0.0-beta902"

Next, add the SWaggerGen library to your middle-ware by adding the following line of code to the bottom of the ConfigureServices() method in Startup.cs:

services.AddSwaggerGen();

Also, add the following two lines of code to the bottom of the Cofigure() method in Startup.cs:

// Enable middleware to serve generated Swagger as a JSON endpoint
app.UseSwagger();

// Enable middleware to serve swagger-ui assets (HTML, JS, CSS etc.)
app.UseSwaggerUi();


Point your browser to http://localhost:{port number}/swagger/v1/swagger.json and you will see a JSON document that describes the endpoints of your service.

image

You can also see the Swagger UI at URL http://localhost{port number}/swagger/ui.

image

In the above example the API service is Studentapi. Your service will be under API V1. Click on it and you will see something similar to the following:

image

To test out GET, click on the first blue GET button and the section will expand describing to you the structure of your object:

image

Click on the “Try it out!” button to view the data coming back from the service for all items in the collection:

image

Click on the first blue GET button again to collapse the section. Now, click on the second blue GET button to test retrieval of an item by id.

image

Enter a value for ‘id’ then click the “Try it out!” button. It should get for you the item for that id.

image

In a similar manner, go ahead and test out all the other POST, DELETE, and PUT buttons.

The official Swagger website at http://swagger.io/. You can generate a Swagger client for most programming languages at http://editor.swagger.io/.

No comments:

Post a Comment