While web API and MVC tend to go together, there are cases where you want a pure web API project. This is most common with REST services that have no UI. You would think that this should be easy to set up but, surprisingly, the default web API project in Visual Studio includes MVC. MVC brings in a lot of stuff that you simply don’t need including styling, MVC routing and client libraries. For a REST service where there will be no UI this is wasteful. In this article I’m going to discuss how to create a basic project template for REST services without the need for MVC.
Documenting Web APIs with Swagger
A while back I posted an article on how to extend the existing help pages generated by Visual Studio for Web API projects to use reflection instead of XML documentation. One of the limitations of that approach was that you could not test the APIs directly. You had to use SoapUI or equivalent. Since then I have started using Swagger for documentation. As a documentation/testing tool it fills the need. In this article I will demonstrate how to integrate Swagger into a Web API project. Additionally I will continue to use the reflection provider from the previous article.
Documenting Web APIs
Prerequisite: This post assumes you understand what web APIs are, what they are designed for and how to write them. If not then take a look at this MSDN article first.
In order for web APIs to be useful they need documentation. Unlike traditional APIs there is no function signatures to look at. Even if you know the name of the “function” there is no easy way to get the parameters or return value. Hence documentation is important to anyone wanting to use such an API. If you are writing a REST API then the documentation is technically where the HATEOAS concept comes in. The reality is, for now at least, most people write web APIs using the REST API philosophy but without HATEOAS. Hence documentation is still needed.
The biggest issue with documentation is keeping it in sync with the code. We have XML doc tags for .NET languages and can use them with web API. But to be useful we have to ensure the documentation is refreshed whenever the API changes. ASP.NET solves this problem by relying on the existing XML doc tags that you’re likely already using. At runtime the documentation is rendered on demand based upon the existing comments. This is one approach to solving the problem. In this article I will take a look at the “built in” functionality, identify when it might not be useful to you and provide an alternative approach that I use.