Using the Azure Cost Management API to Cut Your Cloud Costs

Microsoft Azure is the world’s second-largest cloud provider, offering extensive capabilities to provision and manage enterprise workloads. With Azure services, you pay for what you use, which is convenient but also makes it difficult to plan, budget, and forecast the cost of cloud services used by an organization.

Without proper analytics and monitoring, Azure cost management becomes a major challenge. Like all cloud providers, Azure users face the risk of waste and inefficiency, as a result of the highly dynamic nature and limited visibility of the cloud environment.

To address these challenges, Microsoft provides Cost Management + Billing, a free set of tools that helps analyze, manage, and optimize the cost of workloads in Azure. At a basic level, these tools let you retrieve information about Azure invoices, manage billing information across a large organization with multiple projects or business units, and download actual cost and usage data.

Beyond this, Azure Cost Management + Billing performs data analytics on your costs to identify trends, let you set spending thresholds, notify you about anomalies, and provide recommendations for workload changes that can optimize spending (for example, identifying VMs that are not in use and shutting them down).

Azure Cost Management API

The Azure Cost Management API lets you retrieve and work with Azure cost and usage data programmatically. You can create custom filters and expressions to answer questions related to Azure resource consumption. Note that the API is currently only available to Azure Enterprise customers.

The Cost Management API provides three groups of operations:

  • Dimensions — retrieving data for supported dimensions for use in combination with scopes (a scope is a group of Azure resources). These dimensions can be used for Query or Exports operations.
  • Query — retrieving aggregated cost and usage data based on a specific query. Data can be filtered, sorted, and grouped by any available dimension.
  • Exports — enables scheduling export of cost and usage data to blob storage. Data can be filtered, sorted, and grouped by any dimension before exporting.

Azure Retail Prices API

The Retail Prices API lets you programmatically retrieve current prices for all Azure services. This is important for many use cases such as capacity planning, cloud deployment planning, purchasing reserved or spot instances, and building your own cost analysis or management tools.

The Retail Prices API is not authenticated, allowing anyone to receive free data on Azure services with any combination of region and SKU (item for sale). In the following sections, I’ll describe the basic usage of the Cost Management API and Azure Retail Prices API.

Using Azure Cost Management API

The Azure Cost Management API has rich functionality, allowing you to retrieve and explore costs with multidimensional analysis and custom queries and filters. To provide a taste of the API, I’ll show how to perform three basic operations:

  • Forecasting — projecting estimated costs for a selected time period to the next period.
  • Retrieving reservation details — getting the current status of an Azure reservation (long-term commitment to Azure resources in exchange for a discount).
  • Retrieving alerts — getting alerts generated by Azure Cost Management based on user definitions in the Azure Portal.

The code in the following sections is taken from the official API documentation.

Forecast

The forecast operation lets you define a scope and a selected period and show a projection of estimated costs for that period based on historical trends. If there is a budget defined for the relevant scope, this operation will also show when the forecasted spending is likely to exceed the budget. Forecasting can project costs up to a year in the future.

POST API Endpoint

Here and in the following sections, the {scope} defines the Microsoft subscription or billing entity that the operation pertains to.

https://management.azure.com/{scope}/providers/Microsoft.CostManagement/forecast?api-version=2021-10-01

Sample Request

The request only specifies the scope. The details of the forecast operation are in the request body.

POST https://management.azure.com/providers/Microsoft.Billing/billingAccounts/87966:3543/providers/Microsoft.CostManagement/forecast?api-version=2021-10-01

Request Body

In the example below, we request a forecast based on cost data in the past month, filtering according to the following criteria:

  • Resources are located in East US or Western Europe
  • Resources have one of the tags UAT or Prod
  • Resources are in the Azure Resource Group API

Note the two parameters at the end, which indicate whether to return the actual costs in the defined period together with the forecast.

{
  "type": "Usage",
  "timeframe": "MonthToDate",
  "dataset": {
    "granularity": "Daily",
    "filter": {
      "and": [
        {
          "or": [
            {
              "dimensions": {
                "name": "ResourceLocation",
                "operator": "In",
                "values": [
                  "East US",
                  "West Europe"
                ]
              }
            },
            {
              "tags": {
                "name": "Environment",
                "operator": "In",
                "values": [
                  "UAT",
                  "Prod"
                ]
              }
            }
          ]
        },
        {
          "dimensions": {
            "name": "ResourceGroup",
            "operator": "In",
            "values": [
              "API"
            ]
          }
        }
      ]
    }
  },
  "includeActualCost": false,
  "includeFreshPartialCost": false
}

