Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Documenting a ASP.NET Web API with Swagger

DZone's Guide to

Documenting a ASP.NET Web API with Swagger

Learn about the ways you can contribute to the ASP.NET web API for generating an API website.

· Cloud Zone
Free Resource

Deploy and scale data-rich applications in minutes and with ease. Mesosphere DC/OS includes everything you need to elastically run containerized apps and data services in production.

In this article, I’m going to take a look at some ways you could generate documentation for ASP.NET Web API.  Unless you’ve never generated a Web API website, you’ll be aware that the default templates already include functionality to generate documentation for the API which you might implement, an example of which is here at authme.ws.

Getting started

There’s more than a couple of articles already written about how to generate documentation for ASP.NET Web API using Swagger (and there’s a NuGet package called Swashbuckle which you can easily integrate), but I needed something less dynamic – in fact, I needed to generate static documentation representing what we’d promoted to production (point in time), as it needed to be provided for an audit.

The traditional documentation (e.g. Sandcastle Help File Builder) i clearly not viable as it documents managed code rather than the more important API interfaces and runtime models.

Luckily for me, there’s a toolset complimenting Swagger called Swagger codegen which generates client code to consume APIs, and for me – an ability to generate static HTML (courtesy of [1]) Unfortunately I couldn’t find a .NET port of Swagger Codegen, so I bit the bullet and compiled the Java binaries from the source using Maven and the latest JDK.

What you need

You need to be able to generate a Web API site which you can spin up in IIS or IIS Express.  Ideally, what you’d do is integrate the previously mentioned Swashbuckle NuGet package into your existing (or new) Web API Project. Once installed, all you need to do is change the project settings to generate a comments XML file (not a mandatory step, but useful – see image below) and then configure the SwaggerConfig.cs file which is inserted into the project under the App_Startup folder.

image
Enable XML comments output.

image
Swashbuckle NuGet packages (Swashbuckle and Swashbuckle.Core)

Here’s a really brief (minimal) implementation of the SwaggerConfig with the copious comments removed:

public class SwaggerConfig
{
   public static void Register()
   {
       var thisAssembly = typeof(SwaggerConfig).Assembly;
       GlobalConfiguration.Configuration 
       .EnableSwagger(c =>
       {                      
          c.SingleApiVersion("v1", "API Services");
          c.IncludeXmlComments(GetXmlCommentsPath());
       })
      .EnableSwaggerUi(c =>
       {
       });            
   }
   private static string GetXmlCommentsPath()
   {
       var path = String.Format(@"{0}bin\Services.XML", AppDomain.CurrentDomain.BaseDirectory);
       return path;
   }}

If you compile and run, you should be able to resolve the Swagger UI, like this:

image

image

A very, very impressive dynamic documentation UI.

The key here is in the generated JSON which is accessible via the URI in the textbox, in my case it is: http://localhost:2218/swagger/docs/v1 (swagger.json)

image
Example swagger JSON

Converting to static documentation

Moving on to swagger codegen, you’ll also need a copy of the Java JDK. After installing the JDK (if you haven’t already), you’ll then need to ensure that the JAVA_HOME environment variable is correctly to the correct directory (NOT the runtime directory) and install/extract Maven binaries.

I used the latest JDK (1.8, 32 bit) which has the following directory: C:\Program Files (x86)\Java\jdk1.8.0_51 I also installed Maven into the Java directory and added it to the system path (the bin directory, specifically):

image

When ready, al you need is to extract the swagger codegen code into a local directory, browse to that directory in a command prompt and type mvn package:

image  image

Wait a while while Maven grabs all the packages

Once successfully compiled, it’s a simple matter of executing the compiled jar file.  In my case, I had placed the extracted swagger files in C:\Tools.  Open a command prompt and browse to the following location:

C:\Tools\swagger-codegen-master\

To generate a static HTML document for your API use the following syntax:

java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate -ihttp://localhost:2218/swagger/docs/v1-l html

This produces a nice static document of your Web API:

image

A nice static HTML file which you can “print” to PDF, or copy and paste into Word

Troubleshooting

If your generated .json produces an empty object like this:

“Object”: {
“type”: “object”,
“properties”: {}
}

It could well be due to a lack of sufficient information about the data type in a response.  For example, take the following example Controller definition:

public class VersionController : ApiController
{    private readonly IVersionQuery _query;
            public VersionController(IVersionQuery query)
    {
        Guard.That(query, "query").IsNotNull();
        _query = query;
    }    [AllowAnonymous]
    public IHttpActionResult Get()
    {
        var version = _query.GetVersion();
        return Ok(version);
    }
}

What we’re missing here is an attribute which provides the return type, like this, decorating the Get() implementation:

[ResponseType(typeof(VersionInfo))]

I was assisted in making this discovery by the issues logged at [2], [3].

Discover new technologies simplifying running containers and data services in production with this free eBook by O'Reilly. Courtesy of Mesosphere.

Topics:
asp.net ,web api ,api

Published at DZone with permission of Rob Sanders, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}