how to get the cost of the whole subscription using azure rest api calls?

procomix 20 Reputation points
2023-06-06T07:39:30.2966667+00:00

Dears,

I want to get the cost of a subscription for the last month. can it be done using rest api calls?

thank you,

Azure Cost Management
Azure Cost Management
A Microsoft offering that enables tracking of cloud usage and expenditures for Azure and other cloud providers.
3,642 questions
{count} votes

2 answers

Sort by: Most helpful
  1. SadiqhAhmed-MSFT 49,331 Reputation points Microsoft Employee Moderator
    2023-06-06T08:25:25.7566667+00:00

    Hello @procomix Thank you for reaching out to us on Microsoft Q&A platform. Happy to help!

    I see that you want to get the cost of the subscription using REST API's. You can fetch subscription cost using Azure Cost Management API, you can use the following API endpoint:

    GET https://<span class=" active-doc-0 active-doc-1 active-doc-4" data-doc-items="0,1,4">management.azure.com/{scope}/providers/Microsoft.CostManagement/query?api-version=2019-11-01&$top=100&$skip=0[1](#doc-pos=0)[2](#doc-pos=1)[3](#doc-pos=4)</span>
    

    Here, you need to replace {scope} with the scope of your subscription, such as /subscriptions/{subscriptionID}. You can also add filters to the query to retrieve specific data**4**.

    For example, to retrieve the cost of a subscription for the last month, you can use the following query:

    POST https://<span class=" active-doc-0 active-doc-1 active-doc-4" data-doc-items="0,1,4">management.azure.com/{scope}/providers/Microsoft.CostManagement/query?api-version=2019-11-01[1](#doc-pos=0)[2](#doc-pos=1)[3](#doc-pos=4)</span>
    
    {
      "type": "Usage",
      "timeframe": "MonthToDate",
      "dataset": {
        "granularity": "Daily",
        "aggregation": {
          "totalCost": {
            "name": "PreTaxCost",
            "function": "Sum"
          }
        },
        "grouping": [
          {
            "type": "Dimension",
            "name": "ResourceId"
          }
        ]
      }
    }
    

    This will return the total cost of the subscription for the current month, grouped by resource ID. You can modify the query to retrieve data for a different timeframe or to group the data differently.

    Hope this helps. Please tag me in your reply if you need further assistance!


    If the response helped, do "Accept Answer" and up-vote it

    0 comments No comments

  2. procomix 20 Reputation points
    2023-06-06T12:33:28.4166667+00:00

    I tried the second post command it was successful, however, the first get request wasn't successful. I think it is outdated. Moreover, is there any other command to get the cost of a subscription directly rather than getting all the resources, and add them to get the cost?


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.