Response

In the response, the id, name, and type fields are general identifiers, and the properties field provides a URL that lets you skip to the next page of results.

The columns field provides the actual forecast data, showing the expected cost of the filtered resources in the next month.

{
  "id": ... ,
  "name": ...,
  "type": ...,
  "properties": {
    "nextLink": "https://management.azure.com/providers/Microsoft.Billing/billingAccounts/12345:6789/providers/Microsoft.CostManagement/Forecast?api-version=2021-10-01&$skiptoken=AQAAAA%3D%3D",
    "columns": [
      {
        "name": "PreTaxCost",
        "type": "Number"
      },
      {
        "name": "UsageDate",
        "type": "Number"
      },
      {
        "name": "CostStatus",
        "type": "String"
      },
      {
        "name": "Currency",
        "type": "String"
      }
    ],
    "rows": [
      [
        2.10333307059661,
        20220331,
        "Forecast",
        "USD"
      ],
      [
        218.68795741935486,
        20220331,
        "Forecast",
        "USD"
      ],
      [
        0.14384913581657052,
        20220401,
        "Forecast",
        "USD"
      ],
      [
        0.0098655868513236322,
        20220429,
        "Forecast",
        "USD"
      ]
    ]
  }
}

Reservation Details Report

You can use the API to get details about Azure Reservations, which represent a commitment of 1 or 3 years to use Azure resources, in exchange for a discount of up to 72%. In large Azure deployments, there can be many reservations, and it can be helpful to programmatically retrieve their status to evaluate how to best use reserved resources.

POST API Endpoint

This endpoint generates a reservations details report for a given billing account ID and specified date range.

https://management.azure.com/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/providers/Microsoft.CostManagement/generateReservationDetailsReport?startDate={startDate}&endDate={endDate}&api-version=2021-10-01

Sample Request

POST https://management.azure.com/providers/Microsoft.Billing/billingAccounts/8679287/providers/Microsoft.CostManagement/generateReservationDetailsReport?startDate=2020-01-01&endDate=2020-01-30&api-version=2021-10-01

Response

The response provides a URL to the report in XML format.

{
  "status": "Completed",
  "properties": {
    "reportUrl": "https://storage.blob.core.windows.net/details/20200911/00000000-0000-0000-0000-000000000000?sv=2016-05-31&sr=b&sig=jep8HT2aphfUkyERRZa5LRfd9RPzjXbzB%2F9TNiQ",
    "validUntil": "2020-09-12T02:56:55.5021869Z"
  }
}

Alerts

Users of Azure Cost Management can define budget alerts to be notified when usage or cost reaches or exceeds the budget set for that resource. Alerts can also be defined via the Azure Consumption API.

Budget alerts can be based on a cost or usage budget — in other words, an alert is created either when the cost or the usage exceeds the budgeted amount. When alerts are generated, they are shown in the cost alert section of the Azure portal and sent by email to the budget recipient list. You can also use the API endpoint below to retrieve details of new alerts.

GET API Endpoint

This API endpoint retrieves an alert for a defined scope and alert ID:

https://management.azure.com/{scope}/providers/Microsoft.CostManagement/alerts/{alertId}?api-version=2021-10-01

Sample Request

The following request retrieves the details of a specific alert with ID 222….

GET https://management.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/ScreenSharingTest-peer/providers/Microsoft.CostManagement/alerts/22222222-2222-2222-2222-222222222222?api-version=2021-10-01

Sample Response

The response provides the full details of the alert, including:

  • Type of budget
  • Reason for the alert
  • Time period
  • Alert condition
  • Threshold
  • Current spend
{
  "id": "subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/ScreenSharingTest-peer/providers/Microsoft.CostManagement/alerts/22222222-2222-2222-2222-222222222222",
  "name": "22222222-2222-2222-2222-222222222222",
  "type": "Microsoft.CostManagement/alerts",
  "properties": {
    "definition": {
      "type": "Budget",
      "category": "Cost",
      "criteria": "CostThresholdExceeded"
    },
    "description": "",
    "source": "Preset",
    "details": {
      "timeGrainType": "Quarterly",
      "periodStartDate": "2020-03-01T00:00:00Z",
      "triggeredBy": "22222222-2222-2222-2222-222222222222_1_01",
      "resourceGroupFilter": [],
      "resourceFilter": [],
      "meterFilter": [],
      "tagFilter": {},
      "threshold": 0.8,
      "operator": "GreaterThan",
      "amount": 200000,
      "unit": "USD",
      "currentSpend": 161000.12,
      "contactEmails": [
        "1234@contoso.com"
      ],
      "contactGroups": [],
      "contactRoles": [],
      "overridingAlert": null
    },
    "costEntityId": "budget1",
    "status": "Active",
    "creationTime": "2020-04-27T11:07:52.7143901Z",
    "closeTime": "0001-01-01T00:00:00",
    "modificationTime": "2020-04-28T11:06:02.8999373Z",
    "statusModificationUserName": null,
    "statusModificationTime": "0001-01-01T00:00:00"
  }
}

