Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 34 ยท Real-World Use

Web Requests and REST APIs

Call web APIs from PowerShell: Invoke-RestMethod vs Invoke-WebRequest, headers, JSON bodies, bearer tokens, error handling, pagination and retry with backoff.

Almost every service you automate today has a web API: GitHub, Azure, Microsoft Graph, your ticket system, your monitoring tool. PowerShell talks to them with two cmdlets, Invoke-RestMethod and Invoke-WebRequest. Because PowerShell works with objects, a JSON answer from an API arrives as ordinary properties you can filter, sort and export, with no manual parsing.

In this lesson you will learn which cmdlet to pick, how to send headers and JSON, how to authenticate, how to handle errors, and how to page through large result sets and retry politely. The real cmdlets need a network and a PowerShell runtime, so they appear as read-only code. The runnable examples use a small Node.js server on the loopback address plus a stand-in client, so you can watch the same ideas work. The stand-in is not PowerShell: it only mimics what the cmdlets do.

Code in this lesson targets PowerShell 7. Windows PowerShell 5.1 has the same two cmdlets but fewer parameters (no -Authentication, -SkipHttpErrorCheck, -FollowRelLink or retry options), and Invoke-WebRequest there may need -UseBasicParsing. See What Is PowerShell? for the differences.

Two cmdlets, two jobs

Pick the right cmdlet

Invoke-RestMethod Returns the parsed body. JSON becomes objects.
Invoke-WebRequest Returns the whole response with status and headers.

Use the first for data, the second when you need the envelope.

1 / 2

Invoke-RestMethod (alias irm) sends the request, looks at the Content-Type of the answer and converts it. JSON becomes a [pscustomobject], XML becomes an XML document, anything else stays text. Invoke-WebRequest (alias iwr) returns a response object with StatusCode, Headers, Content and more, and leaves the body untouched. A good rule: if you only want data, use Invoke-RestMethod; if you need to read a header such as Link or Retry-After, or want the status code, use Invoke-WebRequest.

POWERSHELL
# data only: $user is already an object
$user = Invoke-RestMethod -Uri 'https://api.example.com/users/7'
$user.name
$user.roles -join ', '

# the whole response
$response = Invoke-WebRequest -Uri 'https://api.example.com/users/7'
$response.StatusCode          # 200
$response.Headers['Content-Type']
$response.Content | ConvertFrom-Json

You can pipe results like any other objects. See Where-Object, Select-Object and Sort-Object for the tools you will use on the answers.

Headers, bodies and methods

Use -Method for the verb, -Headers for a hashtable of headers and -Body for the payload. For JSON APIs, build the body as a hashtable, convert it with ConvertTo-Json, and say so in -ContentType:

POWERSHELL
$body = @{ title = 'Printer is on fire'; priority = 'high' } | ConvertTo-Json

$ticket = Invoke-RestMethod -Method Post `
    -Uri 'https://api.example.com/tickets' `
    -Headers @{ Accept = 'application/json' } `
    -ContentType 'application/json' `
    -Body $body

$ticket.id

Two details trip people up. First, if you pass a hashtable directly to -Body on a POST, PowerShell sends it as form fields (title=...&priority=...), not JSON. Second, ConvertTo-Json stops at a default depth of 2, so nested objects get flattened to text. Add -Depth 10 for deeper data (see CSV, JSON and XML).

When a URL needs query parameters, avoid gluing strings together. Build the query from values and encode them, so a space or an ampersand in a value cannot break the URL:

POWERSHELL
$query = 'name=' + [uri]::EscapeDataString('Ada & Grace') + '&page=2'
Invoke-RestMethod -Uri "https://api.example.com/search?$query"

Authentication

Most APIs want a token in the Authorization header. PowerShell 7 has built-in support for bearer tokens, and it insists that the token is a SecureString, which nudges you away from leaving it in plain text:

POWERSHELL
$token = Read-Host -Prompt 'API token' -AsSecureString

