Try for free Book a demo

Getting started with Azure API management health check

Microsoft Azure

12 Mins Read | Last modified on March 4th, 2024

Azure API management health check

Due to the increasing influence of businesses on APIs, the volume of APIs on which they rely, and the administrative challenges that APIs pose, API administration has gained popularity. For the most part, other apps don’t have the exact requirements or construction and management processes as APIs. Vital documentation, higher security standards, extensive testing, frequent versioning, and excellent reliability are all requirements for using APIs properly.

What is API Management?

Application program interface (API) management is the process through which a company develops, monitors, and manages APIs in a safe and scalable environment. When it comes to businesses that create or use APIs to track the lifespan of an interface, API management seeks to ensure that the requirements of programmers and apps that utilize the API are satisfied.

Although each organization may have different demands in terms of API administration, the practice includes several fundamental tasks, including security, monitoring, and version control.

What is Azure API management?

Azure API Management is a hybrid, multi-cloud management tool for APIs in all environments. API Management, a platform-as-a-service, provides the entire API lifecycle. Businesses can publish APIs to external, partner, and internal developers with the help of API Management (APIM) to maximize the value of their data and services.

Azure API management

What is an API health check?

The API health check is fundamentally an API monitoring technique that examines your API and notifies you of any issues it finds. Consider it a diagnostic tool for your codebase that can assist you in identifying problems before they cause you more trouble than is necessary.

API health check vs. API ping

When a request is made, the API ping endpoint returns the message 200 OK. The ping endpoint on the API is used to confirm that HTTP requests make it to the API. Dev-ops engineers additionally ping APIs (using ping endpoints) to verify that the API gateway, SSL, routing, and other network-level components cooperate to send a request to the API process.

API ping endpoint only briefly verifies that the API is active and reachable. The API health check endpoint, which was previously covered, verifies several things before returning the state of the API and its dependents.

I’ve encountered numerous API ping endpoints throughout my career that, when the API is broken, return 200 OK. The API health check endpoint is preferable to the API ping endpoint, as it offers many more advantages and supports all API ping use cases.

API health checklist / How to get Azure APIM health check & details

A wide range of elements can be checked by an API health check endpoint; which ones should be checked, and which ones should be skipped? As a general guideline, the API health check endpoint needs to investigate anything that can prevent the API from responding to incoming requests. Each API has its requirements for this, but we’ve included some of the most common ones below for your API health check endpoint:

Downstream Operation Status – Your API’s functionality may rely on other APIs. Be sure to verify that the downstream APIs you rely on are operational.

Database connection – There may be an open connection to a data source through your API. Make sure the connection is active when performing the health assessment.

Database response time – Measure the usual Database query’s average response time.

Memory consumption – Memory leaks may create a spike in memory utilization, disrupting services.

In-flight messages – Does your API support message queuing? Too many in-flight messages may indicate a deeper problem.

Monitor the health of all the APIs and identify the errors

API monitoring operates by repeatedly calling the API from several global locations and logging various performance timings and response information. The following steps make up the API monitoring process:

Configure – To perform the API checks, configure the different API parameters, such as the URL, HTTP method, request details, expected values, and locations.

Run: The given location periodically calls the specified API with the supplied parameters. The System then logs the outcomes of the API call, including response times, HTTP status, and response information.

Alert – Compares the actual values to the configuration’s expected values. Mark the run as unsuccessful and deliver the alerts if they don’t match.

Report: We produce reports on availability and response time over time for the historical study.

For more information, you can refer the blog here.

Azure API Management Health check via Azure Functions

Keeping our systems’ “moving pieces” under control is crucial in a world of distributed transactions, microservices, reliability, and automation. Health monitoring and the proper instrumentation are essential for a system to be successful in production.

Your microservices may occasionally depend on more than “only” the database; they may additionally use internal services or APIs from outside sources. We’re fortunate that.NET offers excellent support for various health checks, saving us from constantly having to invent the wheel.

Azure API Management Health check

We can offer a GET endpoint with a policy that checks the underlying service. It seems that APIM offers a default endpoint for a health check. If everything is in order, you must make a GET request to /status-0123456789abcdef, and you’ll get a 200 status back with an empty body. I’m done now!

