Working with APIs

The Report That Automated Itself

I used to spend 2 hours every Monday morning generating a deployment report: log into Azure DevOps, click through 15 project pipelines, copy data to Excel, calculate statistics, email the team. Every. Single. Monday.

One weekend, I discovered Azure DevOps has a REST API:

$org = "mycompany"
$project = "MainApp"
$pat = $env:AZDO_PAT

$headers = @{
    Authorization = "Basic $([Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(":$pat")))"
}

$builds = Invoke-RestMethod -Uri "https://dev.azure.com/$org/$project/_apis/build/builds?api-version=7.0" -Headers $headers

$builds.value | Select-Object id, buildNumber, status, result | Export-Csv "builds.csv"

Two hours became 30 seconds. That script still runs every Monday, automatically.

Invoke-RestMethod: Your API Swiss Army Knife

Invoke-RestMethod calls REST APIs and automatically parses responses.

Basic GET Request

HTTP Methods

Authentication

Bearer Token

Basic Authentication

API Key

Working with JSON

Parsing JSON Responses

Sending JSON Data

Nested JSON

Real-World API Examples

GitHub API Integration

Azure DevOps API

REST API with Pagination

POST with File Upload

Invoke-WebRequest: When You Need More Control

For scenarios requiring full HTTP response details:

Downloading Files

Error Handling for API Calls

Rate Limiting

Real-World Integration: Automated Monitoring

Common Pitfalls

1. Not Handling Rate Limits

Problem: API blocks after too many requests Solution: Implement retry logic with delays

2. Hardcoded Credentials

Problem: Security risk Solution: Use environment variables or secure storage

3. Not Checking HTTP Status Codes

Problem: Assuming success Solution: Check status and handle errors

Key Takeaways

  • Invoke-RestMethod: Automatic JSON parsing

  • Invoke-WebRequest: Full HTTP response control

  • Authentication: Bearer, Basic, API Keys

  • Error handling: Retry logic for reliability

  • Rate limiting: Respect API limits

  • Security: Never hardcode credentials

What You've Learned

βœ… Making REST API calls with PowerShell βœ… Authentication methods (Bearer, Basic, API Key) βœ… Working with JSON data βœ… Error handling and retry logic βœ… Real-world API integrations βœ… Rate limiting and best practices

Next Steps

You can now integrate with any API. Let's focus on cloud automation. In PowerShell for Azure, you'll learn:

  • Az PowerShell module

  • Managing Azure resources

  • Azure automation patterns

  • Cost optimization scripts

Bring your PowerShell skills to the cloud.


Ready for Azure? Continue to PowerShell for Azure β†’

Last updated