Understanding REST Web Services in PowerShell

by Jan 5, 2021

There are many different types of web services, and PowerShell can access many of them using Invoke-RestMethod. Here is a quick intro to get you started.

In its most simple form, a web service is just a web page with structured data on it. You can use the very same URL in your browser to view the data. PowerShell uses Invoke-RestMethod to retrieve the data. This gets you the latest PowerShell team blogs:

Invoke-RestMethod -Uri https://blogs.msdn.microsoft.com/powershell/feed/ |
  Select-Object -Property Title, pubDate

Simple REST web services like the one above can accept arguments. These arguments can be submitted as part of the URL. Here is a web service that takes any number and returns semi-meaningful information about that number. The next time you get invited to the 25th anniversary, you may want to look up some funny details about the number 25:

 
PS> Invoke-RestMethod http://numbersapi.com/25
25 is the number of cents in a quarter.

PS> Invoke-RestMethod http://numbersapi.com/25
25 is the (critical) number of Florida electoral votes for the 2000 U.S. presidential election.

PS> Invoke-RestMethod http://numbersapi.com/25
25 is the minimum age of candidates for election to the United States House of Representatives.  
 

Other web services accept user information as invisible POST data (similar to form data on web sites). They may also require session state, cookies, and/or logging in.

Here is a final example on this:

# https://4bes.nl/2020/08/23/calling-a-rest-api-from-powershell/

$Body = @{
    Cook = "Freddy"
    Meal = "PastaConCarne"
}
 
$Parameters = @{
    Method = "POST"
    Uri =  "https://4besday4.azurewebsites.net/api/AddMeal"
    Body = ($Body | ConvertTo-Json) 
    ContentType = "application/json"
}
Invoke-RestMethod @Parameters -SessionVariable cookie
Invoke-RestMethod "https://4besday4.azurewebsites.net/api/AddMeal" -WebSession $cookie

A hash table resembles the arguments you are sending to the web service. They are converted to JSON format. It is up to the web service to determine in which format it accepts user input. The data is then transmitted to the web service using the POST method.

If you send a unique name for the cook, you get back a notification from the web service that your meal is being prepared. Make sure you change the data for Cook and Meal.

As you see, Invoke-RestMethod is used twice. The first call gets the session state and cookies and stores this in the $cookie variable which was defined using the -SessionVariable parameter.

The second call submits the session state via the -WebSession parameter. This way, the web service can preserve state between your calls and clearly identify you.


Twitter This Tip! ReTweet this Tip!