Using JSON-based Web Services

by Mar 2, 2015

PowerShell 3 and better

There are plenty of information web services out in the Internet, and many of them return results in JSON format. Here is an example that illustrates how PowerShell would query such web services, and convert the JSON results to objects.

The example uses a web service of the German railroad company. You can enter part of the name of a train station or city, and get back the names of all railroad stations that contain what you entered:

# ask for part of the train station name
$name = Read-Host 'Enter part of train station Name'

# query webservice
$url = "http://openbahnapi.appspot.com/rest/stations/list?contains=$name"
$site = Invoke-WebRequest -Uri $url

# get JSON result
($site.Content | ConvertFrom-Json ).value

The result may look similar to this:

 
PS> Enter part of train station name: hanno
Hannover Hbf
HANNOVER MESSE
Hannoversch Münden
Hannover-Nordstadt
Hannover Bismarckstr.
Hannover Karl-Wiechert-Allee
Hannover-Ledeburg
Hannover-Linden/Fischerhof
Hannover-Vinnhorst
Hannover-Leinhausen
Hannover Anderten-Misburg
Hannover-Bornum

PS>  
 

This example is not about the German railroad system, so if you are not particularly interested in German railroad stations, adapt it to the JSON-based web service of your choice.

The important parts are Invoke-WebRequest (which contacts the web service and returns the result), and ConvertFrom-Json (which takes the results and turns them into objects).

Please note that web services can change on the disposal of their owners. The web service used in the example code was just that: an example web service. 

Twitter This Tip! ReTweet this Tip!