WhiskerBiscuit
WhiskerBiscuit

Reputation: 5157

How do I access the JSON from calling Invoke-WebRequest?

I need to call an API (to get a list of records from my DNS provider), and that can be done using curl. This returns formatted json with all of my records

curl -H 'Authorization: Bearer mytoken' -H 'Accept: application/json' https://api.dnsimple.com/v2/12345/zones/example.com/records

However, I need to be able to do this from PowerShell

$uri = "https://api.dnsimple.com/v2/12345/zones/example.com/records"
$headers = @{}
$headers["Authorization"] = "Bearer mytoken"
$headers["Accept"] = "application/json"
$foo = Invoke-WebRequest $uri -Headers $headers 

This command runs, but where in $foo can I access the returned JSON?

Upvotes: 2

Views: 2141

Answers (1)

briantist
briantist

Reputation: 47832

With Invoke-WebRequest, you would access the Content property: $foo.Content

Note that you can also use Invoke-RestMethod, which automatically converts JSON responses to PowerShell objects.

So this:

$o = Invoke-RestMethod #params

Would be the same as this:

$foo = Invoke-WebRequest #params
$o = $foo.Content | ConvertFrom-Json

Upvotes: 7

Related Questions