Getting Started with Invoke-RestMethod in PowerShell
Welcome back to Wahmans PowerShell blog! Today we’re diving into a super useful cmdlet that helps you interact with RESTful web services directly from PowerShell: Invoke-RestMethod.
What is Invoke-RestMethod?
As described by Microsoft, Invoke-RestMethod “sends an HTTP or HTTPS request to a RESTful web service.” That means if you’re working with APIs, especially in cloud environments like Azure or web-based tools like GitHub, this cmdlet is your best friend.
Why Use Invoke-RestMethod?
With its simple syntax and built-in parsing capabilities (JSON, XML, etc.), Invoke-RestMethod makes it really easy to consume web APIs in scripts or automation workflows.
Let’s dive into some examples!
Example 1: Beginner – Getting Public IP Address
This is a great first use case. Let’s make a request to a public API to get our IP address.
Invoke-RestMethod -Uri 'https://api.ipify.org?format=json'
Expected Output:
{
"ip": "203.0.113.1"
}
Example 2: Intermediate – Getting GitHub User Info
This example fetches information about a GitHub user. You can replace wahman with any GitHub username.
Invoke-RestMethod -Uri 'https://api.github.com/users/wahman'
You’ll receive a JSON response with details like name, public repos, and followers.
Example 3: Advanced – Submitting a POST Request
Let’s say an API you are interacting with requires you to send data via a POST request. Here’s how you do it:
$uri = 'https://jsonplaceholder.typicode.com/posts'
$body = @{
title = 'Wahman Post'
body = 'PowerShell rocks!'
userId = 1
} | ConvertTo-Json
Invoke-RestMethod -Uri $uri -Method Post -Body $body -ContentType 'application/json'
This will create a placeholder blog post on the dummy API.
Example 4: Pro Level – Using Headers and Authentication
Advanced APIs often require authentication tokens and custom headers. Here’s how you include them:
$headers = @{ Authorization = 'Bearer YOUR_ACCESS_TOKEN' }
$uri = 'https://api.example.com/v1/profile'
Invoke-RestMethod -Uri $uri -Headers $headers -Method Get
Just replace YOUR_ACCESS_TOKEN with a valid token. This is common when working with Azure, Google, Jira, and many more APIs.
Wrap Up
And that’s a wrap for today’s deep dive into Invoke-RestMethod. As you can see, it’s a powerful cmdlet that scales from simple API calls to complex automated systems. Keep exploring and integrating web services with PowerShell to make your workflows smarter and more dynamic.
Happy scripting, and I will see you in the next post!
Leave a Reply