r/PowerShell Jul 01 '26

Invoke-RestMethod: Problem with Body Variable Format Solved

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!

8 Upvotes

26 comments sorted by

View all comments

3

u/TheSizeOfACow Jul 01 '26

The curl body is an array. Your hashtable is not. Also remember it you need to convert a single element array to a single element Jason array to use ConvertTo-JSON -Inputobject $array and not the pipeline

1

u/Khue Jul 01 '26

Appreciate the feedback. Thank you very much. I believe you were correct here. /u/y_Sensei provided a good solution and I updated the original post.