0
0
PowerShellscripting~5 mins

REST API calls with Invoke-RestMethod in PowerShell

Choose your learning style9 modes available
Introduction

Invoke-RestMethod helps you talk to web services easily. It sends requests and gets data back in a simple way.

You want to get weather information from an online service.
You need to send data to a website to create or update something.
You want to fetch user details from a web API.
You want to automate checking your online account balance.
You want to download data from a public API for analysis.
Syntax
PowerShell
Invoke-RestMethod -Uri <string> [-Method <string>] [-Headers <hashtable>] [-Body <string>] [-ContentType <string>]

-Uri is the web address you want to call.

-Method is usually GET (to get data) or POST (to send data).

Examples
Simple GET request to get data from the API.
PowerShell
Invoke-RestMethod -Uri 'https://api.example.com/data'
Send JSON data with a POST request.
PowerShell
Invoke-RestMethod -Uri 'https://api.example.com/data' -Method POST -Body '{"name":"John"}' -ContentType 'application/json'
GET request with an authorization header.
PowerShell
Invoke-RestMethod -Uri 'https://api.example.com/data' -Headers @{Authorization='Bearer token123'}
Sample Program

This script calls a public API to get a post's details and prints the title and body.

PowerShell
try {
  $response = Invoke-RestMethod -Uri 'https://jsonplaceholder.typicode.com/posts/1'
  Write-Output "Title: $($response.title)"
  Write-Output "Body: $($response.body)"
} catch {
  Write-Output "Error calling API: $_"
}
OutputSuccess
Important Notes

Invoke-RestMethod automatically converts JSON responses into PowerShell objects.

Use try/catch to handle errors like network issues.

Always check the API documentation for required headers and methods.

Summary

Invoke-RestMethod makes calling web APIs simple and returns easy-to-use objects.

You can use it to GET data or POST data with headers and body.

Handling errors helps keep your scripts reliable.