Azure monitoring REST API walkthrough - Azure Monitor (2023)

  • Article
  • 8 minutes to read

This article shows you how to use the Azure Monitor REST API reference.

Retrieve metric definitions, dimension values, and metric values using the Azure Monitor API and use the data in your applications, or store in a database for analysis. You can also list alert rules and view activity logs using the Azure Monitor API.

Authenticate Azure Monitor requests

Request submitted using the Azure Monitor API use the Azure Resource Manager authentication model. All requests are authenticated with Azure Active Directory. One approach to authenticating the client application is to create an Azure Active Directory service principal and retrieve an authentication token. You can create an Azure Active Directory service principal using the Azure portal, CLI, or PowerShell. For more information, see Register an App to request authorization tokens and work with APIs

Retrieve a token

Once you've created a service principal, retrieve an access token using a REST call. Submit the following request using the appId and password for your service principal or app:

 POST /<appId>/oauth2/v2.0/token Host: https://login.microsoftonline.com Content-Type: application/x-www-form-urlencoded grant_type=client_credentials &client_id=<app-client-id> &resource=https://management.azure.com &client_secret=<password>

For example

curl --location --request POST 'https://login.microsoftonline.com/a1234bcd-5849-4a5d-a2eb-5267eae1bbc7/oauth2/token' \--header 'Content-Type: application/x-www-form-urlencoded' \--data-urlencode 'grant_type=client_credentials' \--data-urlencode 'client_id=0a123b56-c987-1234-abcd-1a2b3c4d5e6f' \--data-urlencode 'client_secret123456.ABCDE.~XYZ876123ABceDb0000' \--data-urlencode 'resource=https://management.azure.com'

A successful request receives an access token in the response:

{ token_type": "Bearer", "expires_in": "86399", "ext_expires_in": "86399", "access_token": ""eyJ0eXAiOiJKV1QiLCJ.....Ax"}

After authenticating and retrieving a token, use the access token in your Azure Monitor API requests by including the header 'Authorization: Bearer <access token>'

Note

For more information on working with the Azure REST API, see the Azure REST API reference.

(Video) Azure Monitor | What is Azure Monitor | Azure Monitor Tutorial | Azure Monitoring Tutorial

Retrieve metric definitions

Use the Azure Monitor Metric Definitions REST API to access the list of metrics that are available for a service.Use the following request format to retrieve metric definitions.

GET /subscriptions/<subscription id>/resourcegroups/<resourceGroupName>/providers/<resourceProviderNamespace>/<resourceType>/<resourceName>/providers/microsoft.insights/metricDefinitions?api-version=<apiVersion>Host: management.azure.comContent-Type: application/jsonAuthorization: Bearer <access token>

For example, The following request retrieves the metric definitions for an Azure Storage account

curl --location --request GET 'https://management.azure.com/subscriptions/12345678-abcd-98765432-abcdef012345/resourceGroups/azmon-rest-api-walkthrough/providers/Microsoft.Storage/storageAccounts/ContosoStorage/providers/microsoft.insights/metricDefinitions?api-version=2018-01-01'--header 'Authorization: Bearer eyJ0eXAiOi...xYz

The following JSON shows an example response body.In this example, only the second metric has dimensions.

{ "value": [ { "id": "/subscriptions/12345678-abcd-98765432-abcdef012345/resourceGroups/azmon-rest-api-walkthrough/providers/Microsoft.Storage/storageAccounts/ContosoStorage/providers/microsoft.insights/metricdefinitions/UsedCapacity", "resourceId": "/subscriptions/12345678-abcd-98765432-abcdef012345/resourceGroups/azmon-rest-api-walkthrough/providers/Microsoft.Storage/storageAccounts/ContosoStorage", "namespace": "Microsoft.Storage/storageAccounts", "category": "Capacity", "name": { "value": "UsedCapacity", "localizedValue": "Used capacity" }, "isDimensionRequired": false, "unit": "Bytes", "primaryAggregationType": "Average", "supportedAggregationTypes": [ "Total", "Average", "Minimum", "Maximum" ], "metricAvailabilities": [ { "timeGrain": "PT1H", "retention": "P93D" }, ... { "timeGrain": "PT12H", "retention": "P93D" }, { "timeGrain": "P1D", "retention": "P93D" } ] }, { "id": "/subscriptions/12345678-abcd-98765432-abcdef012345/resourceGroups/azmon-rest-api-walkthrough/providers/Microsoft.Storage/storageAccounts/ContosoStorage/providers/microsoft.insights/metricdefinitions/Transactions", "resourceId": "/subscriptions/12345678-abcd-98765432-abcdef012345/resourceGroups/azmon-rest-api-walkthrough/providers/Microsoft.Storage/storageAccounts/ContosoStorage", "namespace": "Microsoft.Storage/storageAccounts", "category": "Transaction", "name": { "value": "Transactions", "localizedValue": "Transactions" }, "isDimensionRequired": false, "unit": "Count", "primaryAggregationType": "Total", "supportedAggregationTypes": [ "Total" ], "metricAvailabilities": [ { "timeGrain": "PT1M", "retention": "P93D" }, { "timeGrain": "PT5M", "retention": "P93D" }, ... { "timeGrain": "PT30M", "retention": "P93D" }, { "timeGrain": "PT1H", "retention": "P93D" }, ... { "timeGrain": "P1D", "retention": "P93D" } ], "dimensions": [ { "value": "ResponseType", "localizedValue": "Response type" }, { "value": "GeoType", "localizedValue": "Geo type" }, { "value": "ApiName", "localizedValue": "API name" } ] }, ... ]}