Invoke-RestMethod -Uri 'https://api.example.com/me' `
    -Authentication Bearer -Token $token

For basic authentication use -Authentication Basic -Credential $cred with a credential from Get-Credential. PowerShell 7 refuses to send credentials over plain http:// unless you add -AllowUnencryptedAuthentication, which you should only ever do against a local test server. On Windows PowerShell 5.1, or for custom schemes, set the header yourself: -Headers @{ Authorization = "Bearer $plainToken" }. Where to keep tokens safely is the topic of Security and Secrets.

What the cmdlets do, in a stand-in

The first example starts a tiny server that answers on 127.0.0.1 with a random free port. It has three routes: a user lookup, a ticket creation that requires a token, and a 404 for everything else. Two small functions imitate the cmdlets: invokeWebRequest returns the whole response, invokeRestMethod parses JSON and throws on error statuses, as the real cmdlet does.

Node.js Stand-in: RestMethod vs WebRequest

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

In the real cmdlets a failed request throws a terminating error, so you handle it with try/catch (see Errors, try/catch and ErrorAction). In PowerShell 7 the exception carries the response, which lets you read the status and the error body:

POWERSHELL
try {
    $result = Invoke-RestMethod -Uri 'https://api.example.com/missing'
}
catch {
    $status = $_.Exception.Response.StatusCode      # NotFound
    Write-Warning "Request failed with $([int]$status): $($_.ErrorDetails.Message)"
}

Two PowerShell 7 parameters make error handling simpler. -SkipHttpErrorCheck stops the cmdlet from throwing on 4xx and 5xx, so you can inspect the response yourself, and -StatusCodeVariable code stores the status code in $code. Always add -TimeoutSec to scripts that run unattended, so a stuck server cannot hang your job forever.

Pagination

APIs rarely return everything at once. They return a page and tell you how to get the next one, in one of two common ways. Some put a next link in the JSON body, and some use the HTTP Link header, as GitHub does. PowerShell 7 understands the header form directly:

POWERSHELL
# follows rel="next" links for you, up to 10 pages
Invoke-RestMethod -Uri 'https://api.example.com/items?per_page=50' `
    -FollowRelLink -MaximumFollowRelLink 10 |
    ForEach-Object { $_ }

With -FollowRelLink the output is one array per page, so the ForEach-Object { $_ } at the end unrolls them into single items. For body-based paging, write the loop yourself:

POWERSHELL
$items = [System.Collections.Generic.List[object]]::new()
$uri = 'https://api.example.com/items?page=1'

while ($uri) {
    $page = Invoke-RestMethod -Uri $uri
    $items.AddRange($page.items)
    $uri = $page.next          # $null on the last page ends the loop
}

Use a generic list instead of += on an array, because every += copies the whole array (see Arrays and Hashtables).

Retry with backoff

Networks fail, servers restart and APIs rate-limit you with status 429. A polite client waits and tries again, with longer pauses each time. PowerShell 7 has it built in:

POWERSHELL
Invoke-RestMethod -Uri 'https://api.example.com/items' `
    -MaximumRetryCount 4 -RetryIntervalSec 2

The cmdlet retries on certain failures (rate limiting and server errors, for example) and waits the interval between tries. If you need exponential backoff, or must retry on other conditions, write a small function around the call. Only retry requests that are safe to repeat: a GET is, a POST that creates a ticket may create two.

The next stand-in combines both ideas. Its server hands out three pages of two items, links them with a Link header, and fails once with 503 on page two. The client follows the links and retries with doubling delays. It is a model of the logic, not the cmdlet.

Node.js Stand-in: follow links and retry

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Good habits

  • Wrap calls in try/catch, set -TimeoutSec, and log the status code on failure.
  • Build URLs with [uri]::EscapeDataString() for values, never raw string concatenation.
  • Keep tokens in a secret store, not in the script, and never print a request that includes them.
  • Respect rate limits: read Retry-After when the API sends it, and avoid tight loops.
  • Select only the properties you need early in the pipeline, so large answers do not fill memory.
  • Use Invoke-WebRequest for downloads with -OutFile, and check the hash if the file matters.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which cmdlet returns JSON as ready-to-use objects?

    Invoke-RestMethod converts a JSON answer into objects. Invoke-WebRequest returns the whole response and leaves the body as text.
  2. 2. You need to read the Link header of a response to find the next page. Which cmdlet gives you the headers directly?

    Invoke-WebRequest returns a response object with a Headers property. (Invoke-RestMethod can also follow rel=next links by itself with -FollowRelLink.)
  3. 3. What happens if you pass a hashtable to -Body on a POST and set no content type?

    A hashtable body becomes form-encoded data. For JSON, convert it with ConvertTo-Json and set -ContentType 'application/json'.
  4. 4. Why should you only retry requests that are safe to repeat?

    A GET can be repeated without side effects, but a POST that creates a record may succeed on the server even if the answer was lost, so a retry creates a duplicate.
  5. 5. How does PowerShell 7 treat a 404 or 500 response from Invoke-RestMethod by default?

    Failed statuses raise a terminating error. Use -SkipHttpErrorCheck if you prefer to inspect the response yourself.

Summary

  • Invoke-RestMethod returns parsed data; Invoke-WebRequest returns the whole response with status and headers.
  • Send JSON with ConvertTo-Json, -ContentType 'application/json' and -Body; a hashtable body is form-encoded.
  • PowerShell 7 supports -Authentication Bearer -Token $secureString; never send credentials over plain HTTP outside local tests.
  • Failed statuses throw; use try/catch, -SkipHttpErrorCheck or -StatusCodeVariable, and always set -TimeoutSec.
  • Page with -FollowRelLink or your own loop over a next value, and retry only safe requests, with growing delays.
  • The loopback server and clients here are stand-ins that model the behavior; the real cmdlets are shown read-only.

Next: Security and Secrets.