Visual Studio 2017 and Swagger: Building and Documenting Web APIs

The OpenAPI ‘Swagger’ Specification defines a protocol that allows applications to discover, and generate documentation of methods, parameters and models of REST APIs, This provides a way for any software to identify the features of a REST API. It does for REST APIs what WSDL (Web Service Description Language) did for web services. Visual Studio now provides it to support proxy creation for REST APIs, as Dennes Torres explains.

Swagger is a technology-agnostic standard that allows the discovery of REST APIs, providing a way for any software to identify the features of a REST API.

This is more important than it seems: It’s a game changing technology, in the same way that WSDL (Web Service Description Language) has been for web services.

WSDL has been the fundamental technology that made it possible for tools and IDEs such as Visual Studio to understand web services and to create proxy classes. This feature turns the consumption of web services into a high-level task, encapsulating all protocol details.

That’s the importance of Swagger: It’s able to do for REST APIs what WSDL has already done for web services, by allowing the creation of proxies and by making the use of web APIs much easier.

VS 2017 includes support for REST API proxy creation using Swagger protocol. It’s still in an early stage and lacking some features, however this is a great step towards the broader adoption of Swagger.

We’ll create an example of how we can use Swagger with VS 2017 in order to analyze the advantages and the missing features.

As well as VS 2017, we will also need IIS (Internet Information Server) installed in the development machine for our example.

Development Environment

You can enable IIS as a Windows feature or server role depending if you are using a client operating system or a server one.

Starting Application

Before we can use Swagger, we need a demo solution with a web API project. Let’s build this starting solution before we go on to implement Swagger.

  1. Create an ASP.NET Web API project
    1. Inside Visual Studio, select ‘File’ -> ‘New Project’ menu
    2. In the ‘New Project’ dialog box, inside the left side tree view, select ‘Installed’ -> ‘Templates’ -> ‘Visual C#’ -> ‘Web’ tree items.
    3. In the ‘New Project’ dialog box, in the right side, select ‘ASP.NET Web Application (.NET Framework)’
    4. In the ‘Name’ textbox, type ‘webDemo’

    5. In the ‘Solution Name’ textbox, type ‘slDemo’ and click the ‘Ok’ button
    6. In the ‘New ASP.NET Web Application’ window, below ‘ASP.NET 4.5.2 Templates’, select ‘Web API’ and click the ‘Ok’ button

  2. Configure the Web API project to use the local IIS
    1. In the ‘Solution Explorer’ window, right-click on ‘webDemo’ project and click the ‘Properties’ menu item.
    2. In the right side of ‘webDemo’ properties window, click ‘Web’ page
    3. In the combobox below ‘Servers’, select ‘Local IIS’

    4. Click the ‘Create Virtual Directory’ button
    5. Close the ‘webDemo’ properties page

This project already has a sample web API controller developed, but we need to make some changes. Let’s examine the details of the existing controller and make those changes.

  1. Analyzing and changing the existing API Controller
    1. In the ‘Solution Explorer’ window, inside ‘webDemo’ project, open the ‘Controllers’ folder and check the existing controllers.

    2. Double-click the ‘ValuesController.cs’ file and check the existing actions. This is the only web API controller in the project.
    3. Change the ‘ValuesController’ class for the code below. We are completing the PUT action and storing the list inside Application memory area.

  2. Execute the application and analyze the result
    1. Click ‘Start’ button in the toolbar to execute the application
    2. On the web page just opened, click ‘API’ link in the top menu. You will notice the API operations, basically a CRUD with two GET’s, one POST, PUT and DELETE

    3. In the browser navigation bar, type a new URL: http://localhost/webDemo/API/Values . As a result, a JSON file will be downloaded, therefore the web API is working fine.

Including Swagger in our project

Swagger is a technology agnostic protocol. For each technology, we need some tool to implement the protocol. SwashBuckle is the name of the tool for .NET. There is a version for .NET before 4.5 and another version for .NET after 4.5.

