REST API call returning bad request in powershell but it works in the API help page

112 Views Asked by At

I'm trying to make a REST call through powershell but I'm getting "error 400 bad request". I'm importing a JSON file using ConvertFrom-Json then inputting it into the body of the call via ConvertTo-Json. The weird part is that if I take just $json | ConvertTo-Json -Depth 3 and copy the output to the API page it works no problem so it appears to be formatted correctly. Any ideas what might be causing this?

I removed the username, passsword, and API key for security reasons but I know that those are correct. I've been able to get pretty much this exact block of code working except instead of inputting the body via ConvertTo-Json I manually entered the parameters in there.

$username = "UserName"
$password = ConvertTo-SecureString "Password" -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential($username, $password)
$headers = @{
    "accept" = "application/json"
    "X-API-Key" = "API-KEY"
    }
$response = Invoke-RestMethod -Uri "URI"`
    -Method Post `
    -Credential $credential `
    -Headers $headers `
    -ContentType "application/json" `
    -Body $json | ConvertTo-Json -Depth 3
   }
1

There are 1 best solutions below

0
On BEST ANSWER

Nevermind I figured it out. I needed to convert the entire JSON to a string for the body of the REST call. The snippet below ended up working for me.

$body = $json | ConvertTo-Json -Depth 3
$username = "USERNAME"
$password = ConvertTo-SecureString "PASSWORD" -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential($username, $password)
$headers = @{
    "accept" = "application/json"
    "X-API-Key" = "API KEY"
    }
$response = Invoke-RestMethod -Uri "URI"`
    -Method Post `
    -Credential $credential `
    -Headers $headers `
    -ContentType "application/json" `
    -Body $body.ToString()
   }