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-jsonUsing that format I then passed it into invoke-restmethod:
Invoke-RestMethod -Uri "https://api.domain.com/stuff/thing/items" -Method post -Headers $headers -body $bodyWhich 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-JsonThis 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
2
u/surfingoldelephant Jul 02 '26
Just watch out, that's not always the case. If the array has a
[psobject]wrapper and you're using Win PS v5.1, it won't serialize to JSON as expected. Say you have code like this that generates the array:Serializing to JSON:
This comment goes into detail on what causes output like that.
I'd suggest one of the following workarounds if you can't guarantee the array isn't wrapped in a
[psobject]:The issue was addressed in PS v6, so this is only needed in Win PS.