Welcome PowerShell User! This recipe is just one of the hundreds of useful resources contained in the PowerShell Cookbook.

If you own the book already, login here to get free, online, searchable access to the entire book's content.

If not, the Windows PowerShell Cookbook is available at Amazon, or any of your other favourite book retailers. If you want to see what the PowerShell Cookbook has to offer, enjoy this free 90 page e-book sample: "The Windows PowerShell Interactive Shell".

12.7 Interact with REST-Based Web APIs

Problem

You want to work with an XML or JSON REST-based API.

Solution

Use the Invoke-RestMethod cmdlet to work with REST-based APIs. Example 12-7 demonstrates using the StackOverflow API to retrieve the 10 most recent unanswered quesions tagged “PowerShell.”

Example 12-7. Using Invoke-RestMethod with the StackOverflow API
PS > $url = "https://api.stackexchange.com/2.0/questions/unanswered" +
    "?order=desc&sort=activity&tagged=powershell&pagesize=10&site=stackoverflow"
PS > $result = Invoke-RestMethod $url
PS > $result.Items | ForEach-Object { $_.Title; $_.Link; "" }

Can I have powershell scripts in file with no extension?
http://stackoverflow.com/questions/12230228/can-i-have-powershell-scripts...

Powershell: Replacing regex named groups with variables
http://stackoverflow.com/questions/12225415/powershell-replacing-regex-named...

(...)

Discussion

Most web pages that return useful data provide this information with the intention that it will only ever be displayed by a web browser. Extracting this information is always difficult, although Recipe 12.5 usually makes the solution simpler than straight text manipulation.

When a web page is designed to be consumed by other programs or scripts, it is usually called a web service or web API. Web services are the more fully featured of the two. They rely on a technology called SOAP (Simple Object Access Protocol), and mimic traditional programming APIs that support rigid structures, standardized calling behavior, and strongly typed objects. Recipe 12.8 demonstrates how to interact with web services from PowerShell.

While much less structured, web APIs tend to follow some similar basic design philosophies—primarily URL structures, standard HTTP methods (GET/POST), and data types (JSON/XML). These loosely defined design philosophies are usually grouped under the term REST (Representational State Transfer), making REST API the term most commonly used for non-SOAP web services.

While still designed to be consumed by programs or scripts, REST APIs have a much less rigid structure. Because of their simplicity, they have become the dominant form of web service on the internet.

The Invoke-RestMethod cmdlet forms the basis of how you interact with REST APIs from PowerShell. It acts much like the Invoke-WebRequest cmdlet in that it lets you invoke standard HTTP operations against URLs: GET, PUT, POST, and more. Unlike Invoke-WebRequest, though, Invoke-RestMethod assumes that the data returned from the website is designed to be consumed by a program. Depending on the data returned by the web service (XML or JSON), it automatically interprets the returned data and converts it into PowerShell objects.

Note

If this interpretation is incorrect for a website or REST API, you can always use the Invoke-WebRequest cmdlet directly.

As another example of interacting with REST APIs, Example 12-8 demonstrates using the StackOverflow API to find the accepted answer for the PowerShell questions matching your search term.

Example 12-8. Searching StackOverflow for answers to a PowerShell question
##############################################################################
##
## Search-StackOverflow
##
## From PowerShell Cookbook (O'Reilly)
## by Lee Holmes (http://www.leeholmes.com/guide)
##
##############################################################################

<#

.SYNOPSIS

Searches Stack Overflow for PowerShell questions that relate to your
search term, and provides the link to the accepted answer.


.EXAMPLE

PS > Search-StackOverflow upload ftp
Searches StackOverflow for questions about how to upload FTP files

.EXAMPLE

PS > $answers = Search-StackOverflow.ps1 upload ftp
PS > $answers | Out-GridView -PassThru | Foreach-Object { start $_ }

Launches Out-GridView with the answers from a search. Select the URLs
that you want to launch, and then press OK. PowerShell then launches
your default web browser for those URLs.

#>

Set-StrictMode -Off
Add-Type -Assembly System.Web

$query = $args -join " "
$query = [System.Web.HttpUtility]::UrlEncode($query)

## Use the StackOverflow API to retrieve the answer for a question
$url = "https://api.stackexchange.com/2.0/search?order=desc&sort=relevance" +
    "&pagesize=5&tagged=powershell&intitle=$query&site=stackoverflow"
$question = Invoke-RestMethod $url

## Now go through and show the questions and answers
$question.Items | Where-Object accepted_answer_id | Foreach-Object {
        "Question: " + $_.Title
        "https://www.stackoverflow.com/questions/$($_.accepted_answer_id)"
        ""
}

See Also

Recipe 12.5, “Parse and Analyze a Web Page from the Internet”