Note

We recommend using API version "2018-01-01" or later. Older versions of the metric definitions API don't support dimensions.

Retrieve dimension values

After the retrieving the available metric definitions, retrieve the range of values for the metric's dimensions. Use dimension values to filter or segment the metrics in your queries. Use the Azure Monitor Metrics REST API to find all of the values for a given metric dimension.

Use the metric's name.value element in the filter definitions. If no filters are specified, the default metric is returned. The API only allows one dimension to have a wildcard filter.Specify the request for dimension values using the "resultType=metadata" query parameter. The resultType is omitted for a metric values request.

(Video) What is Azure Monitor?

Note

To retrieve dimension values by using the Azure Monitor REST API, use the API version "2019-07-01" or later.

Use the following request format to retrieve dimension values.

GET /subscriptions/<subscription-id>/resourceGroups/ <resource-group-name>/providers/<resource-provider-namespace>/ <resource-type>/<resource-name>/providers/microsoft.insights/ metrics?metricnames=<metric> &timespan=<starttime/endtime> &$filter=<filter> &resultType=metadata &api-version=<apiVersion> HTTP/1.1Host: management.azure.comContent-Type: application/jsonAuthorization: Bearer <access token>

The following example retrieves the list of dimension values that were emitted for the API Name dimension of the Transactions metric, where the GeoType dimension has a value of Primary, for the specified time range.

curl --location --request GET 'https://management.azure.com/subscriptions/12345678-abcd-98765432-abcdef012345/resourceGroups/azmon-rest-api-walkthrough/providers/Microsoft.Storage/storageAccounts/ContosoStorage/providers/microsoft.insights/metrics \?metricnames=Transactions \&timespan=2023-03-01T00:00:00Z/2023-03-02T00:00:00Z \&resultType=metadata \&$filter=GeoType eq \'Primary\' and ApiName eq \'*\' \&api-version=2019-07-01'-header 'Content-Type: application/json' \--header 'Authorization: Bearer eyJ0e..meG1lWm9Y'

The following JSON shows an example response body.

{ "timespan": "2023-03-01T00:00:00Z/2023-03-02T00:00:00Z", "value": [ { "id": "/subscriptions/12345678-abcd-98765432-abcdef012345/resourceGroups/azmon-rest-api-walkthrough/providers/Microsoft.Storage/storageAccounts/ContosoStorage/providers/Microsoft.Insights/metrics/Transactions", "type": "Microsoft.Insights/metrics", "name": { "value": "Transactions", "localizedValue": "Transactions" }, "unit": "Count", "timeseries": [ { "metadatavalues": [ { "name": { "value": "apiname", "localizedValue": "apiname" }, "value": "DeleteBlob" } ] }, { "metadatavalues": [ { "name": { "value": "apiname", "localizedValue": "apiname" }, "value": "SetBlobProperties" } ] }, ... ] } ], "namespace": "Microsoft.Storage/storageAccounts", "resourceregion": "eastus"}

Retrieve metric values

After retrieving the metric definitions and dimension values, retrieve the metric values. Use the Azure Monitor Metrics REST API to retrieve the metric values.

Use the metric's name.value element in the filter definitions. If no dimension filters are specified, the rolled up, aggregated metric is returned.

To fetch multiple time series with specific dimension values, specify a filter query parameter that specifies both dimension values such as "&$filter=ApiName eq 'ListContainers' or ApiName eq 'GetBlobServiceProperties'".

To return a time series for every value of a given dimension, use an * filter such as "&$filter=ApiName eq '*'". The Top and OrderBy query parameters can be used to limit and order the number of time series returned.

(Video) Complete Azure Monitor explained with overview in 20 Minutes

Note

To retrieve multi-dimensional metric values using the Azure Monitor REST API, use the API version "2019-07-01" or later.

Use the following request format to retrieve metric values.

