How to make a web request using a JSON Body containing arrays or lists?

Situation

I need to interact with a REST API that requires Post JSON data. So I started working with something like this:

Simple working example

$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:

Working

Problem

But if you need to use a list or array in the main part, as in 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 related to a conversion error:

Conversion problem

So, I thought that I could convert the body to a JSON string and use the parameter -Depthfrom ConvertTo-JSON. In addition to this, I tried what it looks like if I first convert the hash table into an object.

But both attempts return the same and even worse result:

does not work

So, I switched to Invoke-WebRequest. But the results here are the same.

My link is an api working call with a JSON string:

"api.token" : "fooobar",
"names": [
    "rJENK",
    "rFOOBAR"
  ]

. , api, , , , Powershell.

:

$ReqURI = 'http://httpbin.org/post'
$Response = Invoke-RestMethod -Method Post -Uri $ReqURI -Body @{
    'api.token' = "api.token"
    'names' = @('rJENK', 'rFOOBAR')
} -Verbose| fl *
$Response

. :

$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
+4
1

, Application/Json:

$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 *

. , .

+3

Source: https://habr.com/ru/post/1667647/


All Articles