OpenAPI

#CASBAN6: Add a Swagger (OpenAPI) page to Azure Functions

#CASBAN6: Add a Swagger (OpenAPI) page to Azure Functions

Why?

Adding a Swagger page to any API project (not only with Azure Functions) is nowadays one of the most common steps. Implementing the OpenAPI specification makes your API easily testable during development, and in the end, it provides an interactive documentation page to your API consumers.

While these are the major advantages, you can go deeper into that topic on the OpenAPI website. Swagger has become the most popular implementation of the OpenAPI specification and is also available for Azure Functions.

Adding the NuGet

Adding the Swagger UI to our Azure Function needs another NuGet package:

Microsoft.Azure.WebJobs.Extensions.OpenApi

The documentation is only available on GitHub (at the time of writing this post, at least).

Getting started

Now that we have downloaded the NuGet package into our project, we need to configure three or four things in the Program.cs file of our Function app. In the ConfigureServices lambda of the Main method, add these lines:

services.AddSingleton<IOpenApiConfigurationOptions>(_ =>
{
    OpenApiConfigurationOptions options = new OpenApiConfigurationOptions
    {
        Info = new OpenApiInfo
        {
            Version = "1.23131.0",
            Title = "Serverless Blog API",
            Description = "This is the API on which the serverless blog engine is running.",
            TermsOfService = new Uri("https://yourdomain.com/tos"),
            Contact = new OpenApiContact
            {
                Name = "Your Name goes here",
                Email = "info@yourdomain.com",
                Url = new Uri("https:/yourdomain.com")
            },
            License = new OpenApiLicense
            {
                Name = "License",
                Url = new Uri("https://yourdomain.com/license")
            }
        },
        Servers = DefaultOpenApiConfigurationOptions.GetHostNames(),
        OpenApiVersion = OpenApiVersionType.V3,
        IncludeRequestingHostName = true,
        ForceHttps = false,
        ForceHttp = false
    };
    return options;
});

Let’s walk through that code. We are adding a new OpenApiInfo object filling all the details about contact, licence, etc. Then we configure additional items like the servers and the OpenAPI specifications version. Last, but not least, we are not forcing the Swagger page to use either http or https. This makes testing locally (especially on macOS) easier.

On Azure, the API gets redirected to https, anyway, so this should not be much of a problem. You can change this according to your needs.

If you are now debugging your Function app, you will see new endpoints in the console:

OpenAPI-endpoint-Azure-function-console

Opening the RenderSwaggerUI URL will lead you to your newly created Swagger page.

Attributing the Function methods

Now that we have our configuration in place, we finally can start to decorate our methods with the OpenAPI attributes. Let’s have a look at the GetList function for posts:

[OpenApiOperation("GET", "Post", Description = "Gets a list of posts from the database.", Visibility = OpenApiVisibilityType.Important)]
[OpenApiParameter("blogId", Type = typeof(Guid), Required = true, Description = "Id of the blog on which the posts exist", Visibility = OpenApiVisibilityType.Important)]
[OpenApiParameter("skip", In = ParameterLocation.Query, Type = typeof(int), Required = true, Description = "skips the specified amount of entries from the results", Visibility = OpenApiVisibilityType.Important)]
[OpenApiParameter("count", In = ParameterLocation.Query, Type = typeof(int), Required = true, Description = "how many results are being returned per request", Visibility = OpenApiVisibilityType.Important)]
[OpenApiResponseWithBody(HttpStatusCode.OK, "application/json", typeof(Post), Description = "Gets a list of posts")]
[OpenApiResponseWithoutBody(HttpStatusCode.Unauthorized, Description = "Response for unauthenticated requests.")]
[OpenApiResponseWithBody(HttpStatusCode.BadRequest, "text/plain", typeof(string), Description = "Request cannot not be processed, see response body why")]

Let’s go through the attributes. To add the endpoint to the Swagger page, add the OpenApiOperation attribute and specify the http method, a tag as well as the description. By setting the visibility to important, we make sure the field gets always shown. The tag is used to group endpoints on the Swagger page.

Depending on your endpoint, you may have parameters. You can add them by using the OpenApiParameter attribute. The In parameter specifies the usage location (path, query, header or cookie). In this project, I used only the default value (path) and the query location.

At the end, we are also describing the output of our function by using the OpenApiResponseWithBody and OpenApiResponseWithoutBody attributes. Specify the status code, the content type and its corresponding object as well as a description.

This is the result of the attribution shown above:

Swagger-UI-Sample-Post

Conclusion