Let’s do a step-by-step walkthrough to implement Swagger using SwashBuckle:

  1. Include SwashBuckle nugget package in the web API project
    1. In the ‘Solution Explorer’ window, right-click the ‘webDemo’ project and click ‘Manage nuget packet’ menu item.
    2. In the ‘Nuget Package Manager’ window, select ‘Browse’
    3. In the textbox inside ‘Nuget Package Manager’ window, type ‘SwashBuckle’.
    4. In the left side of ‘Nuget Package Manager’ window, select ‘SwashBuckle.Net45’ package

    5. In the right side of the ‘Nuget Package Manager’ window, click the ‘Install’ button.
    6. In the ‘Review Changes’ window, click the ‘Ok’ button.
    7. In the ‘License Acceptance’ window, click ‘I Accept’ button.
    8. Close the ‘Nuget Package Manager’ window
  2. Configure the XML documentation. SwashBuckle will use the XML documentation to describe the WEB APIs actions.
    1. In the ‘Solution Explorer’ window, right-click the ‘webDemo’ project and click the ‘Properties’ menu item.
    2. In the ‘webDemo’ window, click ‘Build’ page
    3. In the ‘webDemo’ window, below ‘Output’, click ‘Xml Document File’ checkbox. In the textbox at right you will see the path ‘bin\webDemo.xml’.

    4. In the ‘Solution Explorer’ window, inside ‘webDemo’ project, open the ‘Controllers’ folder and double click ‘ValuesController.cs’ file.
    5. Let’s create an XML documentation for each action and the controller. Over each action and also over the controller declaration, type ‘///’ and describe the action and the controller.

  3. Configure SwashBuckle. For now, the only configuration we need to do is the path of the XML documentation.
    1. In the ‘Solution Explorer’ window, inside ‘webDemo’ project, open the ‘App_Start’ folder and double click ‘SwaggerConfig.cs’ file. This file was included in the project by the ‘SwashBuckle.Net45’ nuget package.

      The ‘Register’ method of the ‘SwaggerConfig’ class is configured to be executed as a ‘PreApplicationStartMethod’.

    2. Include the following method inside ‘SwaggerConfig’ class:

    3. Uncomment the following block of code inside the “Register” method:

  4. Execute and test the application
    1. Execute the application, click the ‘Start’ button in the toolbar.
    2. Type the following URL in the browser address bar: http://localhost/webDemo/Swagger/ui/index
    3. On the Swagger documentation page, click ‘Values’, the name of the controller.

    4. Click each operation to see the documentation. You may notice that Swagger is using the XML documentation description for each operation.
    5. Type the following URL in the browser address bar: http://localhost/webDemo/Swagger/docs/v1 . This time we are looking for the JSON document describing the web API, the core result of SwashBuckle
    6. In the question that will appear, click the ‘Save’ button (I’m using Chrome, this can be a bit different with other browsers)
    7. In the message that will appear, click ‘Open Folder’ button. (I’m using Chrome, this can be a bit different with other browsers)
    8. Open the v1.json file with Notepad. The file won’t be well formatted, the content, however, is a description of the web API, such as you can see in the image below. If you would like so, you can open the file in Visual Studio to see a well-formatted version of the file.

    9. Stop the execution in Visual Studio

Creating the Client Project

Now it’s time to create a client to consume our web API and illustrate how this consumption will be a lot easier.

  1. Add a new Windows Desktop project to the solution
    1. In Visual Studio, click ‘File’ -> ‘Add’ -> ‘New Project’ in the menu
    2. In the ‘New Project’ dialog box, inside the left side tree view, select ‘Installed’-> ‘Templates’ -> ‘Visual C#’ -> ‘Windows Classic Desktop’ tree items.
    3. In the ‘New Project’ dialog box, in the right side, select ‘Windows Forms App (.NET Framework)’
    4. In the ‘Name’ textbox, type ‘winClient’ and click the ‘Ok’ button
  2. Add a reference to the web API and create the proxy
    1. In the ‘Solution Explorer’ window, right-click the ‘winClient’ project, click ‘Add’ -> ‘REST API Client’ menu item.

    2. In the ‘Add REST API Client’ window, ‘Swagger Url’ textbox, type http://localhost/webDemo/Swagger/docs/v1 .
    3. In the ‘Client Namespace’ textbox, type ‘SvcRest’ and click the ‘Ok’ button.

      It seems that nothing happened. Inside ‘Web Publish Activity’ window you will be able to see what happened and an error message: ‘Found operation object with duplicate OperationId ‘Values_Get’. OperationId must be unique among all operations described in the API’.

      The client tool doesn’t support a REST API with operation overload, and our demo API has two GET methods. We need to resolve this problem before we proceed.

Support for operation overload

This lack of support for operation overload is a big flaw, since even the demo web API application, as you may be noticing, uses operation overloads, it has two GET actions, with and without a parameter.

There are two possible solutions:

  • Change the actions name to avoid an overload
  • Implement an operation filter that will intercept the JSON file creation and avoid the overload inside the JSON file.

Let’s implement an operation filter in a step-by-step walkthrough:

  1. Add a new Class Library to the solution
    1. In the ‘Solution Explorer’ window, right-click the solution, click ‘Add’->‘New Project’ context menu item
    2. In the ‘New Project’ dialog box, inside the left side tree view, select ‘Installed’->‘Templates’->‘Visual C#’ ->‘Windows Classic Desktop’ tree items.
    3. In the ‘New Project’ dialog box, in the right side, select ‘Class Library (.NET Framework)’
    4. In the ‘Name’ textbox, type ‘libTools’ and click the ‘Ok’ button

    5. In the ‘Solution Explorer’ window, right-click ‘Class1.cs’ file, below ‘libTools’ project, and click ‘Delete’ menu item.
  2. Install the package ‘SwashBuckle.Core.Net45’ in the new Class Library project. I’m installing only the core of SwashBuckle, not all the libraries.
    1. In the ‘Solution Explorer’ window, right-click the ‘libTools’ project and click ‘Manage nuget packet’ menu item.
    2. In the ‘Nuget Package Manager’ window, select ‘Browse’
    3. In the textbox inside ‘Nuget Package Manager’ window, type ‘SwashBuckle’.
    4. In the left side of ‘Nuget Package Manager’ window, select ‘SwashBuckle.Core.Net45’ package
    5. In the right side of ‘Nuget Package Manager’ window, click ‘Install’ button.
    6. In the ‘Review Changes’ window, click the ‘Ok’ button.
    7. In the ‘License Acceptance’ window, click ‘I Accept’ button.
  3. Implement the operation filter
    1. In the ‘Solution Explorer’ window, right-click ‘libTools’ project, click ‘Add’-> ‘Class…’ context menu item
    2. In the ‘Add New Item’ window, type ‘MultipleOperationsWithSameVerbFilter.cs’ in the ‘Name’ textbox.

    3. Copy the code below and paste inside the new file, replacing the empty class:

  4. In the ‘webDemo’ project, add a reference to the ‘libTools’ project
    1. In ‘Solution Explorer’ window, right-click ‘webDemo’ project, click ‘Add’-> ‘Reference’ context menu item
    2. Inside ‘Reference Manager’ window, on the left side, select ‘Projects’ -> ‘Solution’ item
    3. Inside ‘Reference Manager’ window, on the right side, check the box besides ‘libTools’ and click the ‘Ok’ button

  5. Change Swagger configuration to use the new operation filter
    1. In the ‘Solution Explorer’ window, inside ‘webDemo’ project, open the ‘App_Start’ folder and double click ‘SwaggerConfig.cs’ file.
    2. At the top of ‘SwaggerConfig.cs’ file, add the following line:

    3. Inside the ‘Register’ method, inside the following block:

      Add the following line of code:

  6. In the ‘Solution Explorer’ window, right-click the solution and click ‘Rebuild Solution’ menu item

  7. Repeat the step 2 of the client proxy creation, this time it will work.

Using the proxy in the Client Application

