Adding Swagger UI to your Azure Function APIs allows you for providing documentation for your serverless API pretty easily.
![Swagger UI to Azure Function APIs](https://i0.wp.com/puresourcecode.com/wp-content/uploads/2020/06/rendering-swagger-ui-via-azure-functions-06.png?w=640&ssl=1)
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"
}
]
}
}
}
2 thoughts on “Adding Swagger UI to Azure Function APIs”