GET /subscriptions/<subscription-id>/resourceGroups/<resource-group-name>/providers/<resource-provider-namespace>/<resource-type>/<resource-name>/providers/microsoft.insights/metrics?metricnames=<metric>&timespan=<starttime/endtime>&$filter=<filter>&interval=<timeGrain>&aggregation=<aggreation>&api-version=<apiVersion>Host: management.azure.comContent-Type: application/jsonAuthorization: Bearer <access token>

The following example retrieves the top three APIs, by the number of Transactions in descending value order, during a 5-minute range, where the GeoType dimension has a value of Primary.

curl --location --request GET 'https://management.azure.com/subscriptions/12345678-abcd-98765432-abcdef012345/resourceGroups/azmon-rest-api-walkthrough/providers/Microsoft.Storage/storageAccounts/ContosoStorage/providers/microsoft.insights/metrics \?metricnames=Transactions \&timespan=2023-03-01T02:00:00Z/2023-03-01T02:05:00Z \& $filter=apiname eq '\''GetBlobProperties'\'&interval=PT1M \&aggregation=Total \&top=3 \&orderby=Total desc \&api-version=2019-07-01"' \--header 'Content-Type: application/json' \--header 'Authorization: Bearer yJ0eXAiOi...g1dCI6Ii1LS'

The following JSON shows an example response body.

{ "cost": 0, "timespan": "2023-03-01T02:00:00Z/2023-03-01T02:05:00Z", "interval": "PT1M", "value": [ { "id": "/subscriptions/12345678-abcd-98765432-abcdef012345/resourceGroups/azmon-rest-api-walkthrough/providers/Microsoft.Storage/storageAccounts/ContosoStorage/providers/Microsoft.Insights/metrics/Transactions", "type": "Microsoft.Insights/metrics", "name": { "value": "Transactions", "localizedValue": "Transactions" }, "unit": "Count", "timeseries": [ { "metadatavalues": [ { "name": { "value": "apiname", "localizedValue": "apiname" }, "value": "GetBlobProperties" } ], "data": [ { "timeStamp": "2023-09-19T02:00:00Z", "total": 2 }, { "timeStamp": "2023-09-19T02:01:00Z", "total": 1 }, { "timeStamp": "2023-09-19T02:02:00Z", "total": 3 }, { "timeStamp": "2023-09-19T02:03:00Z", "total": 7 }, { "timeStamp": "2023-09-19T02:04:00Z", "total": 2 } ] }, ... ] } ], "namespace": "Microsoft.Storage/storageAccounts", "resourceregion": "eastus"}

Retrieve the resource ID

Using the REST API requires the resource ID of the target Azure resource.Resource IDs follow the following pattern:

/subscriptions/<subscription-id>/resourceGroups/<resource-group-name>/providers/<provider>/<resource name>/

For example

  • Azure IoT Hub: /subscriptions/<subscription-id>/resourceGroups/<resource-group-name>/providers/Microsoft.Devices/IotHubs/<iot-hub-name>
  • Elastic SQL pool: /subscriptions/<subscription-id>/resourceGroups/<resource-group-name>/providers/Microsoft.Sql/servers/<pool-db>/elasticpools/<sql-pool-name>
  • Azure SQL Database (v12): /subscriptions/<subscription-id>/resourceGroups/<resource-group-name>/providers/Microsoft.Sql/servers/<server-name>/databases/<database-name>
  • Azure Service Bus: /subscriptions/<subscription-id>/resourceGroups/<resource-group-name>/providers/Microsoft.ServiceBus/<namespace>/<servicebus-name>
  • Azure Virtual Machine Scale Sets: /subscriptions/<subscription-id>/resourceGroups/<resource-group-name>/providers/Microsoft.Compute/virtualMachineScaleSets/<vm-name>
  • Azure Virtual Machines: /subscriptions/<subscription-id>/resourceGroups/<resource-group-name>/providers/Microsoft.Compute/virtualMachines/<vm-name>
  • Azure Event Hubs: /subscriptions/<subscription-id>/resourceGroups/<resource-group-name>/providers/Microsoft.EventHub/namespaces/<eventhub-namespace>

Use the Azure portal, PowerShell or the Azure CLI to find the resource ID.

(Video) Learn Live - Azure Monitoring

  • Azure portal
  • PowerShell
  • Azure CLI

To find the resourceID in the portal, from the resource's overview page, select JSON viewAzure monitoring REST API walkthrough - Azure Monitor (1)

The Resource JSON page is displayed. The resource ID can be copied using the icon on the right of the ID

Azure monitoring REST API walkthrough - Azure Monitor (2)

Retrieve activity log data

Use the Azure Monitor REST API to query activity log data.

Use the following request format for activity log queries.

GET /subscriptions/<subscriptionId>/providers/Microsoft.Insights/eventtypes/management/values \?api-version=2015-04-01 \&$filter=<filter> \&$select=<select>host: management.azure.com

