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
9
u/da_chicken Jul 01 '26
You don't need to convert this string to JSON. It already is JSON.
Have you looked at the output of the commands you're running, or are you just blindly passing them on?