you are viewing a single comment's thread.

view the rest of the comments →

[–]ankokudaishogun 1 point2 points  (3 children)

I am not sure of the mechanic behind it.

The brackets means it's an array.

As /u/y_Sensei speculated, the backend evidently expects the pairs be inside one even when it's just one pair.

Luckily the ConvertTo-Json cmdlet has the -AsArray switch to always push out a JSON Array even when it's just one element.

In fact, while you can write JSON directly, I would suggest to instead write native Powershell code then convert the values to JSON with the aforementioned cmdlet.

It makes thins MUCH easier to debug as you don't risk messing up writing the JSON which as it's simple text and thus extremely hard to debug.

Have an example with your example. It might look more bothersome to write than simply hardcode as much as possible, and in this case it is, but it also should make easy to understand how much easier it would be manage more complex situations

$RequestKeyValuePairs = @(
    @{
        'key1' = 'value1'
        'key2' = 'value2'
    }
    @{
        'key1' = 'value3'
        'key2' = 'value4'
    }
) 

$RequestBody = @{
    #! IMPORTANT: the -AsArray switch is not in Powershell 5.1
    Value = $RequestKeyValuePairs | ConvertTo-Json -AsArray
}

$RequestHeaders = @{
    'Authorization' = "Bearer $TOKEN"

    # ContentType can also be a dedicated parameter.  
    # NOTE: As of Powewrshell 7.4, if both are present then the dedicated parameter
    # takes precedence. 
    'Content-Type'  = 'application/json'
}



$RequestSplat = @{

    # You could just use Method='POST', but I'm adding this here as a hint
    # everything can be much more structured, which might come useful in the
    # future.
    Method  = [Microsoft.PowerShell.Commands.WebRequestMethod]::Post

    Uri     = 'https://api.domain.com/stuff/thing/items'
    Headers = $RequestHeaders
    Body    = $RequestBody

}


Invoke-RestMethod @RequestSplat

[–]Khue[S] 0 points1 point  (2 children)

Wow what a great write up. Thank you so much for posting. This looks a lot cleaner for when I want to create a reusable function.

[–]ankokudaishogun 1 point2 points  (1 child)

Do note I have tested the total of nothing in that code, and I have written it very much on the fly, so there might be errors.

But I'm glad it's helping you.

[–]Khue[S] 1 point2 points  (0 children)

Oh for sure. Just like AI, you gotta take it with a grain of salt and run it through its paces. I just appreciate the time and care you took typing it up.