Documenting webapi with Swagger

If you’ve ever worked with webservices, chances are you’ve run into WSDL (http://www.w3.org/TR/wsdl). In the webapi world you don’t get so much out the box – this is where swagger can help expose test methods, documentation and a lot more.

For asp.net projects you can make use of a library: https://github.com/domaindrivendev/Swashbuckle. Install via nuget and you get a UI allowing a configurable interaction with all the webapi methods in your solution:

The swagger UI:
swagger ui

The test controller and methods:
webapi methods

All pretty simple stuff – how about if you want to secure things?
An example scenario might be you only want swagger accessible if you are visiting via http://localhost (or a loopback url).

It’s straight forwards if you implement a custom webapi DelegatingHandler.

This then needs wiring into the webapi request pipelines. In your WebApiConfig file (OTB in your solution in the folder: App_Start) add:

In the TestController example above we had several httpPost methods available – to enable this functionality you need to allow the routes to include the {action} url chunk.

Azure webapi’s are now compatible with swagger – see https://azure.microsoft.com/en-gb/documentation/articles/app-service-dotnet-create-api-app/ for more info.

3 thoughts on “Documenting webapi with Swagger

  1. Are you doing this with Sitecore 8.2? I’m trying to figure out where to initialize swagger – any example pipeline methods would be useful thanks.

    • FYI this was in a standalone MVC project.

      In the past when I’ve used WebApi within Sitecore projects you still have access to the same WebApiConfig.cs config file (have a look in App_Start). Does this give you the hook you wanted?

  2. Thanks Boro. I figured out that I need kick swagger off at the same (just after) I register the WebApi routes – i.e. in pipeline processor. However I now get the following error when trying to access my docs –

    “ExceptionMessage”:”Not supported by Swagger 2.0: Multiple operations with path ‘sitecore/shell/api/ct/Action/Review’

    Is there a way to tell swagger to only document certain controller (or certain routes)?

Leave a Reply

Your email address will not be published.