Adding Swagger UI Documentation to Azure Function APIs

You can set up Swagger UI in your Azure Function API to allow for providing documentation for your serverless API pretty easily.

Initial Configuration

First, add the SwashBuckle library to your process via the <project>.csproj file:

<ItemGroup>
    <PackageReference ... />
    <PackageReference Include="AzureFunctions.Extensions.Swashbuckle" Version="1.4.1" />
    ...
</ItemGroup>

Next set up the SwashBuckle startup code in SwashBucketStartup.cs:

using System.Reflection;
using AzureFunctions.Extensions.Swashbuckle;
using YOUR_NAMESPACE;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Hosting;

[assembly: WebJobsStartup(typeof(SwashBuckleStartup))]
namespace YOUR_NAMESPACE
{
  internal class SwashBuckleStartup : IWebJobsStartup
  {
    public void Configure(IWebJobsBuilder builder)
    {
      builder.AddSwashBuckle(Assembly.GetExecutingAssembly());
    }
  }
}

Now create both HTTP Triggers for the Swagger document:

[FunctionName("SwaggerJson")]
[SwaggerIgnore]
public static Task<HttpResponseMessage> Run(
    [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "json")]
        HttpRequestMessage req,
    ILogger log,
    [SwashBuckleClient] ISwashBuckleClient swashBuckleClient)
{
  return Task.FromResult(swashBuckleClient.CreateSwaggerDocumentResponse(req));
}

And the Swagger UI document:

[FunctionName("SwaggerUI")]
[SwaggerIgnore]
public static Task<HttpResponseMessage> Run(
    [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "ui")]
        HttpRequestMessage req,
    ILogger log,
    [SwashBuckleClient] ISwashBuckleClient swashBuckleClient)
{
  return Task.FromResult(swashBuckleClient.CreateSwaggerUIResponse(req, "json"));
}

Running this locally will provide two endpoints:

The final step for initial configuration is changing the documentation for the API page. Add the following to host.json:

{
  "version": "2.0",
  "extensions": {
    ...

    "Swashbuckle": {
      "Documents": [
        {
          "Title": "YOUR_TITLE",
          "Version": "v1",
          "Description": "YOUR_DESCRIPTION"
        }
      ]
    }
  }
}

Which will give you:

Further Reading:

https://medium.com/@yuka1984/open-api-swagger-and-swagger-ui-on-azure-functions-v2-c-a4a460b34b55

Leave a Reply

Your email address will not be published. Required fields are marked *