Make your REST based APIs easier to consume by providing metadata using the Swagger JSON format.

Not so long ago, creating enterprise grade APIs was an Indiana Jones level epic adventure in XML, XSD schemas, and obscure WS-* specifications. Microsoft made it easier with WCF but the resulting services were more than just a bit on the heavy side and not particularly AJAX friendly. Over time Web and Mobile developers pushed for lighter weight APIs with the current REST standard model being the result. Remote Procedure Call styled APIs gave way to HTTP verbs and resources, XML was not replaced but largely ignored in favor of JSON, and WSDL metadata was replaced with documentation; automatic or manual.

Swagger

But sometimes the old ways were the best, or at least pretty darned useful. WSDL for all of its complexity made accessing APIs easier thanks to proxy generators, WSCF, and other tooling. Swagger is a metadata specification that works similarly to WSDL to describe your API in a way that code generators can build client proxies. It’s got quite a following now including being a key to Azure’s API Apps and how Azure Logic Apps perform integration.  There’s an online Swagger Editor as well as other online tools for validation, enhanced Node.js support, and others.  Here’s an example of the Swagger specification from their live Pet Store example.

[code language=”javascript”]
swagger: “2.0”
info:
description: “This is a sample server Petstore server. You can find out more about Swagger at <a href=”http://swagger.io”>http://swagger.io</a> or on irc.freenode.net, #swagger. For this sample, you can use the api key “special-key” to test the authorization filters”
version: 1.0.0
title: Swagger Petstore
termsOfService: “http://helloreverb.com/terms/”
contact:
email: “apiteam@swagger.io”
license:
name: Apache 2.0
url: “http://www.apache.org/licenses/LICENSE-2.0.html”
host: petstore.swagger.io
basePath: /v2
tags:
– name: pet
description: Everything about your Pets
externalDocs:
description: Find out more
url: “http://swagger.io”
– name: store
description: Access to Petstore orders
– name: user
description: Operations about user
externalDocs:
description: Find out more about our store
url: “http://swagger.io”
schemes:
– http
paths:
/pet:
post:
tags:
– pet
summary: Add a new pet to the store
description: “”
operationId: addPet
consumes:
– application/json
– application/xml
produces:
– application/xml
– application/json
parameters:
– in: body
name: body
description: Pet object that needs to be added to the store
required: true
schema:
$ref: “#/definitions/Pet”
responses:
“405”:
description: Invalid input
security:
– petstore_auth:
– “write:pets”
– “read:pets”
[/code]

For more information on all of the available tags that Swagger supports check out Swagger.io.  The Swagger.json file can become input to an SDK generator which you can find on GitHub.  Available generators include Android, C#, Java, Node.js, PHP, Python, Ruby, and several others.  And because it’s all open source you can create your own.

Swagger UI

Another use of the Swagger.json file is to provide a custom user interface for developers to explore your API.  Swagger UI allows consumers of your API to view the available resources with HTTP verbs, input parameters, documentation, and even oAuth specifications.  When configured correctly it will even let users make API calls directly from the UI to see what the request and response will look like.  This is a screen shot of the base Swagger UI for the Pet Store demo.

SwaggerPetStore

Adding Swagger Support to an ASP.NET WebAPI Project

Let’s look at how easy it is to add Swagger support to an ASP.NET WebAPI project.  First create your WebAPI Project in Visual Studio (I’m using Visual Studio 2015 RC so some screens may look a bit different) by clicking File->New->Project and select a new ASP.NET Web Application.

NewWebAPI

On the New ASP.NET Project screen select a new WebAPI project.

NewWebAPI2

Now that you have a working API, it’s time to add Swagger support.  Fortunately the heavy lifting for this has been done by Richard Morris (@DomainDrivenDev) and others and available as a NuGet package called Swashbuckle.  To add Swashbuckle to your project just open the Nuget Package Manager Console and issue this command.

NugetSwashbuckle

This NuGet package installs a few DLLs and also sets up the bootstrapping of Swagger by adding a SwaggerConfig.cs file to your project’s App_Start folder.  This file contains most of the configuration values you might ever want to set along with some comments on how to use them properly.  If you run your application now and navigate to http://localhost:<port>/swagger/docs/v1 you’ll be able to view/download the Swagger.json file that is generated by reflecting over your API in much the same way that the “Help” ApiDescription pages work.  If you navigate to http://localhost:<port>/swagger you will be able to see a Swagger UI generated from that Swagger.json file.

SwaggerUI

You’ll notice that there’s not a lot of descriptive information about the API available beyond what could be learned via Reflection.  To add more details to this we can tell Swashbuckle to expose our code’s XML comments into the Swagger.json file which will then be picked up by Swagger UI.  Here’s how to do that.

First you need to turn on generation of you XML Documentation in the Build properties page of your project.

EnableXMLDoc

Next we need to tell Swashbuckle to use that file to generate better descriptions.  To do this we need to edit the SwaggerConfig.cs file and uncomment the line that tells Swashbuckle to include XML comments.

[code language=”cs”]

c.IncludeXmlComments(System.Web.Hosting.HostingEnvironment.MapPath(“/bin/MyAPI.xml”));

[/code]

Next let’s add some comments to one of our API methods.

[code language=”cs”]

/// <summary>
/// Returns a specific value based on the ID you request
/// </summary>
/// <param name=”id”>The ID of the value you want to return</param>
/// <returns>A value</returns>
public string Get(int id)
{
return “value”;
}
[/code]

Now if we look at our Swagger UI again we will see those comments for that specific call.

SwaggerComments

There are tons more features you can add using Swashbuckle including describing your security model, specifying multiple versions of an API, and modifying how Swagger UI looks and operates.  So check out Swagger and if you find any other interesting tweaks feel free to drop us a comment.