With PowerShell 3.0 comes a wonderful Invoke-RestMethod cmdlet which much simplifies using REST services. The cmdlet handles all communication as well as data serialisation/deserialisation. Below gist shows how easy it is to make a call to get some data from the REST service:

$result = Invoke-RestMethod 'http://www.restservice.com/events'

Depending on the result type (atom, JSON, XML), the cmdlet will appropriately deserialise data and return richly object (or collection of objects).

Often access to the service requires authorization. In that case all you need to do is pass and instance of the PSCredential object. Depending on the case you can either use Get-Credential cmdlet which will prompt user for credentials, or create new instance of PSCredential object. Below example, taken from RabbitMQTools module (at the time of writing this module is in very early stage), shows how to list all Virtual Hosts registered with RabbitMQ server, using credentials of guest user:

$secpasswd = ConvertTo-SecureString 'guest' -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential ('guest', $secpasswd)
 
$vhosts = Invoke-RestMethod 'http://localhost:15672/api/vhosts' -credential $cred

To create new entity in REST service you use PUT method passing extra data in the body. For example, to create new Virtual Host in RabbitMQ with tracing enabled, you will call method PUT passing hosts name in the Url. Notice that variable $body is converted to JSON object and the content type on REST call is specified as JSON. as well:

$secpasswd = ConvertTo-SecureString 'guest' -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential ('guest', $secpasswd)
$body = @{
    "tracing" = $true
} | ConvertTo-Json

$vhosts = Invoke-RestMethod 'http://localhost:15672/api/vhosts/vhostname' -credential $cred -Method Put -ContentType "application/json" -Body $body

Deleting entity means calling REST service and using DELETE method:

$secpasswd = ConvertTo-SecureString 'guest' -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential ('guest', $secpasswd)

$vhosts = Invoke-RestMethod 'http://localhost:15672/api/vhosts/vhostname' -credential $cred -Method DELETE

Summary

As you can see working with REST Api services in PowerShell is very easy. The Invoke-RestMethod` cmdlet fully abstracts all communication and serialisation from the developer. The result comes as rich object and can be piped to other cmdlets like select or where.

I’d like to thank Jason Helmick and Jeffrey Snover for great Getting Started with PowerShell 3.0 Jump Start and Advanced Tools & Scripting with PowerShell 3.0 Jump Start modules on Microsoft Virtual Academy which helped me getting started with PowerShell.

And to find more about creating PowerShell modules come back to this blog, where I plan to write about my experiences at creating RabbitMQTools – the PowerShell module for administering RabbitMQ servers.