r/PowerShell • u/Khue • Jul 01 '26
Solved Invoke-RestMethod: Problem with Body Variable Format
I am trying to convert a curl command to PoSh's Invoke-RestMethod. I typically don't have a problem with this but today, I seem to be having an issue. Curl command looks like this:
curl https://api.domain.com/stuff/thing/items \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '[
{ "key1": "value1", "key2": "value2" },
{ "key1": "value3", "key2": "value4" }
]'
To start off and make things easy, I was simply trying to do a single json entry.
$body = @"
{
"key1": "value1",
"key2": "value2"
}
"@ | convertto-json
Using that format I then passed it into invoke-restmethod:
Invoke-RestMethod -Uri "https://api.domain.com/stuff/thing/items" -Method post -Headers $headers -body $body
Which then spit back:
Invoke-RestMethod:
{
"result": null,
"success": false,
"errors": [
{
"code": 10026,
"message": "filters.api.invalid_json"
}
],
"messages": []
}
I tried a few different versions of this as well without too much luck. This is the first time I've had to submit an actual key value combination to this particular API using JSON. The only other body format example I have for this particular vendor's APIs in JSON format is this:
$body = @{
value = @(
"value1",
"value2",
"value3",
"value4"
)
} | ConvertTo-Json
This particular endpoint didn't require a key value pair. It only required a list of strings.
Update:
Credit to /u/y_Sensei . What ended up working was this:
Single key value pair:
$body = @'
[
{
"key1": "value1",
"key2": "value2"
}
]
'@
Multi key value pair:
$body = @'
[
{
"key1": "value1",
"key2": "value2"
},
{
"key1: "value3",
"key2: "value4"
}
]
'@
Thank you to all contributors! I appreciate it!
View all comments
Show parent comment
1
u/Over_Dingo Jul 03 '26
These were escape characters. You were converting a singular object that was a string literal, that happenned to look like json. Try chaining convertto-json in the pipeline to see an abomination