REST API Calls
PowerShell provides robust tools for interacting with RESTful APIs through Invoke-RestMethod and Invoke-WebRequest. These cmdlets enable you to send HTTP requests (GET, POST, PUT, DELETE, etc.) to web services, parse responses, and integrate with enterprise systems like cloud platforms, custom APIs, or third-party services. This section covers core concepts and practical examples for making REST API calls.
Choosing Between Invoke-RestMethod and Invoke-WebRequest¶
-
Invoke-RestMethod
Simplifies working with JSON-based APIs. It automatically serializes/deserializes data and handles common HTTP methods. Best for straightforward REST interactions.
Example:
-
Invoke-WebRequest
Offers finer control over raw HTTP requests and responses. Useful for non-JSON payloads, custom headers, or advanced scenarios like file uploads.
Example:
Core Concepts: HTTP Verbs and Parameters¶
| Verb | Purpose | Example Command |
|---|---|---|
GET |
Retrieve data | Invoke-RestMethod -Uri "https://api.example.com/users" -Method Get |
POST |
Create a resource | Invoke-RestMethod -Uri "https://api.example.com/users" -Method Post -Body $userData |
PUT |
Update a resource | Invoke-RestMethod -Uri "https://api.example.com/users/123" -Method Put -Body $userData |
DELETE |
Remove a resource | Invoke-Rest,Method -Uri "https://api.example.com/users/123" -Method Delete |
Key Parameters:
- -Uri: Target API endpoint.
- -Method: HTTP verb (Get, Post, etc.).
- -Headers: Add custom headers (e.g., for authentication).
- -Body: Data to send in the request body (use -ContentType to specify format like application/json).
Example: Authenticating with a Bearer Token¶
$token = "your-access-token"
$headers = @{
"Authorization" = "Bearer $token"
"Accept" = "application/json"
}
$response = Invoke-RestMethod -Uri "https://api.example.com/secure/data" -Headers $headers -Method Get
Handling Errors and Responses¶
-
Error Handling: Use
try/catchblocks to handle exceptions:
-
Parsing Responses:
For JSON responses, useConvertFrom-Jsonto transform raw content into PowerShell objects.
Common Use Cases¶
- Automating Cloud Services: Interact with AWS, Azure, or GCP APIs to manage resources.
- Custom API Integration: Communicate with internal systems or SaaS platforms.
- Monitoring and Reporting: Poll APIs for metrics or log data.
Key takeaways¶
- Use
Invoke-RestMethodfor simplicity with JSON APIs; useInvoke-WebRequestfor raw HTTP control. - Always specify
-Methodand handle authentication via headers. - Parse JSON responses with
ConvertFrom-Jsonand usetry/catchfor error resilience. - Leverage PowerShell’s object-oriented approach to work with API data directly.
- Test endpoints with tools like Postman before automating to ensure correct request formats.