brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: Invoke-RestMethod turns a JSON API answer into PowerShell objects

Scripting
~/tips/tip-scripting-invoke-restmethod-json

$r = Invoke-RestMethod https://api.github.com/repos/PowerShell/PowerShell/releases/latest

Call a REST API and work with the fields directly, without parsing JSON yourself.

In PowerShell, Invoke-WebRequest gives you the raw response. For JSON APIs its sibling Invoke-RestMethod is nicer: it parses the body and hands you objects with properties.

Call the URL and pick the fields you want:

$r = Invoke-RestMethod https://api.github.com/repos/PowerShell/PowerShell/releases/latest
$r.tag_name
$r.assets | Select-Object name, size

No ConvertFrom-Json needed. Nested data becomes nested objects, so $r.assets is a list you can filter and sort like any other PowerShell output. The short alias is irm.

Sending data works the same way. Build the body as a hashtable and convert it:

$body = @{ name = "backup"; enabled = $true } | ConvertTo-Json
Invoke-RestMethod -Method Post -Uri https://api.example.com/jobs `
  -ContentType 'application/json' -Body $body

I like it for quick checks of a service from a script.

Error handling is the catch. Any 4xx or 5xx response throws an error instead of returning the body. In PowerShell 7 you can add -SkipHttpErrorCheck and -StatusCodeVariable code to get the response and status yourself; Windows PowerShell 5.1 does not have those switches. Also, when the API returns a list, the documentation notes that the whole array goes down a pipeline as one object.

Further reading: Invoke-RestMethod documentation

More Scripting tips import difflib import json, os, tempfile from collections import Counter import shutil from contextlib import chdir All Scripting tips (10) All topics

Link