Let’s look at some possible coding solutions. Installing the Nuget package comes first.

Microsoft.Extensions.Diagnostics.HealthChecks.

Then we have to create a custom class to run the health check :
using System;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Diagnostics.HealthChecks;
namespace MyFunctionApp
{
    public class ApimHealthCheck : IHealthCheck
    {
        private readonly HttpClient _httpClient;
        public ApimHealthCheck(IHttpClientFactory httpClientFactory)
        {
            if (httpClientFactory is null)            
                throw new ArgumentNullException(nameof(httpClientFactory));            
            _httpClient = httpClientFactory.CreateClient("APIM");
        }
        public async Task CheckHealthAsync(
            HealthCheckContext context,
            CancellationToken cancellationToken = default)
        {
            var response = await _httpClient.GetAsync("/status-0123456789abcdef");
            return (response.StatusCode == System.Net.HttpStatusCode.OK) ?
                HealthCheckResult.Healthy() :
                HealthCheckResult.Unhealthy();
        }
    }
}

At this point, we can register it in our Startup.cs

[assembly: FunctionsStartup(typeof(Startup))]
namespace MyFunctionApp
{
    public class Startup : FunctionsStartup
    {
        public override void Configure(IFunctionsHostBuilder builder)
		{
			Services.AddHttpClient(); 
			Services.AddHttpClient("APIM", client =>
            {
                client.BaseAddress = new Uri(Environment.GetEnvironmentVariable("APIM_URL"));
            });			
			Services.AddHealthChecks()
			        .AddCheck("APIM");
		}
	}
}

Let’s investigate this situation. First, we’re ensuring that the IoC Container has access to the IHttpClientFactory. The next step is registering a named client and setting its APIM URI. We can also add further headers, such as a Subscription key for authentication and authorization.

We can begin registering healthchecks for all of our dependents, including our ApimHealthCheck, by calling AddHealthChecks().

Now, since we’re writing a Function App, we also have to create a Function to run the checks:

public class HealthFunctions
{
    private readonly HealthCheckService _healthService;
    public HealthFunctions(HealthCheckService healthService)
    {
        _healthService = healthService ?? throw new System.ArgumentNullException(nameof(healthService));
    }
    [FunctionName(nameof(Healthcheck))]
    public async Task Healthcheck(
        [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "health")]
        HttpRequest req)
    {
        var healthResult = await _healthService.CheckHealthAsync();
        var status = (healthResult.Status == HealthStatus.Healthy) ? 200 : 500;
        return new JsonResult(new
        {
            status = healthResult.Status.ToString(),
            entries = healthResult.Entries.Select(e => new
            {
                name = e.Key,
                status = e.Value.Status.ToString(),
                e.Value.Description,
                e.Value.Exception
            })
        })
        {
            StatusCode = status
        };
    }
}

When invoked, this will return a 200 or a 500 status with this payload:

{"status":"Healthy","entries":[{"name":"APIM","status":"Healthy","description":null,"exception":null}]}

API health check best practices

It’s crucial to check the health of your API constantly and to set up notifications if something is wrong. Here are some recommendations to assist you in keeping an eye on the health of your API.

Automate API health checks

Using a fault-tolerant API monitoring solution, you should automate all of your API health checks. Furthermore, it would help if you refrained from deploying your customized API monitoring system for API health checks. The danger of monitoring tool outages and bugs is reduced by using a dedicated API monitoring solution. For a list of various services for API monitoring, make sure to read our post on the top API monitoring solutions.

Check API health as frequently as possible

The health of your API should ideally be checked by your API health monitoring tool every minute. Is it excessive? No! What if an API health check was performed every hour? What would happen if your API went down after the most recent health check? You don’t realize your API is down for 60 minutes.

Disable Cache

Your API process must fulfil every request to your Restful or GraphQL (micro)service API health check endpoint. If your health endpoint’s caching is disabled, HTTP caching cannot fulfil the request. As a result, the most recent status of your microservice is returned for each request to the API health check endpoint.

Add Cache-Control: no-cache to your endpoint to turn off the cache.

