Practical .NET

Generate Useful Documentation for Your Web API Project

I wrote an earlier article about implementing HATEOAS in Web Services as a way of reducing documentation. In the comments to that article, a reader suggested that, if I really wanted to reduce documentation, I should be looking at Swagger.

OK: That reader was right.

I had heard about Swagger (more officially known as the OpenAPI specification), but I also knew that support for it was "spotty to non-existent" in Visual Studio. As a result, I hadn't paid attention. That was a mistake.

The idea behind the OpenAPI specification is to provide the same kind of support for RESTful Web Services that WSDL provided for SOAP-based Web Services: automatic, machine-readable documentation for Web Services to support creating and testing Web Service consumers along with support for communicating the specifications for Web Services from designers to developers. This appeals to me for the same reason as the JSON Schema: I like tools that automate the development process and ensure that interacting applications can successfully talk to each other.

Adding the Swashbuckle NuGet package to your project will give you Swagger/OpenAPI support. Perversely, I'm going to talk about that machine-readable support in a later column. This article's topic, however, is how Swashbuckle uses that information to give you a form of active documentation.

One last warning: The process for using Swashbuckle is different between ASP.NET Web API and ASP.NET Core -- in this article, I'm looking at ASP.NET Web API.

Accessing the Swagger UI
Once you've added Swashbuckle to your application you'll find a new file in your App_Start folder called SwaggerConfig.cs. This is where you'll configure Swagger. The default file will contain a minimum configuration, tailored to your project. A configuration file for a project I'm working one for one of my current clients looks like this, for example:

var thisAssembly = typeof(SwaggerConfig).Assembly;

GlobalConfiguration.Configuration
                .EnableSwagger(c =>
                    {
                        c.SingleApiVersion("v1", "CiRAM.CFCM.SOA.Population");
                    })
.EnableSwaggerUI();

To see the user interface generated by Swagger just surf to your service's base URL with /swagger tacked on the end. For my client's project, running in debug mode, the Swagger URL looks like this:

http://localhost:53916/swagger

Swagger converts that into:

http://localhost:53916/swagger/ui/index

You can use the EnableSwagger method in the configuration file to configure the URL used to reach your Swagger documentation page and to add description or contact information (among other information) to the page. You can also configure Swashbuckle to pick up any XML comments you've added to your application and include them in the Swagger page. If your Web Service has evolved into multiple versions, then you'll want to use MultipleApiVersions rather than SingleApiVersion in your configuration code.

Using the Documentation
Once you've accessed the Swagger documentation page, over on the right-hand side, you'll see a Show/Hide link that, when clicked, lists your HTTP verb operations (for example, your GETs, POSTs and so on). For any operation, clicking on the verb displays a sample of the output of the method in your choice of JSON or XML, letting you preview what you'll get from that method when you set your request's Accept header to any of text/xml, text/json, application/xml or application/json.

When building an application, this page can also be a quick way to check your service's configuration (I discovered that I had forgotten to put braces around one of the parameters in my URL template, for example).

In that page you also get the ability to submit a query to your service. The page includes a list of parameters expected by each method along with the opportunity to set those parameters to a value before submitting a query to your service. The parameter list distinguishes between those parameters that need to be part of the URL and those optional parameters that will go into your querystring. If you've marked one of the parameters in your URL template as optional, Swagger generates a separate URL entry for examples both with and without the parameter.

The information about where your parameter values go doesn't really matter when you're using the Swagger page because, of course, the page will format your requests correctly. You will, however, need that information when you start writing your own requests.

If you click on the Try It! button to submit your query, the page will show you even more information. You'll get, for starters, the URL used to send your request and a cURL command line that you can copy and paste into a Command window, incorporate into a batch file or use in automated testing. The page will also give you the response body, the response code and the response headers returned from your request.

Of course, for PUT and POST requests you need to submit parameters consisting of whole objects, either in JSON or XML. Fortunately, the Swagger page provides a sample of those input objects in the format of your choice. The page displays those objects either in a specification-like format or, more usefully, as a sample JSON or XML document with dummy values. Clicking on the sample JSON/XML format adds it to your parameter list so that you can replace those dummy values with real data to use in your test request.

The next step is to generate a machine-readable file that describes your Web Service and can be used in development. Swashbuckle/Swagger/OpenApi is doing that also, as I'll discuss in a later column.

About the Author

Peter Vogel is a system architect and principal in PH&V Information Services. PH&V provides full-stack consulting from UX design through object modeling to database design. Peter tweets about his VSM columns with the hashtag #vogelarticles. His blog posts on user experience design can be found at http://blog.learningtree.com/tag/ui/.

comments powered by Disqus

Featured

  • Creating Reactive Applications in .NET

    In modern applications, data is being retrieved in asynchronous, real-time streams, as traditional pull requests where the clients asks for data from the server are becoming a thing of the past.

  • AI for GitHub Collaboration? Maybe Not So Much

    No doubt GitHub Copilot has been a boon for developers, but AI might not be the best tool for collaboration, according to developers weighing in on a recent social media post from the GitHub team.

  • Visual Studio 2022 Getting VS Code 'Command Palette' Equivalent

    As any Visual Studio Code user knows, the editor's command palette is a powerful tool for getting things done quickly, without having to navigate through menus and dialogs. Now, we learn how an equivalent is coming for Microsoft's flagship Visual Studio IDE, invoked by the same familiar Ctrl+Shift+P keyboard shortcut.

  • .NET 9 Preview 3: 'I've Been Waiting 9 Years for This API!'

    Microsoft's third preview of .NET 9 sees a lot of minor tweaks and fixes with no earth-shaking new functionality, but little things can be important to individual developers.

  • Data Anomaly Detection Using a Neural Autoencoder with C#

    Dr. James McCaffrey of Microsoft Research tackles the process of examining a set of source data to find data items that are different in some way from the majority of the source items.

Subscribe on YouTube