Using POST method in REST API in PowerShell

In one of previous blog post, we discussed how to work with using REST APIs in PowerShell. In this blog post, we’ll discuss how to use POST method in REST API.

POST involve sending both a body and headers.

  $person = @{
   $body = (ConvertTo-Json $person)
   $hdrs = @{}
   Invoke-RestMethod -Uri $url -Method Post -Body $body -ContentType 'application/json' -Headers $hdrs

The above on several lines is easier to read than one long line:

$hdrs = @{"X-API-KEY"='???'; "X-SIGNATURE"='234j123l4kl23j41l23k4j'; X-DATE"='12/29/2016'"}

The power of Powershell lies in the helpers cmdlets available and how it can fluidly turn input into objects, and then to manipulate those objects in a granular way like by using ConvertTo-Json cmdlet.

The API-KEY is obtained from the service’s website during sign-up.

Do note that if -ContentType ‘application/json is not added to REST calls, an error message is likely because when POST is specified, Invoke-RestMethod sets the content type to “application/x-www-form-urlencoded” for sending out forms, not REST calls.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s