Bird
Raised Fist0
PowerShellscripting~10 mins

REST API calls with Invoke-RestMethod in PowerShell - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - REST API calls with Invoke-RestMethod
Start Script
Prepare API URL
Call Invoke-RestMethod
Receive Response
Process/Display Data
End Script
This flow shows how a PowerShell script prepares a URL, calls Invoke-RestMethod to get data from a REST API, then processes and shows the response.
Execution Sample
PowerShell
$url = 'https://api.agify.io?name=michael'
$response = Invoke-RestMethod -Uri $url
$response | Format-List
This script calls a public API to guess the age for the name 'michael' and shows the response details.
Execution Table
StepActionVariable/CommandResult/Output
1Set API URL$url = 'https://api.agify.io?name=michael'Variable $url holds the API endpoint string
2Call REST API$response = Invoke-RestMethod -Uri $urlStores JSON response as PowerShell object in $response
3Display response$response | Format-ListShows properties: name, age, count with values
4EndScript finishesNo further actions
💡 Script ends after displaying the API response
Variable Tracker
VariableStartAfter Step 1After Step 2Final
$urlnull'https://api.agify.io?name=michael''https://api.agify.io?name=michael''https://api.agify.io?name=michael'
$responsenullnull{name: 'michael', age: 69, count: 12345}{name: 'michael', age: 69, count: 12345}
Key Moments - 3 Insights
Why do we assign the API URL to a variable before calling Invoke-RestMethod?
Assigning the URL to $url makes the script easier to read and change. The execution_table row 1 shows $url holding the API endpoint before the call.
What type of data does Invoke-RestMethod return and how is it stored?
Invoke-RestMethod converts JSON response into a PowerShell object stored in $response, as shown in execution_table row 2.
Why do we use Format-List when displaying $response?
Format-List shows all properties clearly in a list format, making it easier to read the API response, as in execution_table row 3.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of $url after step 1?
A'https://api.agify.io?name=michael'
Bnull
C'https://api.agify.io?name=john'
DAn empty string
💡 Hint
Check the 'Variable/Command' and 'Result/Output' columns for step 1 in execution_table
At which step does $response get its value?
AStep 1
BStep 2
CStep 3
DStep 4
💡 Hint
Look at the 'Action' and 'Variable/Command' columns in execution_table to see when $response is assigned
If we changed the URL to a different name, how would $response change?
AIt would stay the same
BIt would be empty
CIt would contain data for the new name
DIt would cause an error
💡 Hint
Refer to variable_tracker showing $response content depends on the API URL value
Concept Snapshot
Invoke-RestMethod calls a REST API and returns data as a PowerShell object.
Assign the API URL to a variable for clarity.
Store the response in a variable to use later.
Use Format-List or other commands to display the data.
This method works for GET requests easily.
Full Transcript
This example shows how to use PowerShell's Invoke-RestMethod to call a REST API. First, the API URL is saved in the variable $url. Then Invoke-RestMethod calls the API and stores the JSON response as a PowerShell object in $response. Finally, Format-List displays the response properties clearly. This process helps you get and use data from web APIs simply in scripts.

Practice

(1/5)
1. What does the PowerShell cmdlet Invoke-RestMethod primarily do?
easy
A. It sends HTTP requests to web APIs and returns parsed responses.
B. It creates new files on the local system.
C. It compiles PowerShell scripts into executables.
D. It manages Windows services remotely.

Solution

  1. Step 1: Understand the purpose of Invoke-RestMethod

    This cmdlet is designed to send HTTP requests to REST APIs and automatically parse the response into PowerShell objects.
  2. Step 2: Compare options with the cmdlet's function

    Options B, C, and D describe unrelated tasks like file creation, compiling, or service management, which Invoke-RestMethod does not perform.
  3. Final Answer:

    It sends HTTP requests to web APIs and returns parsed responses. -> Option A
  4. Quick Check:

    Invoke-RestMethod = Sends HTTP requests [OK]
Hint: Invoke-RestMethod calls APIs and returns objects [OK]
Common Mistakes:
  • Confusing Invoke-RestMethod with file or service commands
  • Thinking it only sends GET requests
  • Assuming it returns raw text instead of parsed objects
2. Which of the following is the correct syntax to send a GET request to https://api.example.com/data using Invoke-RestMethod?
easy
A. Invoke-RestMethod -Url https://api.example.com/data -Method GET
B. Invoke-RestMethod -Url https://api.example.com/data -Method POST
C. Invoke-RestMethod -Uri https://api.example.com/data -Method FETCH
D. Invoke-RestMethod -Uri https://api.example.com/data -Method GET

