Search code examples
powershellpowershell-7.0

Powershell - Invoke-RestMethod - POST nested JSON


I'm trying to interact with an API to POST some data to a service we use, in order to add some email addresses to a policy. This will eventually take a list of email addresses and loop through it for each one, but for now I'm just trying to get it to work with a single address.

I'm using Powershell 7, I would say I'm intermediate with powershell, but this is my first foray into interacting with an API, using JSON, and using the Invoke-RESTMethod commandlet. The API reference for the service shows lots of code examples in other languages, just not PS!

Here's the problem I'm running in to. I'm trying to formulate a -Body statement that looks to be 3 elements instead of two. Here is what that example statement looks like in CURL:

{
  "custodians": [
    {
      "emailId": "[email protected]"
    }
  ],
  "action": "add"
}

The Action:Add part is fine, easy peasy. I'm trying to figure out how to correctly format the custodians part. I cant figure out how to do 3 elements instead of two. I've tried different combinations of {} [] and () to no avail:

"custodians" = ({"emailId" = "[email protected]"})

gives me an "The assignment expression is not valid" error

"custodians" = [{"emailId" = "[email protected]"}]

and

"custodians" = [@{"emailId" = "[email protected]"}]

give me an "Missing type name after '['." error.

These, as well as a few other combinations I've typed out, all showed formatting errors in VSCode so I already knew they wouldn't work, I'm just not sure why. I'm sure I just haven't cracked the right combination of @, {}, [] or () but I cant seem to find any info online (probably because I'm not using the right vocabulary or phrasing in my searches) that shows how to format with three elements.

If its relevant or helpful, here is a larger code sample of the whole query Im working on. Assume the Auth headers are fine (I can request my auth tokens and do GETs without issue so far):

$headers = @{
    "Authorization" = $bearerAuthValue
    "Accept" = "application/json"
    "Content Type" = "application/json"
} 

$body = @{
    "custodians" = @(emailId = "[email protected]"),
    "Action" = "add"
}
$uri = "https://thisisanaddress.com"
Invoke-RestMethod -Method 'POST' -Uri $uri -Headers $headers -Body $body

Solution

  • You are looking at having multiple emailids in custodians?

    $body = @{
        custodians = @(
            @{emailId = '[email protected]' }
            @{emailId = '[email protected]' }
            @{emailId = '[email protected]' }
        )
        Action = 'add'
    }
    

    Output:

    $body | ConvertTo-Json
    
    {
      "Action": "add",
      "custodians": [
        {
          "emailId": "[email protected]"
        },
        {
          "emailId": "[email protected]"
        },
        {
          "emailId": "[email protected]"
        }
      ]
    }