Be Sociable, Share!

Tweet



Email

WhatsApp



Recently I was working on designing and implementing a large scale RESTful API using ASP.NET Web API, this RESTful API contains large number of endpoints with different data models used in the request/response payloads.

Proper documentation and having a solid API explorer (Playground) is a crucial thing for your API success and likability by developers. There is a very informative slides by John Musser which highlights the top 10 reasons which makes developers hate your API, and unsurprisingly the top one is the lack of documentation and the absence of interactive documentation; so to avoid this pitfall I decided to document my Web API using Swagger.

Swagger basically is a framework for describing, consuming, and visualizing RESTful APIs. The nice thing about Swagger that it is really keeps the documentation system, the client, and the server code in sync always, in other words the documentation of methods, parameters, and models are tightly integrated into the server code.

ASP.NET Web API Documentation using Swagger

So in this short post I decided to add documentation using Swagger for a simple ASP.NET Web API project which contains a single controller with different HTTP methods, the live demo API explorer can be accessed here, and the source code can be found on GitHub. The final result for the API explorer will look as the image below:

Swagger is language-agnostic so there are different implementations for different platforms. For the ASP.NET Web API world there is a solid open source implementation named “Swashbuckle” this implementation simplifies adding Swagger to any Web API project by following simple steps which I’ll highlight in this post.

The nice thing about Swashbuckle that it has no dependency on ASP.NET MVC, so there is no need to include any MVC Nuget packages in order to enable API documentation, as well Swashbuckle contains an embedded version of swagger-ui which will automatically serve up once Swashbuckle is installed.

Swagger-ui basically is a dependency-free collection of HTML, Javascript, and CSS files that dynamically generate documentation and sandbox from a Swagger-compliant API, it is a Single Page Application which forms the play ground shown in the image above.

Steps to Add Swashbuckle to ASP.NET Web API

The sample ASP.NET Web API project I want to document is built using Owin middleware and hosted on IIS, I’ll not go into details on how I built the Web API, but I’ll focus on how I added Swashbuckle to the API.

For brevity the API contains single controller named “StudentsController”, the source code for the controller can be viewed here, as well it contains a simple “Student” Model class which can be viewed here.

Step 1: Install the needed Nuget Package

Open NuGet Package Manager Console and install the below package:

Install-Package Swashbuckle 1 Install-Package Swashbuckle

Once this package is installed it will install a bootstrapper (App_Start/SwaggerConfig.cs) file which initiates Swashbuckle on application start-up using WebActivatorEx.

Step 2: Call the bootstrapper in “Startup” class

Now we need to add the highlighted line below to “Startup” class, so open the Startup class and replace it with the code below:

[assembly: OwinStartup(typeof(WebApiSwagger.Startup))] namespace WebApiSwagger { public class Startup { public void Configuration(IAppBuilder app) { HttpConfiguration config = new HttpConfiguration(); WebApiConfig.Register(config); Swashbuckle.Bootstrapper.Init(config); app.UseWebApi(config); } } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 [ assembly : OwinStartup ( typeof ( WebApiSwagger . Startup ) ) ] namespace WebApiSwagger { public class Startup { public void Configuration ( IAppBuilder app ) { HttpConfiguration config = new HttpConfiguration ( ) ; WebApiConfig . Register ( config ) ; Swashbuckle . Bootstrapper . Init ( config ) ; app . UseWebApi ( config ) ; } } }

Step 3: Enable generating XML documentation

This is not required step to use “Swashbuckle” but I believe it is very useful for API consumers especially if you have complex data models, so to enable XML documentation, right click on your Web API project — >”Properties” then choose “Build” tab, after you choose it scroll down to the “Output” section and check “XML documentation file” check box and set the file path to: “bin\[YourProjectName].XML” as the image below. This will add an XML file to the bin folder which contains all the XML comments you added as annotation to the controllers or data models.

Step 4: Configure Swashbuckle to use XML Comments

By default Swashbuckle doesn’t include the annotated XML comments on the API controllers and data models into the generated specification and the UI, to include them we need to configure it, so open file “SwaggerConfig.cs” and paste the highlighted code below:

public class SwaggerConfig { public static void Register() { Swashbuckle.Bootstrapper.Init(GlobalConfiguration.Configuration); // NOTE: If you want to customize the generated swagger or UI, use SwaggerSpecConfig and/or SwaggerUiConfig here ... SwaggerSpecConfig.Customize(c => { c.IncludeXmlComments(GetXmlCommentsPath()); }); } protected static string GetXmlCommentsPath() { return System.String.Format(@"{0}\bin\WebApiSwagger.XML", System.AppDomain.CurrentDomain.BaseDirectory); } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 public class SwaggerConfig { public static void Register ( ) { Swashbuckle . Bootstrapper . Init ( GlobalConfiguration . Configuration ) ; // NOTE: If you want to customize the generated swagger or UI, use SwaggerSpecConfig and/or SwaggerUiConfig here ... SwaggerSpecConfig . Customize ( c = > { c . IncludeXmlComments ( GetXmlCommentsPath ( ) ) ; } ) ; } protected static string GetXmlCommentsPath ( ) { return System . String . Format ( @"{0}\bin\WebApiSwagger.XML" , System . AppDomain . CurrentDomain . BaseDirectory ) ; } }

Step 5: Start annotating your API methods and data models

Now we can start adding XML comments to API methods so for example if we take a look on the HTTP POST method in Students Controller as the code below:

/// <summary> /// Add new student /// </summary> /// <param name="student">Student Model</param> /// <remarks>Insert new student</remarks> /// <response code="400">Bad request</response> /// <response code="500">Internal Server Error</response> [Route("")] [ResponseType(typeof(Student))] public IHttpActionResult Post(Student student) { //Method implementation goes here.... } 1 2 3 4 5 6 7 8 9 10 11 12 13 /// <summary> /// Add new student /// </summary> /// <param name="student">Student Model</param> /// <remarks>Insert new student</remarks> /// <response code="400">Bad request</response> /// <response code="500">Internal Server Error</response> [ Route ( "" ) ] [ ResponseType ( typeof ( Student ) ) ] public IHttpActionResult Post ( Student student ) { //Method implementation goes here.... }

You will notice that each XML tag is reflected on the Swagger properties as the image below:



Summary

You can add Swashbuckle seamlessly to any Web API project, and then you can easily customize the generated specification along with the UI (swagger-ui). You can check the documentation and troubleshooting section here.

That’s it for now, hopefully this post will be useful for anyone looking to document their ASP.NET Web API, if you have any question or you have used another tool for documentation please drop me a comment.

The live demo API explorer can be accessed here, and the source code can be found on GitHub.

Follow me on Twitter @tjoudeh