Solution

  1. Step 1: Identify correct parameter names and HTTP method

    The correct parameter for the URL is '-Uri' and the HTTP method for retrieving data is 'GET'.
  2. Step 2: Check each option for syntax correctness

    Invoke-RestMethod -Uri https://api.example.com/data -Method GET uses '-Uri' and '-Method GET' correctly. Invoke-RestMethod -Url https://api.example.com/data -Method POST uses '-Url' (incorrect parameter) and POST method. Invoke-RestMethod -Url https://api.example.com/data -Method GET uses '-Url' (incorrect parameter). Invoke-RestMethod -Uri https://api.example.com/data -Method FETCH uses an invalid HTTP method 'FETCH'.
  3. Final Answer:

    Invoke-RestMethod -Uri https://api.example.com/data -Method GET -> Option D
  4. Quick Check:

    Use -Uri and -Method GET for GET requests [OK]
Hint: Use -Uri for URL and -Method GET for GET requests [OK]
Common Mistakes:
  • Using -Url instead of -Uri
  • Using -Method POST instead of GET
  • Using invalid HTTP methods like FETCH
3. What will be the output of this PowerShell code snippet?
 $response = Invoke-RestMethod -Uri 'https://jsonplaceholder.typicode.com/posts/1' -Method GET
$response.title
medium
A. Null, because $response.title does not exist
B. An error because the -Method parameter is missing
C. The title of the post with ID 1 from the API
D. The entire JSON response as a string

Solution

  1. Step 1: Understand Invoke-RestMethod behavior

    Invoke-RestMethod sends a GET request and parses JSON into an object. Accessing $response.title retrieves the 'title' property.
  2. Step 2: Analyze the code and expected output

    The API returns a JSON object with a 'title' field for post ID 1. The code prints that title string.
  3. Final Answer:

    The title of the post with ID 1 from the API -> Option C
  4. Quick Check:

    Invoke-RestMethod parses JSON; access properties directly [OK]
Hint: Invoke-RestMethod returns objects; access properties like .title [OK]
Common Mistakes:
  • Expecting raw JSON string instead of parsed object
  • Forgetting to specify -Method GET (optional but recommended)
  • Assuming $response.title is null without checking API
4. You run this command but get an error:
Invoke-RestMethod -Uri 'https://api.example.com/data' -Method POST -Body '{"name":"John"}'

What is the most likely cause?
medium
A. The -Method POST is invalid; only GET is allowed.
B. The -Body parameter must be a PowerShell object, not a JSON string.
C. The URI is missing the protocol (http/https).
D. Invoke-RestMethod cannot send POST requests.

Solution

  1. Step 1: Understand -Body parameter requirements

    Invoke-RestMethod expects the -Body parameter as a PowerShell object or properly formatted string with correct headers.
  2. Step 2: Identify issue with JSON string body

    Passing a raw JSON string without setting Content-Type header or converting to object causes errors.
  3. Final Answer:

    The -Body parameter must be a PowerShell object, not a JSON string. -> Option B
  4. Quick Check:

    Use objects or set headers when sending JSON body [OK]
Hint: Send objects or set headers when posting JSON body [OK]
Common Mistakes:
  • Passing JSON string without Content-Type header
  • Assuming POST is unsupported
  • Omitting protocol in URI
5. You want to send a POST request with JSON data {"username":"admin","password":"pass123"} to https://api.example.com/login using Invoke-RestMethod. Which script correctly sends the request and handles the JSON response?
hard
A. $body = @{username='admin'; password='pass123'}
Invoke-RestMethod -Uri 'https://api.example.com/login' -Method POST -Body ($body | ConvertTo-Json) -ContentType 'application/json'
B. $body = '{"username":"admin","password":"pass123"}'
Invoke-RestMethod -Uri 'https://api.example.com/login' -Method POST -Body $body
C. $body = @{username='admin'; password='pass123'}
Invoke-RestMethod -Uri 'https://api.example.com/login' -Method GET -Body $body
D. Invoke-RestMethod -Uri 'https://api.example.com/login' -Method POST -Body @{username='admin'; password='pass123'}

Solution

  1. Step 1: Prepare the body as a PowerShell object and convert to JSON

    Creating a hashtable and converting it to JSON ensures the body is correctly formatted for the API.
  2. Step 2: Use -ContentType 'application/json' to inform the server

    Setting the Content-Type header is necessary for the server to interpret the JSON body correctly.
  3. Step 3: Verify the HTTP method is POST

    POST is required to send data; GET with body is invalid.
  4. Final Answer:

    $body = @{username='admin'; password='pass123'}
    Invoke-RestMethod -Uri 'https://api.example.com/login' -Method POST -Body ($body | ConvertTo-Json) -ContentType 'application/json'
    -> Option A
  5. Quick Check:

    Convert body to JSON and set Content-Type for POST [OK]
Hint: Convert body to JSON and set Content-Type for POST [OK]
Common Mistakes:
  • Sending raw JSON string without Content-Type header
  • Using GET method with body
  • Passing hashtable directly without JSON conversion