Azure Functions on PureSourceCode.com

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 from NuGet searching this package

AzureFunctions.Extensions.Swashbuckle

Next set up the SwashBuckle startup code in SwashBuckleStartup.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> RunUI(
    [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "/")]
        HttpRequestMessage req,
    ILogger log,
    [SwashBuckleClient] ISwashBuckleClient swashBuckleClient)
{
  return Task.FromResult(swashBuckleClient.CreateSwaggerUIResponse(req, "json"));
}

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"
        }
      ]
    }
  }
}

By Enrico

My greatest passion is technology. I am interested in multiple fields and I have a lot of experience in software design and development. I started professional development when I was 6 years. Today I am a strong full-stack .NET developer (C#, Xamarin, Azure)

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: