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.
# 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.'
$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
1. Which cmdlet automatically parses a JSON API response into a PowerShell object?
2. What is the recommended way to store an API token used in a PowerShell script?
3. How does GitHub's REST API commonly signal that more pages of results are available?
4. In PowerShell 7+, what happens by default when Invoke-RestMethod receives a 404 response?
5. Which parameter would you use to attach a custom Authorization header to a REST call?
Was this page helpful?
You May Also Like
PowerShell for Azure
Use the Az PowerShell module to authenticate, provision, and automate Azure resources at scale.
Modules and the PowerShell Gallery
Learn how PowerShell packages reusable code into modules and how to discover, install, and publish them via the PowerShell Gallery.
Managing Active Directory with PowerShell
Use the ActiveDirectory module to query, create, and modify users, groups, and organizational units at scale.
Related Reading
Related Study Notes in Programming
Browse all study notesApache Spark Study Notes
Programming · 30 topics
ProgrammingApache Flink Study Notes
Programming · 30 topics
ProgrammingHadoop Study Notes
Programming · 30 topics
ProgrammingSnowflake Study Notes
Programming · 30 topics
ProgrammingApache Airflow Study Notes
Programming · 30 topics
Programmingdbt (Data Build Tool) Study Notes
Programming · 30 topics