REST API in PowerShell

When working in PowerShell under windows, naively you do not have curl. And if you are looking to work with REST most of the examples are created for use with curl.
Luckily PowerShell has integrated command called Invoke-RestMethod.
Here are few examples that cover the basics.
Simple GET example

$response = Invoke-RestMethod 'http://example.com/api/data'

GET with custom headers

$message = 'Message'
$secret = 'secret'
$hmacsha = New-Object System.Security.Cryptography.HMACSHA256
$hmacsha.key = [Text.Encoding]::UTF8.GetBytes($secret)
$signature = $hmacsha.ComputeHash([Text.Encoding]::UTF8.GetBytes($message))
$encb64=[System.Convert]::ToBase64String($signature)
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("X-DATE", '9/29/2019')
$headers.Add("X-SIGNATURE", $encb64)
$headers.Add("X-API-KEY", 'testuser')

$response = Invoke-RestMethod 'http://example.com/api/data/1' -Headers $headers

PUT/POST example

$person = @{
    first='joe'
    lastname='doe'
}
$json = $person | ConvertTo-Json
$response = Invoke-RestMethod 'http://example.com/api/data/1' -Method Put -Body $json -ContentType 'application/json'

DELETE example

$response = Invoke-RestMethod 'http://example.com/api/data/1' -Method Delete

The documentation is extensive and available here: Invoke-RestMethod.

If you have found a spelling error, please, notify us by selecting that text and pressing Ctrl+Enter.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.