October 12, 2016

Documenting WebAPI Using Swagger

Post by: Craig Jeffords

Introduction

Documentation. We all know it’s necessary and that it makes our lives easier when we have it, but it’s also the last item on everybody’s mind when we create or enhance applications.  It takes time to get documentation right but more often than not, we put it together at the end of the project.  We fully intending to document every little detail then end up with enough time and budget to deliver only the basics.

Documenting APIs isn’t much different.  We spend the vast majority of our time working on functionality and performance, all while intending to deliver great documentation at the end.  Unfortunately, by waiting until the end, we either run out of time or priorities changes and once again, we are left with insufficient documentation.

Wouldn’t it be nice if our API documentation scaled with our application?

Overview

With that question in mind, I decided to do some research.  I’ve used ASP.Net Help Pages in the past and found them to be pretty handy once I had everything configured correctly.  The documentation I’ve found is generally 3 to 4 years old, however, and I always seemed to find quirky behavior when I used them.  APIExplorer is another solution I’ve looked into but, like Help Pages, all the documentation seems like it’s 3 to 4 years old.

A relatively new player in the space is RAML.  RAML stands for RESTful API Modeling Language.  They claim to give enterprises the ability to design using an API-First mentality and non-technical terms.  You design, test and prototype your API using their tools, then are able to use the generated RAML to create your API solution.  There are many community-maintained projects that allow you to use RAML in whatever language you choose, but I felt this was way beyond the scope of this blog, which is to find a relatively painless way to automatically create helpful API documentation.

Swagger

After consulting with some of my colleagues and through the research I mentioned above, I decided to look into Swagger.  I found a good tutorial, written by Shane Boyer, that shows how to create Web API documentation using Swagger.  I used it to document a small API application that I recently put together.  Unlike the tutorial application, my API supports live data using Entity Framework Core and an Azure-based SQL Server database.  My goal here is to understand what it takes to implement and maintain API documentation using a 3rd party tool.

My Environment

I created an ASP.Net Core 1.0 Web API project which will handle all aspects of a beer tracking application I’m writing in my spare time.  I’m using this project as a learning tool so I don’t expect it to ever be released for public consumption.

I’m using EntityFrameworkCore Code First Migrations to create/update models and back-end schema.

  • Visual Studio 2015 Enterprise Update 3
  • Asp.Net Core 1.0
  • EntityFrameworkCore 1.0.1
  • Swashbuckle 6.0.0-beta902

Nothing I’m using requires VS Enterprise so if you want to follow along with this blog using Community Edition, you shouldn’t have any issues.

The Tutorial

I’m going to follow Shane’s tutorial and share my thoughts as I go.  So let’s get started.

Install Nuget Packages

We’re using a third party package so the first thing we need to do is install it in our solution.  The more I work with .Net Core, the more I like using the Package Manager Console over the Nuget Package Manager but to each their own.  To install via Package Manager Console, type the command Install-Package Swashbuckle -Pre and hit enter.

Install through Package Manager Console:

If you’re more comfortable using the Nuget Package Manager, you can right-click your project and click ‘Manage Nuget Packages’.  Under the ‘Browse’ tab, ensure you’ve checked the box next to ‘Include prereleases’, then click on the Swashbuckle package and install the latest version (6.0.0-beta902 at the time of this writing).

Install through Nuget Package Manager:

Regardless of how you choose to install the package, you should now see it listed as a dependency in your project.json file.  If you don’t see it, you need to add it.

Swashbuckle Dependency in project.json:

Add and Configure Swagger to Middleware

Next we configure the application to use Swagger in the .Net Core middleware section of the application.  To add Swagger, we edit the ConfigureServices() and Configure() methods of the application’s Startup.cs member.

Add SwaggerGen to the ConfigureServices() Method:

Adding SwaggerGen to the application’s service collection provides the ability to create JSON swagger documents to describe your API. 

Configure Swagger and SwaggerUi:

Adding SwaggerUi to the application provides functionality to translate the JSON documents created by SwaggerGen to display a nicely formatted page to the user that includes built in tests for public methods.

If you wanted to get quickly started with API documentation and don’t feel the need to customize from the default look and feel of Swagger, you could stop here.  By installing the package, adding it to the application’s service collection, and configuring it using default settings, you have rich API documentation without doing anything else.  So let’s launch and see what we have.

Launch Swagger and Examine Out of the Box Functionality