Response Time Matters

The time it took for the endpoint to respond to the request is essential in addition to how quickly the API health check endpoint responded. For instance, if the endpoint replies after 30 seconds, there is a problem with the API.

It begins warning you if it takes longer than expected for your API to react.

JSON Response

Additional verification using API monitoring tools is possible when the health check result is returned in JSON format.

Response Status Code

Utilize the response status code and keep the monitoring tool well-informed about the outcome of the health check. 200 OK should be the result of a successful health check. To indicate a failure, use one of the other standard HTTP status codes, such as 500 Internal Error.

The general condition of your API should be reflected in the response status code.

Consider protecting your health check endpoint

Due to the lack of internal or sensitive information they convey, the majority of ping endpoints are accessible to the general public. A smart option is to secure this endpoint because, on the other hand, API health check endpoints reveal information about your service. Only ensure that your API monitoring software supports the delivery of API access keys.

Turbo360 handles the API monitoring challenges

To maximize the value of their data and services, businesses can publish APIs to external, partner, and internal developers with the help of API Management (APIM). Turbo360 is one platform to manage and monitor Azure Serverless components related to enterprise integration. Azure Portal is designed more on vertical technology silos, and it’s challenging to visualize and manage such connected solutions. Turbo360 is one tool you can depend on to manage and monitor all your distributed Azure Serverless components. In terms of API monitoring and management, it has been segregated into three main parts.

APIM API

An API Management service instance is built on APIs. Each API stands for a set of developer-accessible actions. Each API contains a reference to the back-end service that uses it, and each API’s activities are mapped to those of the back-end service.

It is vital to assess the dependability, effectiveness, and performance of the API Management APIs to integrate crucial business logic into a solution.

For every part within Turbo360, users are provided with an in-built Resource Dashboard for APIM API resources.

API health check best practices

  1. Unauthorized Requests
  2. Data Transfer
  3. Success Requests
  4. Failed Requests
  5. Request Summary
  6. Response Time Summary
  7. Service Time Summary
  8. Response Time Maximum vs. Minimum
  9. Cache Hit Vs. Miss
  10. Request Success Vs. Failure

The widgets were provided to stay on track, with the metric values for enhanced business performance.

Also, users can monitor their APIM API resources by configuring the metrics available for monitoring. Users can specify monitoring threshold values based on their needs.

Monitor APIM resources

APIM Operation

The actions taken by the back-end service are equivalent to the actions taken by the API.

Operation response caching, URL mapping, query and path parameters, request and response content, and API Management operations are all extremely customizable.

Policies for rate caps, quotas, and IP restrictions can also be implemented at the API or specific operation level.

Azure APIM health check

Likewise, of APIM API, we have a set of widgets that can be used for APIM Operation. Users can monitor their APIM Operation resources by configuring the metrics available for monitoring. Users can specify monitoring threshold values based on their needs. When the monitoring rule type is a metric, selecting metrics against metric rules is also an option.

Azure APIM health check

APIM Product

By way of goods, APIs are made accessible to developers. There may be one or more APIs in API Management solutions, and each is identified by its title, description, and terms of use.

Either open or closed products are possible. In contrast to available products, which can be used without a membership, protected items demand one.

An API key that can be used with any of the product’s APIs is given to the subscribed person. The process for manually or automatically approving subscriptions is configured at the product level.

Customers can use Turbo360 to perform actions such as publishing and unpublishing the APIM Product.

publishing and publishing APIM

Users can use the default dashboard for APIM Product resources to visualize the metric data for further reference with the set of 10 nos default widgets provided for the APIM Product.

Monitor APIM Product

Users can monitor their APIM Product resources by configuring the state and metrics available for monitoring by specifying threshold values based on their needs.

Monitor APIM Product

To attain more information, please refer to the article link here

Wrap Up

I hope this blog helps you understand the basic concepts of Azure API management health check, how to get Azure APIM health check & details, the challenges, and how to overcome those challenges. Within Turbo360, Azure API management health checks can be monitored and managed from various perspectives.

This article was originally published on Oct 28, 2022. It was most recently updated on Mar 4, 2024.

Related Articles