See more options for retrieving and defining alerts via the API here.

Using the Azure Retail Prices API

The Azure Retail Prices API lets you retrieve raw pricing data for Azure services. The following filters are supported, allowing you to specify the Azure services for which you need pricing information:

  • armRegionName—Azure region
  • Location—Availability Zone
  • meterId/meterName—ID and name for the meter reporting the charge
  • productid—official Azure product ID
  • skuId—official ID for the Azure SKU
  • productName—official Azure product name
  • skuName—official name for Azure SKU
  • serviceName—official name for Azure service
  • serviceId—official ID for the service
  • serviceFamily—official name of service family
  • priceType—Azure pricing model
  • armSkuName—name of the resource used in Azure Resource Manager (ARM)

GET API Endpoint

The endpoint provides pricing data based on a number of filters.

https://prices.azure.com/api/retail/prices?$filter={selected-filter} eq '{value}'

Examples of Usage

Viewing prices for all virtual machines:

https://prices.azure.com/api/retail/prices?$filter=serviceName eq 'Virtual Machines'

Viewing prices for computing resources:

https://prices.azure.com/api/retail/prices?$filter=serviceFamily eq 'Compute'

Viewing prices for computing resources with currency in Euro:

https://prices.azure.com/api/retail/prices?currencyCode='EUR'&$filter=serviceFamily eq 'Compute'

Sample Response

The following is an example response showing the price for one Azure product: Virtual Machines FS Series Windows. The response lists all the relevant IDs, service, product, and SKU name, and the current price.

{
  "currencyCode": "EUR",
  "tierMinimumUnits": 0,
  "retailPrice": 0.6176,
  "unitPrice": 0.6176,
  "armRegionName": "westeurope",
  "location": "EU West",
  "effectiveStartDate": "2021-04-01T00:00:00Z",
  "meterId": "000a794b-bdb0-58be-a0cd-0c3a0f222923",
  "meterName": "F16s Spot",
  "productId": "DZH318Z0BQPS",
  "skuId": "DZH318Z0BQPS/00TG",
  "productName": "Virtual Machines FS Series Windows",
  "skuName": "F16s Spot",
  "serviceName": "Virtual Machines",
  "serviceId": "DZH313Z7MMC8",
  "serviceFamily": "Compute",
  "unitOfMeasure": "1 Hour",
  "type": "Consumption",
  "isPrimaryMeterRegion": true,
  "armSkuName": "Standard_F16s"
}

Conclusion

In this article, I explained the basics of two Azure cost APIs: the Azure Cost Management API and the Azure Retail Prices API. Both APIs provide broad functionality, but I covered some of the most important functions. Here is how each of these functions can help you reduce Azure cloud costs:

  • Forecasting: You provide a scope (Microsoft subscription or billing entity) and a forecast period, and the API returns expected future cost data. This can help you reduce costs by identifying resources that are expected to have high spending and help to optimize or downsize them.
  • Reservation details: You provide a billing account ID and date range, and the API returns details about all active reservations. This can help reduce Azure costs by identifying currently reserved resources and making optimal use of them instead of starting unneeded, higher-cost on-demand resources.
  • Alerts: You can use the API to define alerts on budget events (such as resources exceeding their budget) and also to view current alerts. I showed how to retrieve current alerts for a certain scope. This can help you reduce cloud costs by integrating Azure alerts with internal systems to make staff aware of budget outages.
  • Retrieving retail pricing: I showed a few examples for retrieving current retail pricing for Azure services, including VMs, compute resources, and currency conversion. This can reduce Azure costs by querying retail prices on a regular basis to identify low-cost resource opportunities.

I hope this will be useful as you integrate with Azure’s native cost management solution to automate and improve cloud cost optimization.