PowerShell and REST APIs: consume and automate external services
João Barros
24 de July de 2025
1 min read
PowerShell is a first-class HTTP client with Invoke-RestMethod and Invoke-WebRequest. Combined with its native ability to handle JSON and XML, it is ideal for integrating external APIs into automations without extra code.
OAuth2 authentication (Client Credentials)
# Get an access token (Azure AD / Entra ID)
$body = @{
grant_type = "client_credentials"
client_id = $env:APP_CLIENT_ID
client_secret = $env:APP_CLIENT_SECRET
scope = "https://graph.microsoft.com/.default"
}
$tokenResponse = Invoke-RestMethod `
-Method POST `
-Uri "https://login.microsoftonline.com/$env:TENANT_ID/oauth2/v2.0/token" `
-ContentType "application/x-www-form-urlencoded" `
-Body $body
$token = $tokenResponse.access_token
GET with authentication headers
# Reusable headers
$headers = @{
Authorization = "Bearer $token"
"Content-Type" = "application/json"
}
# GET call
$users = Invoke-RestMethod `
-Method GET `
-Uri "https://graph.microsoft.com/v1.0/users" `
-Headers $headers
$users.value | Select-Object displayName, mail | Format-Table
Automatic pagination
# Collect all result pages
$url = "https://graph.microsoft.com/v1.0/users?$top=100"
$results = @()
do {
$response = Invoke-RestMethod -Uri $url -Headers $headers -Method GET
$results += $response.value
$url = $response."@odata.nextLink"
} while ($url)
Write-Output "Total users: $($results.Count)"
POST — create resources via API
# Create a group via the Graph API
$body = @{
displayName = "Analytics Team"
mailEnabled = $false
securityEnabled = $true
mailNickname = "analytics-team"
} | ConvertTo-Json
Invoke-RestMethod `
-Method POST `
-Uri "https://graph.microsoft.com/v1.0/groups" `
-Headers $headers `
-Body $body
Conclusion
PowerShell + Invoke-RestMethod covers 95% of integrations with modern APIs. For enterprise automations that combine M365, Azure and external systems with no dedicated SDK, it is the fastest to implement and easiest to maintain.