Working with REST APIs in PowerShell
Interacting with REST APIs is a core capability of PowerShell, allowing you to automate services like GitHub, Azure, AWS, and many others.
Parent Topic: PowerShell Scripting and Programming Related: PowerShell Comprehensive Guide
1. The Cmdlets: Invoke-RestMethod vs. Invoke-WebRequest
Invoke-RestMethod(IRM): The go-to cmdlet for REST APIs. It automatically parses JSON or XML responses into PowerShell objects.Invoke-WebRequest(IWR): Returns the raw HTTP response (headers, status code, raw content). Use this if you need to inspect headers or scrape HTML.
2. Basic GET Requests
Fetching data is straightforward.
# Get public data
$response = Invoke-RestMethod -Uri "https://api.github.com/users/octocat"
# Access properties directly
Write-Host "User: $($response.login)"
Write-Host "Bio: $($response.bio)"
3. POST Requests (Sending Data)
To create or update resources, you typically use POST or PUT methods and send a JSON body.
$body = @{
title = "My New Issue"
body = "This is a test issue created via PowerShell."
} | ConvertTo-Json
$params = @{
Uri = "https://api.github.com/repos/owner/repo/issues"
Method = "Post"
Body = $body
ContentType = "application/json"
Headers = @{ Authorization = "Bearer YOUR_TOKEN" }
}
# Splatting makes the command cleaner
Invoke-RestMethod @params
4. Authentication
Most APIs require authentication headers.
Bearer Token (OAuth/JWT)
$headers = @{
Authorization = "Bearer eyJhbGciOi..."
}
Invoke-RestMethod -Uri $uri -Headers $headers
Basic Authentication
# Automatic encoding
$credential = Get-Credential
Invoke-RestMethod -Uri $uri -Credential $credential -Authentication Basic
5. Handling Errors
API calls can fail (404, 500, etc.). Use try-catch to handle them gracefully.
try {
Invoke-RestMethod -Uri "https://api.example.com/missing" -ErrorAction Stop
}
catch {
# The exception object contains the response details
$statusCode = $_.Exception.Response.StatusCode.value__
# Reading the error body stream
$errorBody = $_.Exception.Response.GetResponseStream()
$reader = [System.IO.StreamReader]::new($errorBody)
$details = $reader.ReadToEnd()
Write-Error "API Call Failed [$statusCode]: $details"
}
Return to PowerShell Scripting and Programming