Ingredients for well-designed OWIN middleware components - Part 6

Edit this page | 1 minute read

In the fifth post of this series I talked about some PowerShell tips to align the versions of all NuGet packages. In this sixth post, I'd like to show you how you can make your HTTP API much easier to use.

Ingredient 7: Swagger-enabled documentation
If your component exposes an HTTP API based on WebAPI, I would suggest you add support for Swagger documentation. Swagger has become the ad-hoc WSDL equivalent for HTTP-based API. Adding this to your WebAPI controllers is as easy as referencing the Swashbuckle NuGet package and attaching the following lines of code to your HttpConfiguration.

private static void EnableSwagger(HttpConfiguration configuration)
{
  configuration.EnableSwagger(c =>
  {
    c.SingleApiVersion("v1", "Piercer; easily diagnose run-time assemblies and threads");
    c.RootUrl(req => SwaggerDocsConfig.DefaultRootUrlResolver(req) + "/api");
    c.IncludeXmlComments(GetXmlCommentsPath());
  }).EnableSwaggerUi();
}

private static string GetXmlCommentsPath()
{
  return Assembly.GetExecutingAssembly().CodeBase.ToLower().Replace(".dll", ".xml");
}

In the case of Piercer, starting the Test Host and browsing to http://localhost:12345/api/swagger/docs/v1returns the following JSON that you can use directly to generate code using swagger-codegen.

{
"swagger": "2.0",
"info": {
"version": "v1",
"title": "Piercer; easily diagnose run-time assemblies and threads"
},
"host": "localhost:12345",
"basePath": "/api",
"schemes": ["http"],
"paths": {
"/piercer/assemblies": {
"get": {
"tags": ["Piercer"],
"summary": "Returns all the run-time assemblies of the host process.",
"operationId": "Piercer_GetAssemblies",
"consumes": [],
"produces": ["application/json",
"text/json",
"application/xml",
"text/xml"],
"responses": {
"200": {
"description": "OK",
"schema": {
"type": "array",
"items": {
"type": "string"
}
}
}
},
"deprecated": false
}
}
},
"definitions": {

}
}

On the other hand, if you would browse to http://localhost:12345/api/swagger/ui/index, you'll get this nice UI:

Customizing how your component exposes its HTTP APIs or tweaking the look and feel of the documentation page is all documented at the Swashbuckle landing page

Leave a Comment