By investing some time into attributing all your functions, you will have a fully blown API documentation ready for yourself and your API consumers. I recommend studying the samples found in the GitHub repo, which helped me a lot to understand all the attributes and how to implement the Swagger page. As always, I hope this post will be helpful for some of you.

In the next post, I will show you how to use an Azure Function as a facade for uploading, deleting and retrieving files from Azure Blob storage.

Until the next post, happy coding, everyone!

Posted by msicc in Azure, Dev Stories, 1 comment
#CASBAN6: Setting up an Azure Functions project for the API

#CASBAN6: Setting up an Azure Functions project for the API

Now that we have our Entity Framework project in place and our DTO mappings ready, it is finally time to create the API for our blogging engine. I am using Azure Functions for this.

Out-of-Process vs. In-Process

Azure Functions can be run in-process or in an isolated process. The isolated project decouples the function app from the underlying process, which enables additional features like custom middleware and Dependency Injection. Besides that, it allows you to run non-LTS versions, which can be helpful sometimes. These were the main reasons for choosing the Out-of-Process model. If you want to learn more about that topic, I recommend reading the docs.

Create the project

As you may have noticed, I recently became kind of a fan of JetBrains’ Rider IDE. Some steps may be different if done in Visual Studio, but you will be able to follow along.

First, make sure you have the Azure plugin installed. Go to the Settings, and select Plugins on the list at the left-hand side. Search for ‘Azure’ and install the Azure Toolkit for Rider. You will need to restart the application.

JetBrains Rider Plugin Settings

Once you have the plugin installed, open your solution and create a new project in it (I made it in a separate folder). Select the Azure Functions template on the left.

JetBrains Rider New Project dialog with Azure Functions selected.

I named the project BlogFunctions. Select the Isolated worker runtime option, and as Framework, we keep it on .NET 6 for the time being.

NuGet packages and project references

To enable all the functionalities we are going to use and add, we need some NuGet packages:

  • Microsoft.Azure.Functions.Worker, Version=1.10.0
  • Microsoft.Azure.Functions.Worker.Sdk, Version=1.7.0
  • Microsoft.Azure.Functions.Worker.Extensions.Http, Version=3.0.13
  • Microsoft.Azure.Functions.Worker.Extensions.ServiceBus, Version=5.7.0
  • Microsoft.Extensions.DependencyInjection, Version=6.0.1
  • Microsoft.Azure.Core.NewtonsoftJson, Version=1.0.0

Please note that I use the latest version that support .NET 6 and not the .NET 7. We also need to reference the projects we already created before, as you can see in this picture:

Project and Package references in the Function app

Program.cs

Now we finally can have a look at our Program.cs file. I am not using top-level statements here, but feel free if you want to, the code doesn’t change, just the surroundings.

To make our application running, we need to create a new HostBuilder object. I still prefer Newtonsoft.Json over System.Text.Json, so let’s add that one first:

IHost? host = new HostBuilder().ConfigureFunctionsWorkerDefaults(worker => worker.UseNewtonsoftJson()).Build();

host.Run();

In order to be able to use our Entity Framework project we created already earlier, we need to add a ConnectionString and also configure the application to instantiate our DBContext. Update the code above as follows:

string? sqlConnectionString = Environment.GetEnvironmentVariable("SqlConnectionString");

IHost? host = 
	new HostBuilder().
		ConfigureFunctionsWorkerDefaults(worker => worker.UseNewtonsoftJson()).              
		ConfigureServices(services =>
		{
			if (!string.IsNullOrWhiteSpace(sqlConnectionString))
				services.AddDbContext<BlogContext>(options =>
					options.UseSqlServer(sqlConnectionString));	              
		}).
		Build();

host.Run();

The connection string will be read from the local.settings.json file locally and from the Function app’s configuration on Azure. For the moment, just add your local ConnectionString:

{
  "IsEncrypted": false,
    "Values": {
        "FUNCTIONS_WORKER_RUNTIME": "dotnet-isolated",
        "AzureWebJobsStorage": "UseDevelopmentStorage=true",
        "SqlConnectionString": "Data Source=localhost;Initial Catalog=localDB;User ID=sa;Password=thisShouldB3Stronger!",
        
    }
}

Side note: If you have a look into the GitHub repo, you will see that there are some entries for OpenAPI in both files. The OpenAPI integration will get its own blog post later in this blog series, but for this post, they are not important.

Conclusion

In this post, we had a look at how to set up an Azure Functions app with Newtonsoft.Json and our Entity.Framework DbContext. In the next post, we will have a look at some Extensions that will be helpful, as well as the base class implementation of most functions within the app. As always, I hope this post was helpful for some of you.

Until the next post, happy coding, everyone!

Posted by msicc in Azure, Dev Stories, 2 comments