Skip to content
AgileLogics
6 min read

Calling REST APIs

Prerequisites: Working with JSON, try, catch, and finally

Invoke-RestMethod calls a web API and converts the JSON (or XML) response into objects automatically.

GET requests

# illustrative
$repo = Invoke-RestMethod -Uri 'https://api.github.com/repos/PowerShell/PowerShell'
$repo.full_name
$repo.stargazers_count
$repo.license.name
PowerShell/PowerShell
48912
MIT License

No parsing step — the response is already an object.

Query parameters and headers

# illustrative
$headers = @{
  Authorization = "Bearer $env:GITHUB_TOKEN"
  Accept        = 'application/vnd.github+json'
}
$params = @{
  Uri     = 'https://api.github.com/search/repositories?q=language:powershell&sort=stars&per_page=5'
  Headers = $headers
}
(Invoke-RestMethod @params).items | Select-Object name, stargazers_count

Read tokens from environment variables or a secret vault — never paste them into scripts.

Sending data

# illustrative
$body = @{ title = 'Build failed'; priority = 'high' } | ConvertTo-Json
Invoke-RestMethod -Uri 'https://api.example.com/tickets' -Method Post `
  -Body $body -ContentType 'application/json'

-Method accepts Get, Post, Put, Patch, and Delete. (The backtick at the end of a line continues the command — splatting is usually cleaner.)

Handling errors

# illustrative
try {
  Invoke-RestMethod -Uri 'https://api.github.com/repos/nobody/nothing' -ErrorAction Stop
} catch {
  $status = $_.Exception.Response.StatusCode.value__
  "Request failed with HTTP $status"
}
Request failed with HTTP 404

PowerShell 7 adds useful options: -StatusCodeVariable to capture the status without try, -SkipHttpErrorCheck to handle error responses yourself, and -MaximumRetryCount / -RetryIntervalSec for retries.

Invoke-WebRequest

Invoke-WebRequest returns the raw response — status code, headers, and content — for downloading files or when you need headers:

# illustrative
Invoke-WebRequest -Uri 'https://example.com/report.pdf' -OutFile report.pdf
(Invoke-WebRequest -Uri 'https://example.com').StatusCode

Encode or decode payloads with the Base64 Encoder when an API needs it.