100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
Programming

PowerShell and REST APIs

Use Invoke-RestMethod and Invoke-WebRequest to consume, authenticate against, and automate workflows around HTTP REST APIs.

Practical PowerShellIntermediate10 min readJul 10, 2026
Analogies

Calling REST Endpoints with Invoke-RestMethod

Invoke-RestMethod is PowerShell's primary cmdlet for calling REST APIs; it automatically parses JSON or XML responses into native PowerShell objects, so you can pipe the result straight into Where-Object, Select-Object, or Format-Table without manual deserialization. This differs from Invoke-WebRequest, which returns the raw HTTP response including headers, status code, and unparsed content, useful when you need to inspect response metadata rather than just the body. Both cmdlets accept -Method, -Headers, -Body, and -ContentType to fully control the outgoing request.

🏏

Cricket analogy: Invoke-RestMethod is like a scorer's app that ingests raw ball-by-ball feed data and instantly renders it as a formatted scorecard, versus Invoke-WebRequest which is like getting the raw umpire's signal log you'd have to interpret yourself.

powershell
# GET request returning parsed JSON as PSCustomObject
$repo = Invoke-RestMethod -Uri 'https://api.github.com/repos/PowerShell/PowerShell' -Method Get
$repo.stargazers_count

# POST with a JSON body
$body = @{ name = 'demo-issue'; body = 'Created via PowerShell' } | ConvertTo-Json
Invoke-RestMethod -Uri 'https://api.example.com/issues' -Method Post `
  -Body $body -ContentType 'application/json' -Headers @{ Authorization = "Bearer $token" }

Authentication Patterns

Most REST APIs require authentication via an Authorization header, commonly a Bearer token for OAuth2/API-key schemes or Basic auth encoded as base64 username:password. PowerShell lets you build the -Headers hashtable manually, or for Basic auth you can pass a PSCredential to the -Credential parameter alongside -Authentication Basic (in PowerShell 6+/7). For token-based flows like Azure AD or GitHub personal access tokens, it's best practice to store secrets in a SecretManagement vault or environment variable rather than hardcoding them in scripts.

🏏

Cricket analogy: Bearer token auth is like a match official's accreditation lanyard scanned at the stadium gate every time — no lanyard, no access to the dressing room, exactly like a missing Authorization header returning a 401.

Use the Microsoft.PowerShell.SecretManagement and SecretStore modules to store API tokens securely and retrieve them with Get-Secret, instead of embedding credentials as plaintext strings in scripts.

Handling Pagination, Errors, and Rate Limits

Many REST APIs paginate large result sets using a Link header (like GitHub's API) or a next-page token embedded in the response body. Since Invoke-RestMethod doesn't auto-follow pagination, you typically loop, extracting the next URL from response headers via -ResponseHeadersVariable or from a cursor field in the JSON body, until no further page is returned. For errors, a non-2xx status code throws a terminating error in PowerShell 7+, which you should catch with try/catch and inspect via $_.Exception.Response.StatusCode; well-behaved scripts also respect rate-limit headers like X-RateLimit-Remaining and back off with Start-Sleep when close to the limit.

🏏

Cricket analogy: Paginating API results is like requesting a bowling analysis one over at a time from a scorer instead of the entire innings dump, looping until the scorer says 'no more overs bowled.'

powershell
$uri = 'https://api.github.com/repos/PowerShell/PowerShell/issues?per_page=100'
$allIssues = @()
do {
    $response = Invoke-WebRequest -Uri $uri -Headers @{ Authorization = "Bearer $token" }
    $allIssues += $response.Content | ConvertFrom-Json
    $linkHeader = $response.Headers['Link']
    $uri = if ($linkHeader -match '<([^>]+)>;\s*rel="next"') { $matches[1] } else { $null }
} while ($uri)

try {
    Invoke-RestMethod -Uri 'https://api.example.com/data' -Method Get
} catch {
    Write-Warning "Request failed: $($_.Exception.Response.StatusCode) - $($_.ErrorDetails.Message)"
}

In Windows PowerShell 5.1, Invoke-RestMethod does not throw a terminating error for HTTP error codes the same way PowerShell 7 does by default — always test error handling on the actual PowerShell version your script targets.

  • Invoke-RestMethod auto-parses JSON/XML into PowerShell objects; Invoke-WebRequest returns the raw response for header/status inspection.
  • Use -Method, -Headers, -Body, and -ContentType to fully shape outgoing requests.
  • Authorization headers (Bearer tokens, Basic auth) are the standard way to authenticate REST calls.
  • Store API secrets in SecretManagement/SecretStore rather than hardcoding them in scripts.
  • Pagination requires manually looping using Link headers or cursor tokens since PowerShell doesn't auto-follow pages.
  • Wrap REST calls in try/catch and inspect $_.Exception.Response.StatusCode for error handling.
  • Respect rate-limit headers and back off with Start-Sleep to avoid throttling.

Practice what you learned

Was this page helpful?

Topics covered

#Programming#PowerShellStudyNotes#PowerShellAndRESTAPIs#PowerShell#REST#APIs#Calling#StudyNotes#SkillVeris#ExamPrep