(+351) 21 24 10006  ·  info@bconcepts.pt
Carnaxide, Lisboa
PowerShell
PowerShell 1 min

PowerShell e APIs REST: consumir e automatizar serviços externos

João Barros 24 de July de 2025 1 min de leitura

O PowerShell é um cliente HTTP de primeira classe com Invoke-RestMethod e Invoke-WebRequest. Combinado com a capacidade de manipular JSON e XML nativamente, é ideal para integrar APIs externas em automações sem código adicional.

Autenticação OAuth2 (Client Credentials)

# Obter token de acesso (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 com headers de autenticação

# Headers reutilizáveis
$headers = @{
    Authorization  = "Bearer $token"
    "Content-Type" = "application/json"
}

# Chamada GET
$users = Invoke-RestMethod `
    -Method GET `
    -Uri "https://graph.microsoft.com/v1.0/users" `
    -Headers $headers

$users.value | Select-Object displayName, mail | Format-Table

Paginação automática

# Colectar todas as páginas de resultados
$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 utilizadores: $($results.Count)"

POST — criar recursos via API

# Criar grupo via Graph API
$body = @{
    displayName     = "Equipa Analytics"
    mailEnabled     = $false
    securityEnabled = $true
    mailNickname    = "equipa-analytics"
} | ConvertTo-Json

Invoke-RestMethod `
    -Method POST `
    -Uri "https://graph.microsoft.com/v1.0/groups" `
    -Headers $headers `
    -Body $body

Conclusão

PowerShell + Invoke-RestMethod cobre 95% das integrações com APIs modernas. Para automações empresariais que combinam M365, Azure e sistemas externos sem SDK dedicado, é a ferramenta mais rápida de implementar e mais fácil de manter.

Partilhar: