Monday, March 7, 2016

Invoke Webservice or RESTApi using windows Powershell

You can test the REST API web services using powershell. Some times it may require to access webservice in powershell for automation purpose.

Using invoke-RestMethod, one can call web service in powershell. I am using freely available webservice call for testing purpose.

PS C:\Users> $uri = "http://jsonplaceholder.typicode.com/posts"
PS C:\Users> $p=Invoke-RestMethod -Uri $uri -Method GET

PS C:\Users> $p.count
100

PS C:\Users> $p[0] | fl
userId : 1
id     : 1
title  : sunt aut facere repellat provident occaecati excepturi optio reprehenderit
body   : quia et suscipit
         suscipit recusandae consequuntur expedita et cum
         reprehenderit molestiae ut ut quas totam
         nostrum rerum est autem sunt rem eveniet architecto

If the Webservice requires authentication, you can use following way by providing username and password.

For example, To get list of calender events from your mailbox using O365 REST Api

$uri = "https://outlook.office365.com/api/v1.0/users/admin@domain.com/calendarview?startDateTime=$(Get-Date)&endDateTime=$((Get-Date).AddDays(7))"
$password = ConvertTo-SecureString 'passwordxxxxx' -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential "admin@domain.com",$password
$p=Invoke-RestMethod -Uri $uri -Method GET -Credential $cred
$p| fl


Hope it helps.
Pin It
Related Posts Plugin for WordPress, Blogger...