Home > front end >  Getting 'Bad Request' and 'Invalid query definition' when calling Azure REST API
Getting 'Bad Request' and 'Invalid query definition' when calling Azure REST API

Time:05-13

I'm trying to call an Azure REST API endpoint to get information my daily usage cost.

I'm using Powershell 7.2 and here's my code:

$uri = 'https://management.azure.com/subscriptions/{subscription id}/providers/Microsoft.CostManagement/query?api-version=2021-10-01'
$token = '{generated bearer token string}'
$securetoken = ConvertTo-SecureString $token -AsPlainText -Force

$body = @{
    type = 'Usage'
    timeframe = 'MonthToDate'
    dataset = @{
        granularity = 'Daily'
        aggregation = @{
            totalCost = @{
                name = 'PreTaxCost'
                function = 'Sum'
            }
        }
        grouping = @(
            @{
                type = 'Dimension'
                name = 'ServiceName'
            }
        )
        
    }
}

$costresponse = Invoke-WebRequest -Uri $uri -Method Post -Authentication Bearer -Token $securetoken -Body $body
Write-Host $costresponse

Here's the request body example from the Microsoft documentation I'm trying to emulate:

{
  "type": "Usage",
  "timeframe": "TheLastMonth",
  "dataset": {
    "granularity": "None",
    "aggregation": {
      "totalCost": {
        "name": "PreTaxCost",
        "function": "Sum"
      }
    },
    "grouping": [
      {
        "type": "Dimension",
        "name": "ResourceGroup"
      }
    ]
  }
}

When I run the code I get this error message:

Line |
  27 |  … tresponse = Invoke-WebRequest -Uri $uri -Method Post -Authentication  …
     |                ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     | {"error":{"code":"BadRequest","message":"Invalid query definition: Missing dataset granularity; valid
     | values: 'Daily'.\r\n\r\n (Request ID: c6ead005-85b3-4ebe-9b46-........)"}}

I think the error has to do with the body syntax but I can't figure out what is the issue. I'm following this Microsoft documentation: https://docs.microsoft.com/en-us/rest/api/cost-management/query/usage

EDIT: I tried converting the body to JSON and adding a depth parameter like this:

$costresponse = Invoke-WebRequest -Uri $uri -Method Post -Authentication Bearer -Token $securetoken -Body ($body|ConvertTo-Json -Depth 5)

And now I get a slightly different error message:

Line |
  26 |  … tresponse = Invoke-WebRequest -Uri $uri -Method Post -Authentication  …
     |                ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     | {"error":{"code":"BadRequest","message":"Invalid query definition, Dataset is invalid or not supplied.
     | (Request ID: cf6a4b8f-88e8-4037-aa33-904......)"}}

CodePudding user response:

I needed to add -ContentType 'application/json' to my Invoke-WebRequest function to get it to work. Thanks to @bluuf for the suggestion.

  • Related