I need to interact with a REST API which requires JSON post data. So I started working with something like this:
$ReqURI = 'http://httpbin.org/post'
Invoke-WebRequest -Method Post -Uri $ReqURI -Body @{
'api.token' = "api.token"
'action' = 'create item'
} -Verbose| fl *
So I tested it with httpbin.org:
But If you need to use a list or array in the body part like this example:
$ReqURI = 'http://httpbin.org/post'
$Response = Invoke-RestMethod -Method Post -Uri $ReqURI -Body @{
'api.token' = "api.token"
'names' = @('rJENK', 'rFOOBAR')
} -Verbose| fl *
$Response
... you get something like a converting error:
So I thought I could convert the body myself into a JSON string and using the -Depth
parameter from ConvertTo-JSON
. In addition to that I tried how it looks like if I convert the hashtable into an object first.
But both tries return the same and even worse result:
So finally I switched to Invoke-WebRequest
. But the results here are the same.
My reference is a working api call with the JSON string:
"api.token" : "fooobar",
"names": [
"rJENK",
"rFOOBAR"
]
I figured out a workaround. It seems like the api I'm working with can't handle requests containing nested elements or array created by PowerShell.
Non working example:
$ReqURI = 'http://httpbin.org/post'
$Response = Invoke-RestMethod -Method Post -Uri $ReqURI -Body @{
'api.token' = "api.token"
'names' = @('rJENK', 'rFOOBAR')
} -Verbose| fl *
$Response
Instead I had to fake an array with indexes. That's the workaround:
$ReqURI = 'http://httpbin.org/post'
$Response = Invoke-RestMethod -Method Post -Uri $ReqURI -Body @{
'api.token' = "api.token"
'names[0]' = 'rJENK'
'names[1]' = 'rFOOBAR'
} -Verbose| fl *
$Response
Arrays in JSON are almost the same as arrays in JavaScript. In JSON, array values must be of type string, number, object, array, boolean or null. In JavaScript, array values can be all of the above, plus any other valid JavaScript expression, including functions, dates, and undefined.
' { } ' used for Object and ' [] ' is used for Array in json.
A JSON array contains zero, one, or more ordered elements, separated by a comma. The JSON array is surrounded by square brackets [ ] . A JSON array is zero terminated, the first index of the array is zero (0). Therefore, the last index of the array is length - 1.
JSON Syntax An object is a set of name-value pairs, and an array is a list of values. JSON defines seven value types: string, number, object, array, true, false, and null.
So now you have to use the content type as Application/Json like:
$ReqURI = 'http://httpbin.org/post'
$Jsonbody= @{
'api.token' = "api.token"
'names' = @('rJENK', 'rFOOBAR')
} | ConvertTo-Json
$Response = Invoke-RestMethod -Method Post -ContentType 'application/json' -Uri $ReqURI -Body $body -Verbose| fl *
This should do your work. Hope it helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With