REST API в PowerShell

Когато работим с PowerShell в Windows по подразбиране няма curl.А ако работим с REST повечето примери използват curl.
За щастие в PowerShell има командата Invoke-RestMethod.
Ето няколко примера
Упростен пример за GET

$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

$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

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

Официалната документация е тук Invoke-RestMethod.

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

Вашият коментар

Този сайт използва Akismet за намаляване на спама. Научете как се обработват данните ви за коментари.