Now the web API proxy is built inside the client project, it’s time to use it to access the web API. However, the proxy needs an additional class to control authentication. Another flaw in this feature is the fact it doesn’t deal well with anonymous authentication, but we can overcome this problem with a quick fix.

  1. Install the ‘Microsoft.Rest.ClientRuntime’ package in the ‘libTools’ project. This package is needed for our fix.
    1. In the ‘Solution Explorer’ window, right-click the ‘libTools’ project and click ‘Manage nuget packet’ menu item.
    2. In the ‘Nuget Package Manager’ window, select ‘Browse’
    3. In the textbox inside ‘Nuget Package Manager’ window, type ‘Microsoft.Rest.ClientRuntime’.
    4. In the left side of ‘Nuget Package Manager’ window, select ‘Microsoft.Rest.ClientRuntime’ package
    5. In the right side of ‘Nuget Package Manager’ window, click ‘Install’ button.
    6. In the ‘Review Changes’ window, click the ‘Ok’ button.
    7. In the ‘License Acceptance’ window, click ‘I Accept’ button.
  2. Implement the AnonymousCredential class. It will sove the anonymous authentication problem.
    1. In the ‘Solution Explorer’ window, right-click ‘libTools’ project and click ‘Add’-> ‘Class’ context menu item.
    2. In the ‘Add new item’ dialog box, type ‘AnonymousCredential.cs’ in ‘Name’ textbox and click the ‘Ok’ button
    3. In the top of the new file, add the following statement:

    4. Use the following code for this class. Yes, nothing is needed but the inheritance.

  3. 3) Build the client Windows form to access the API
    1. In the ‘Solution Explorer’ window, below ‘winClient’ project, double-click ‘Form1.cs’ file.
    2. From the ‘Toolbox’ window, add three buttons inside the form.
    3. Change the button properties according to the following:

      Name: cmdAllValues
      Text: All Values

      Name: cmdValue
      Text: Single Value

      Name: cmdUpdate
      Text: Update

  4. In the Windows project, add a reference to the ‘libTools’ project
    1. In the ‘Solution Explorer’ window, right-click ‘winClient’ project, click ‘Add’-> ‘Reference’ context menu item
    2. Inside ‘Reference Manager’ window, on the left side, select ‘Projects’ -> ‘Solution’ item
    3. Inside ‘Reference Manager’ window, on the right side, check the box besides ‘libTools’ and click the ‘Ok’ button
  5. Add the code for the ‘All Values’ button
    1. Select the ‘Form1.cs (design)’ page
    2. Double click the ‘All Values’ button, this will create a click event for the button.
    3. In the top of the ‘Form1.cs’ file (already opened by the previous task), add the following statements:

    4. Change the ‘cmdAllValues_Click’ for the following code:

      It’s important to notice the following details:

      • There are both, synchronous and asynchronous methods in the proxy. The code is illustrating the synchronous call.
      • Most methods are extension methods: due to that, we need the ‘Using svcRest’ statement.
      • You don’t need to deal with the protocol details to call the API. That’s the advantage of the proxy. We have this advantage for webservices ever since .NET was created; now we can work in this way also with web APIs.
  6. Add the code for the ‘Single Value’ button
    1. Select the ‘Form1.cs (design)’ page
    2. Double click the ‘Single Value’ button, this will create a click event for the button.
    3. Change the ‘cmdValue_Click’ for the following code:

  7. Add the code for the ‘Update’ button
    1. Select the ‘Form1.cs (design)’ page
    2. Double click the ‘Update’ button, this will create a click event for the button.
    3. Change the ‘cmdUpdate_Click’ for the following code:

  8. Execute and test the application
    1. In the ‘Solution Explorer’ window, right-click the ‘winClient’ project and click ‘Set as Startup Project’
    2. Click ‘Start’ button in the toolbox to run the application
    3. Click the ‘All Values’ button, the ‘Single Value’ button, ‘Update’ button and ‘Single Value’ button again, in sequence and click the ‘Ok’ button when needed, to check the result. The API calls will be working well.

Conclusion

These new features are really game-changing, improving the way that we use web APIs. This is just the beginning, because there are much more about these features that are coming.

You may have noticed some flaws; for example, the client only creates a C# proxy: However, it’s very common nowadays to require a Javascript proxy, particularly for the consumption of web APIs in AngularJS applications. It’s important to remember that the core of this technology is the JSON format that describes the web API. Anyone can build a new Visual Studio Add-In that is capable of reading this JSON description and creating a Javascript proxy. We will, for sure, see improvements in a short while.

Swagger deserves more advanced articles than this, to be sure, but for now I will give you some links for further reading: