Search code examples
restapipowershellrestful-authentication

How do I access the value of a field returned by a Restful API


I have a very basic requirement to call a RESTful API. I am currently on a Windows 2012 R2 server using version 4 of PowerShell.

Here is my code:

$logon = @{
    username = 'blah'
    password='blah'
}

$body = $logon | ConvertTo-Json 

$URI = 'https://URL/Logon'

Invoke-WebRequest -URI $URI -Method POST -Body $body -ContentType 'application/json' -Verbose 

I get the following result:

{"LogonResult":"blahblahblah"}

How do I extract just the logon token to reuse as a variable? I've already put a variable at the beginning of the command:

   $token =  (Invoke-WebRequest -URI $URI -Method POST -Body $body -ContentType 'application/json' -Verbose).content 

This returns the entire result, not just the token. How do I get just the token as a result?


Solution

  • You can get the value of the returned LogonResult property as follows:

    $token =  ((Invoke-WebRequest -URI $URI -Method POST -Body $body -ContentType 'application/json' -Verbose).content | ConvertFrom-JSON).LogonResult
    

    Or you simplify this by using Invoke-RestMethod as this returns just the content and converts it to a PSObject automatically:

    $token =  (Invoke-RestMethod -URI $URI -Method POST -Body $body -ContentType 'application/json' -Verbose).LogonResult