Search code examples
azure-functionsopenapiopenapi-generator

How can I configure the swagger ui page for Azure Functions v3?


I added OpenApi support to an Azure functions application (v3), using .ConfigureOpenApi() in Program.Main(). I use function decorations for the specific functions but how can I control the general API name, version etc, shown on ~/api/swagger/ui ?

Here is my Program.Main() code:

        public static void Main()
        {

            var host = new HostBuilder()
                .ConfigureFunctionsWorkerDefaults(worker => worker.UseNewtonsoftJson())        
                .ConfigureOpenApi()
                .ConfigureServices(services =>
                    {
                        services.AddLogging();
                    }
                )
                .Build();

            host.Run();
        }
    }

Solution

  • To control the API meta-information you should define a class that implements IOpenApiConfigurationOptions (located in namespace Microsoft.Azure.WebJobs.Extensions.OpenApi.Core.Abstractions).

    Note: There should be only one implementation of the IOpenApiConfigurationOptions interface in your project. Class namespace or visibility does not seem to matter.

    The easiest way to do it is to inherit DefaultOpenApiConfigurationOptions provided by Microsoft.Azure.WebJobs.Extensions.OpenApi.Core and override specific properties.

    Add a file to your project with the following content (and update necessary values):

    using System;
    using Microsoft.Azure.WebJobs.Extensions.OpenApi.Core.Configurations;
    using Microsoft.Azure.WebJobs.Extensions.OpenApi.Core.Enums;
    using Microsoft.OpenApi.Models;
    
    namespace MyApp
    {
        internal class OpenApiConfigurationOptions : DefaultOpenApiConfigurationOptions
        {
            public override OpenApiInfo Info { get; set; } = new OpenApiInfo
            {
                Version = "1.0.0",
                Title = "My API",
                Description = "My API description",
                License = new OpenApiLicense
                {
                    Name = "MIT",
                    Url = new Uri("http://opensource.org/licenses/MIT"),
                }
            };
    
            public override OpenApiVersionType OpenApiVersion { get; set; } = OpenApiVersionType.V3;
        }
    }
    

    There are sample projects from Microsoft that can be found here