Invoke RestMethod - PowerShell
Overview
Invoke-RestMethod allows you to send HTTP requests and retrieve responses from RESTful web services within PowerShell. This versatile command enables interfacing with remote web APIs, retrieving data, and performing various tasks. It is a powerful tool for PowerShell users seeking to integrate with external web applications and services.
Syntax
Invoke-RestMethod [-Uri] <Uri> [-Method] <String> [-Body] <Object> [-Headers] <Hashtable> [-Parameters] <Hashtable> [-ContentType] <String> [-Accept] <String> [-UserAgent] <String> [-WebSession] <WebSession> [-Timeout] <Int32> [-MaxRetry] <Int32> [-UseBasicParsing] [-ErrorAction] <ActionPreference> [-ErrorVariable] <String> [-OutFile] <String> [-OutVariable] <String> [-PassThru]
Options/Flags
-Uri
-Method
-Body
-Headers
-Parameters
-ContentType
-Accept
-UserAgent
-WebSession
-Timeout
-MaxRetry
-UseBasicParsing
-ErrorAction
-ErrorVariable
-OutFile
-OutVariable
-PassThru
Examples
Simple GET request:
Invoke-RestMethod -Uri "https://example.com/api/users"
POST request with a request body:
$body = @{ Name = "John"; Age = 30 }
Invoke-RestMethod -Uri "https://example.com/api/users" -Method "POST" -Body $body
Retrieving a response as JSON:
$response = Invoke-RestMethod -Uri "https://example.com/api/users" -UseBasicParsing
$users = $response.JsonObject
Saving the response to a file:
Invoke-RestMethod -Uri "https://example.com/api/users" -OutFile "users.json"
Common Issues
- 404 Not Found: Ensure the URI is correct and accessible.
- 401 Unauthorized: Verify your credentials or ensure the API requires authentication.
- Timeout errors: Increase the timeout value using the
-Timeout
parameter. - Parse errors: Use the
-UseBasicParsing
switch parameter for responses that are not in JSON format. - SSL errors: Ensure the server’s SSL certificate is trusted or use the
-Insecure
parameter to bypass SSL certificate checking (not recommended for production environments).
Integration
Invoke-RestMethod can be combined with other PowerShell commands or tools for more complex tasks:
- Piping results to other commands:
Invoke-RestMethod -Uri "https://example.com/api/users" | Out-File "users.txt"
- Using web sessions for improved performance:
$session = New-WebSession
Invoke-RestMethod -Uri "https://example.com/api/users" -WebSession $session
- Creating scripts to automate API interactions:
Write your own PowerShell scripts to automate repetitive or complex API interactions using Invoke-RestMethod.
Related Commands
New-WebSession
Invoke-WebRequest
New-WebServiceProxy
- REST API Documentation