1

In PowerShell using Invoke-RestMetjhod to call different API´s I am stuck getting an InvalidOperation error when trying to pass both header and body information to the POST call.

My script is:

Set-StrictMode -Version Latest

$ApiToken = Get-Content ‘C:\APIEnergiNet\api_token.txt’
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("Authorization", "Bearer $ApiToken")

$response =   Invoke-RestMethod 'https://api.eloverblik.dk/customerapi/api/token' -Method 'GET' -Headers $headers

$GetMetringPointID = Invoke-RestMethod 'https://api.eloverblik.dk/customerapi/api/meteringpoints/meteringpoints?includeAll=true' -Headers @{ Authorization = "Bearer " + $response.result }



foreach($result in $GetMetringPointID){
    
    $CurrentMeteringID = $GetMetringPointID.result.meteringPointId

    foreach($Currentresult in $CurrentMeteringID){

        $MeterID = $Currentresult

        $GetCharges = Invoke-RestMethod 'https://api.eloverblik.dk/customerapi/api/MeteringPoints/MeteringPoint/GetCharges' -Method 'POST' -Headers @{ Authorization = "Bearer " + $response.result } -Body @{ meteringPoints = @( @{meteringPoint = "$Currentresult" } ) }

        $GetCharges

    }

}

The API needs the following sent in the body :

{
  "meteringPoints": {
    "meteringPoint": [
      "string"
    ]
  }
}

if I create variable $postParams containing the data like this:

        $postParams = @{
            meteringPoints = @(
                @{meteringPoint = "$MeterID" }
            )
        }
        
        $postParams

it returns:

meteringPoints {System.Collections.Hashtable}

The API has a swagger here https://api.eloverblik.dk/customerapi/index.html

Can anyone help me why I get this error and how to fix it?

Best Regards

Stig :-)

UPDATE WITH LATEST CODE BELOW:

Set-StrictMode -Version Latest

$ApiToken = Get-Content ‘C:\APIEnergiNet\api_token.txt’
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("Authorization", "Bearer $ApiToken")

$response =   Invoke-RestMethod 'https://api.eloverblik.dk/customerapi/api/token' -Method 'GET' -Headers $headers

$GetMetringPointID = Invoke-RestMethod 'https://api.eloverblik.dk/customerapi/api/meteringpoints/meteringpoints?includeAll=true' -Headers @{ Authorization = "Bearer " + $response.result }




foreach ($result in $GetMetringPointID)
{
    
    $CurrentMeteringID = $GetMetringPointID.result.meteringPointId
    
    foreach ($Currentresult in $CurrentMeteringID)
    {
        
        $MeterID = $Currentresult
        
        $postParams = @{
            meteringPoints = @(
                @{ meteringPoint = "$MeterID" }
            )
        } | ConvertTo-Json
        
        
        $resultlist = Invoke-RestMethod 'https://api.eloverblik.dk/customerapi/api/MeteringPoints/MeteringPoint/GetCharges' -Method 'POST' -ContentType 'application/json' -Headers @{ Authorization = "Bearer " + $response.result } -Body @{ $postParams }


$resultlist

    }

}

ERROR I NOW GET:

ParserError: C:\APIEnergiNet\api.ps1:31:245
Line |
  31 |  … Authorization = "Bearer " + $response.result } -Body @{ $postParams }
     |                                                                       ~
     | Missing '=' operator after key in hash literal.
StigK
  • 11
  • 3
  • 1
    You need to add `-ContentType 'application/json'` as a parameter in the `Invoke-restmethod` command. Also, Please forcefully convert the body to json using `convertto-json` before passing it as a parameter. – Ranadip Dutta Jan 02 '23 at 12:22
  • Hi @RanadipDutta thank you for your comment :-) .. ´convertto-json´ at the `$postParams` solve the format of JSON, but when adding `-ContentType 'application/json'` I get ParserError with Missing '=' operator after key in hash literal. .. it points to end of this line ´… horization = "Bearer " + $response.result } } -Body @{ $postParams }´ – StigK Jan 02 '23 at 13:39
  • `@{ ... }` looks like you will send body as an hashtable, whereas a string value is awaited. Did you try with `-Body $postParams` instead? – PJProudhon Jan 02 '23 at 14:48
  • 1
    @StigK: Kindly edit the question and update the new code along with the error message. So that we can debug further. – Ranadip Dutta Jan 02 '23 at 16:17
  • @RanadipDutta I have made section with UPDATE WITH LATEST CODE BELOW and error below that – StigK Jan 03 '23 at 09:21
  • @PJProudhon if I only set `-Body $postParams` I get the following error `Response status code does not indicate success: 400 (Bad request). InvalidOperation: ` – StigK Jan 03 '23 at 09:30
  • @StigK would you try to reproduce with a tool like [Postman](https://www.postman.com/downloads/)? A 400 can have many different causes. You're at least pretty sure the body is properly sent now ;-) – PJProudhon Jan 03 '23 at 10:22

1 Answers1

1

I've made this little PS for you based on yours

$Path              = "C:\EnergiNet\"
$TokenFile         = $Path + "token.txt"
$JSON_ResponseFile = $Path + "Response.json"
$XML_ResponseFile  = $Path + "Response.xml"
$ApiToken          = Get-Content $TokenFile

# Get Auth token #
$response =   Invoke-RestMethod 'https://api.eloverblik.dk/customerapi/api/token' -Method 'GET' -Headers @{ Authorization = "Bearer " + $ApiToken }

$Auth_Token = $response.result

$body = '{ "meteringPoints": {"meteringPoint": ["571313174xxxxxxxxxxx","571313174xxxxxxxxxxx","571313174xxxxxxxxxxx"] }}'

$headers = @{
    'Authorization' = "Bearer " + $response.result
    'Accept' = 'application/json'
}

Invoke-RestMethod 'https://api.eloverblik.dk/customerapi/api/meterdata/gettimeseries/2023-01-01/2023-02-01/Quarter' -Method 'POST' -ContentType 'application/json' -Headers $headers -Body $body | ConvertTo-Json -Depth 100 | out-file $JSON_ResponseFile

$headers = @{
    'Authorization' = "Bearer " + $response.result
    'Accept' = 'application/xml'
}
(Invoke-RestMethod 'https://api.eloverblik.dk/customerapi/api/meterdata/gettimeseries/2023-01-01/2023-02-01/Quarter' -Method 'POST' -ContentType 'application/json' -Headers $headers -Body $body).outerXml | out-file $XML_ResponseFile
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Feb 14 '23 at 00:31