Start your application and leave it running.  You can select either IISExpress or name of the application itself if you want to see the command window and follow while queries are executed.  It doesn’t matter as both will work with Swagger.  First, take a look at the JSON documents that Swagger has created.

Navigate to the JSON document at:  http://localhost:<port>/swagger/v1/swagger.json

As you can see below, information about every endpoint is summarized in a JSON document which is then used by SwaggerUI to create a nicely formatted help screen to which we will navigate next.  The help screen shows all the information you define for each public endpoint and also allows the user to test functionality from your help page.

I was pretty impressed with Swagger at this point.  I started with a small API project which had no documentation and within 10 minutes (install the package, register the service, default configure components), I ended up with fully functional help documentation that includes testable endpoints. 

JSON Docs:

Once you have inspected the JSON documents Swagger has created from your end points, navigate to the actual documentation pages.

Navigate to the Documentation at: http://localhost:<port>/swagger/ui

As you can see, with very little actual coding, we have a nicely defined documentation page that allows us to expand each end point to see more details and to run tests.

Documentation page:

Expanded end point documentation:

Live End Point Testing:

While Swagger’s out of the box functionality is really nice, we’re really just scratching the surface.  From here, we can customize and extend swagger using some familiar mechanisms to really take our documentation to the next level.

Customize and Extend Swagger

You can add a section for author, detailed description, and licensing information, use XML comments much like ASP.Net Help Pages, and use Data Annotation on your models to allow more descriptive object examples.  You can also define response types so that users of your API can understand what they should expect to see from a response or what a response code means when they see it.

Add Author, License, Description, Title, and Version

Add and configure the ConfigureSwaggerGen service to show information pertinent to the overall API solution.  You can add Info (using Swashbuckle.Swagger.Model), like the version of your API, a title, description, terms of service, contact and license documentation.  The version you document in this method needs to case-sensitive match the version in the URL of the Swagger JSON document or this step will not work.  Changing the API version is possible but it requires some changes I felt were beyond the scope of this blog entry

Adding ConfigureSwaggerGen to the Startup.cs ConfigureServices() method:

Enable XML Comments (Similar to Help Pages)

You can enable XML comments in the same way you do when using ASP.Net Help Pages so you can add endpoint specific documentation.  Swagger will pick up that documentation with just a few small changes.

First, enable XML comments on the Build tab of the project properties, then add the application path and filename for the comments to the Startup.cs ConfigureServices() method then add some XML comments on each Controller method.

Right-click -> Project -> Properties:

Configure Startup.cs Configuration Method to use path and filename for comments:

Add using Microsoft.Extensions.PlatformAbstractions to the Startup.cs member to use AppllicationBasePath.

As you can see, you can add a LOT more information to each end point just by adding to the XML comments, including <remarks> and <response> sections.  It’s very powerful.

Using <remarks>, defining <response code />, etc…

The documentation really takes off once we add XML comments.  Swagger breaks those comments down nicely and adds them to the details page of the endpoint.

How the API documentation looks with XML comments:

Use Data Annotation…

And lastly…  Annotate your models.  Because, at the end of the day, that’s all a developer wants, right?  What type is it? What do I need to call it? Where does it have to go?  And by when?  Don’t make us dig.  Put it out there so when we user your API we don’t have to e-mail back and forth for half a day because I’m passing to the wrong field name or type by following substandard documentation.  

Conclusion

Simply put, I think I just found my favorite new way to create API documentation.  The fact that I was able to create nicely formatted, testable end point documentation by simply writing my controller functions and installing/configuring Swagger was a very pleasant surprise.  Also, from everything I’ve read so far, I’m just scratching the surface with what I can do with Swagger. 

The last section of Shane’s tutorial describes how to implement your own .css and .html to further customize the documentation page, but I felt that was out of scope for this blog.  I can see value in it, however, for enterprises that want their API documentation pages styled similarly to the rest of their web applications.

Relevant Insights

New Site Showcases Our Growth Into a Full-Service IT Consultancy

Over the past year, Core BTS has evolved. Simply put, we’ve amassed greater scale and expertise that, in combination with...

5 Steps to Reduce Your Ransomware Risk

As the recent ransomware attack on the U.S.’s second-largest meat producer, JBS, made clear, cyberattacks on critical infrastructure can cause...

How to Unlock the Organizational Value of Digital Transformation

As organizations look to stay competitive in today's dynamic and unpredictable marketplace, a trend has re-emerged that is ushering us...
X