Working with REST services in PowerShell

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:

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:

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:

Deleting entity means calling REST service and using DELETE method:

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.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s