Develop Microservices Using Azure Functions, API Management
Explore how to easily build cloud-deployed microservices using serverless technology with Azure Functions and connect with APIs standardized in API Management.
Join the DZone community and get the full member experience.
Join For FreeMicroservices are a popular architectural pattern for building scalable and modular applications. They allow developers to focus on building small, independent, and reusable services that interact with each other through APIs. This blog will guide you through creating a simple serverless microservice and deploying it to Azure Cloud. I have used this approach to start building simple prototypes of various products, get early feedback from customers, and iterate faster.
Components
Azure Functions: The Serverless Workhorse
Azure Functions is a serverless compute service that lets you run code pieces (functions) in Azure Cloud without worrying about provisioning infrastructure. We will leverage the event-driven functionality of Azure Functions to execute some API logic based on an HTTP request trigger.
Azure API Management: The Gateway
Azure API Management acts as a front door for microservices. It enables standard management of API, generating API documentation using swagger, setting authorization and rate limiting on APIs.
Building a Simple Weather Microservice using Azure Functions and API Management
Let's build a simple weather microservice using Azure Functions and API Management. We will build an API to get the current weather forecast. In this article, we are using C# as our development language, but other languages like Java and Python are also supported. We are also developing in Visual Studio Code IDE, which has native integrations with Azure Cloud, enabling us to publish APIs directly to the cloud from our development machine.
Prerequisites
- Create an Azure account and active subscription.
- Install Visual Studio Code.
- Add the Azure Functions extension to the Visual Studio Code.
- Install Azure Functions Core Tools, which enables local debugging of functions.
Step 1: Create Azure Functions Project
The Functions extension in VS Code enables the creation of a function app with a sample function. Here are the steps to create a HTTP triggered function in a new project:
1. Open the VS Code command palette (press F1) and search for Azure Functions: Create New Project.
2. On the location prompt, create a project folder: WeatherService is a desired location.
3. Select the following options next: language C#, .NET 8.0 Isolated LTS version, and HTTP trigger for the template.
4. For the function name, select "GetCurrentForecastFunction." Then, select a namespace: "Weather.Function."
5. For access rights, select "Function." This requires a function key to be provided when the function is called.
The above steps will create a WeatherService
functions project with a single function called, GetCurrentForecastFunction
, similar to the one below:
Step 2: Run the Function Locally
1. Let's execute the test function project created by hitting "F5" (also can be executed by Run -> Debug).
The output in the terminal will look similar to:
Azure Functions Core Tools
Core Tools Version: 4.0.6821 Commit hash: N/A +c09a2033faa7ecf51b3773308283af0ca9a99f83 (64-bit)
Function Runtime Version: 4.1036.1.23224
[2025-01-25T15:59:49.061Z] Found /Users/ankitmasrani/Projects/WeatherService/WeatherService.csproj. Using for user secrets file configuration.
[2025-01-25T15:59:50.295Z] Worker process started and initialized.
Functions:
GetCurrentForecastFunction: [GET] http://localhost:5004/api/GetCurrentForecastFunction
The port can be set by updating the local.settings.json
file:
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "",
"FUNCTIONS_WORKER_RUNTIME": "dotnet-isolated"
},
"Host": {
"LocalHttpPort": 5004
}
}
Visiting the localhost link, you can see a test function output: "Welcome to Azure Functions."
Now, let's update this function logic to invoke a weather forecast API that will return the current forecast for a city. Many external APIs can be invoked to get weather information. I have created a free account for WeatherAPI.com and used their APIs in this article. Once you create a free account, you can create a subscription key in your account, and it will be used to authorize requests to get the current weather information.
The code snippet below shows the function logic updated with integrating with a weather API to get the current weather for a city. We are taking the city as an input to the API, and it is configured in the "Route" option.
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Extensions.Logging;
using System.Net.Http;
using System.Threading.Tasks;
namespace Weather.Function
{
public class GetCurrentForecastFunction
{
private readonly ILogger<GetCurrentForecastFunction> _logger;
public GetCurrentForecastFunction(ILogger<GetCurrentForecastFunction> logger)
{
_logger = logger;
}
[Function("GetCurrentForecastFunction")]
public async Task<IActionResult> Run([HttpTrigger(AuthorizationLevel.Function, "get", Route = "weather/{city}")] HttpRequest req, string city, FunctionContext executionContext)
{
_logger.LogInformation("Get current weather");
using (HttpClient client = new HttpClient())
{
try
{
HttpResponseMessage response = await client.GetAsync($"https://api.weatherapi.com/v1/current.json?key=<YOUR_API_KEY>&q={city}&aqi=no");
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
return new OkObjectResult(responseBody);
}
catch (HttpRequestException e)
{
Console.WriteLine($"Request error: {e.Message}");
}
}
return new BadRequestResult();
}
}
}
Now, you can execute the function and try this locally:
Next, let's publish this Azure function to Azure Cloud so it can be shared with clients or customers.
Step 3: Publish the Function Logic to Azure
Installing the Azure Functions extension in VS Code will show the Azure icon in VS Code. In there, we can connect to the Azure account and set up new Azure resources or view or update existing resources.
We will create a new Function App as shown below:
Next, there will be a few prompts:
- Enter a globally unique name for the function app.
- Select a runtime stack: .Net 8 (isolated)
- Select a location. This is the Azure region where the function app will be hosted. We can select the recommended region. It will be generally the region where capacity is available.
Once triggered, the function app creation will start, and in the end, an output similar to the one below can be seen:
Next, you can log in to the Azure portal, and under the subscription, you can view a resource group created with the same name as the function app. This resource group contains all the resources required for a function app.
- Resource group is a logical container for all related resources.
- Function app allows grouping of functions for easier management, sharing execution plan, etc.
- An Azure App Service plan defines the host for the function app. The App service plan that we created by default will be a Consumption Service plan. In the Consumption Service plan, host-to-execute functions are added and removed dynamically based on function triggers, and you are charged for the compute resources when your functions are running. Please see more information here.
- Application Insights instance tracks the use of the app functions.
Once the function app is created, it can be viewed in the Resources Explorer in the Azure VS Code extension, and we can right-click on the function app and deploy to it:
Next, visit the Azure Function app on the Azure Portal under your resource group. In the overview section of the function app, the weather function will be visible. Click on the function. Then, you can copy the function URL and execute it in a browser:
Awesome, now we have a cloud-deployed API using Azure Function apps.
Step 4: Connect Azure Function from API Management
API Management is an Azure service that acts as a gateway for your APIs. We can define APIs, rate limiting parameters, and API authorization using API management. It allows our APIs to be defined irrespective of the backend where the API logic is executed. In this case, our backend service to execute the API is Azure Function App.
- Create an API Management instance in Azure Portal. The VS Code extension for API management can also be used to create this but in my experience, it does not fully work when we want to connect it to Azure functions. For now, we can use the portal.
-
Next, you can create an API from Function App:
-
On selection of your Function App, update the API settings as below:
-
Then, you can test your API in the API Management console and view the output:
- You can also share this API with others:
- URL: The request URL is
https://<API_MANAGEMENT_INSTANCE_NAME>.azure-api.net/weather/<CITY>
. This is also visible from the Test console shown in the above image. - In the settings, we configured the API to be authorized by a subscription key. This can be managed in the Subscription blade on the left. You can create a subscription for a particular scope which can be a specific API or all APIs:
https://<API_MANAGEMENT_INSTANCE_NAME>.azure-api.net/weather/<CITY>?subscription-key=<SUSCRIPTION_KEY>
.
- URL: The request URL is
Step 5: Monitor Your APIs
Monitoring your microservice is crucial for ensuring its reliability and understanding its usage patterns. Azure API Management offers built-in metrics that allow you to monitor your APIs and their interactions. These metrics help you understand how clients are using your microservice and provide valuable data for performance tuning.
Key metrics include:
- API request counts: Tracks the number of requests made to your API endpoints. This helps identify usage patterns, peak traffic times, and potential overloading scenarios.
- Request latency: Measures the time taken to process requests and return responses. Monitoring latency ensures your API meets performance expectations.
- Response status codes: Provides a breakdown of HTTP response codes (e.g., 200, 404, 500) to detect issues like frequent client errors or server-side failures.
Recap
Building microservices with Azure Functions, API Management, and VS Code is a straightforward yet powerful approach to creating scalable and modular applications. Here's a quick recap of what we've achieved:
- Azure Functions: Provided a lightweight, serverless compute model to implement our microservice.
- API Management: Acted as a secure and efficient API gateway to expose and manage our microservice.
- VS Code: Simplified the development, testing, and deployment process with robust Azure integrations.
With these tools, we created, deployed, and managed a fully functional microservice. Whether you're a solo developer exploring serverless architecture or part of a larger team transitioning to microservices, this workflow offers an accessible entry point and gets you quickly started without worrying about infrastructure planning.
Next Steps
To productionize your microservice, focus on these key areas:
Rate Limiting and Throttling
Use Azure API Management to enforce rate limits, quotas, and throttling to prevent misuse and ensure fair resource allocation.
Capacity Planning
Analyze traffic patterns and implement autoscaling to handle demand. Test with tools like Azure Load Testing to identify bottlenecks.
Automating Deployment
Set up a CI/CD pipeline with Azure DevOps to automate builds, tests, and deployments. Use Infrastructure as Code for consistent cloud setups.
Securing Your Microservice
Implement authentication (OAuth 2.0, API keys) via API Management, and manage secrets with Azure Key Vault. Enable managed identities for secure resource access.
Opinions expressed by DZone contributors are their own.
Comments