$filter reduces the set of data collected.This argument is required and it also requires at least the start date/time.The $filter argument accepts the following patterns:

  • List events for a resource group: $filter=eventTimestamp ge '2014-07-16T04:36:37.6407898Z' and eventTimestamp le '2014-07-20T04:36:37.6407898Z' and resourceGroupName eq 'resourceGroupName'.
  • List events for resource: $filter=eventTimestamp ge '2014-07-16T04:36:37.6407898Z' and eventTimestamp le '2014-07-20T04:36:37.6407898Z' and resourceUri eq 'resourceURI'.
  • List events for a subscription in a time range: $filter=eventTimestamp ge '2014-07-16T04:36:37.6407898Z' and eventTimestamp le '2014-07-20T04:36:37.6407898Z'.
  • List events for a resource provider: $filter=eventTimestamp ge '2014-07-16T04:36:37.6407898Z' and eventTimestamp le '2014-07-20T04:36:37.6407898Z' and resourceProvider eq 'resourceProviderName'.
  • List events for a correlation ID: $filter=eventTimestamp ge '2014-07-16T04:36:37.6407898Z' and eventTimestamp le '2014-07-20T04:36:37.6407898Z' and correlationId eq 'correlationID'.

$select is used to fetch a specified list of properties for the returned events.The $select argument is a comma separated list of property names to be returned.Valid values are:authorization, claims, correlationId, description, eventDataId, eventName, eventTimestamp, httpRequest, level, operationId, operationName, properties, resourceGroupName, resourceProviderName, resourceId, status, submissionTimestamp, subStatus, and subscriptionId.

The following sample requests use the Azure Monitor REST API to query an activity log.

Get activity logs with filter:

The following example gets the activity logs for resource group "MSSupportGroup" between the dates 2023-03-21T20:00:00Z and 2023-03-24T20:00:00Z

(Video) Azure Application Insights Tutorial | Amazing telemetry service

GET https://management.azure.com/subscriptions/12345678-abcd-98765432-abcdef012345/providers/microsoft.insights/eventtypes/management/values?api-version=2015-04-01&$filter=eventTimestamp ge '2023-03-21T20:00:00Z' and eventTimestamp le '2023-03-24T20:00:00Z' and resourceGroupName eq 'MSSupportGroup'

Get activity logs with filter and select:

The following example gets the activity logs for resource group "MSSupportGroup", between the dates 2023-03-21T20:00:00Z and 2023-03-24T20:00:00Z, returning the elements eventName,operationName,status,eventTimestamp,correlationId,submissionTimestamp, and level

GET https://management.azure.com/subscriptions/12345678-abcd-98765432-abcdef012345/providers/microsoft.insights/eventtypes/management/values?api-version=2015-04-01&$filter=eventTimestamp ge '2023-03-21T20:00:00Z' and eventTimestamp le '2023-03-24T20:00:00Z'and resourceGroupName eq 'MSSupportGroup'&$select=eventName,operationName,status,eventTimestamp,correlationId,submissionTimestamp,level

Troubleshooting

You may receive one of the following HTTP error statuses:

  • 429 Too Many Requests
  • 503 Service Unavailable
  • 504 Gateway Timeout

If one of these statuses is returned, resend the request.

Next steps

  • Review the overview of monitoring.
  • View the supported metrics with Azure Monitor.
  • Review the Microsoft Azure Monitor REST API reference.
  • Review the Azure Management Library.

Videos

1. Monitor the health of your Azure virtual machine by using Azure Metrics Explorer and metric alerts
(Ed Goad)
2. Microsoft Azure Monitor Agent and Data Collection Rule Overview
(John Savill's Technical Training)
3. Azure Monitoring and Alerting with Service-Now integration using LogicApps: Step-by-Step Tutorial
(Practice Cloud)
4. Azure Monitor Logs Log Types
(John Savill's Technical Training)
5. DEMO Azure Insights Monitoring VM, VM ScaleSets
(Paddy Maddy)
6. How to Monitor the Published APIs in Azure API Management Instance
(asar cloud Chef)
Top Articles
Latest Posts
Article information

Author: Nicola Considine CPA

Last Updated: 04/20/2023

Views: 6145

Rating: 4.9 / 5 (49 voted)

Reviews: 88% of readers found this page helpful

Author information

Name: Nicola Considine CPA

Birthday: 1993-02-26

Address: 3809 Clinton Inlet, East Aleisha, UT 46318-2392

Phone: +2681424145499

Job: Government Technician

Hobby: Calligraphy, Lego building, Worldbuilding, Shooting, Bird watching, Shopping, Cooking

Introduction: My name is Nicola Considine CPA, I am a determined, witty, powerful, brainy, open, smiling, proud person who loves writing and wants to share my knowledge and understanding with you.