Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call REST API from PowerShell Script

How can I call a rest based API from a PowerShell script and process the Json answer?

like image 569
user285677 Avatar asked Aug 26 '10 11:08

user285677


People also ask

Can we call REST API from PowerShell?

In the PowerShell world, that client is the Invoke-RestMethod cmdlet. This cmdlet sends HTTP requests using various HTTP methods to REST API endpoints. HTTP methods then instruct REST APIs to carry out various actions to be performed on a resource.

How do I run a REST API in PowerShell?

To call a REST API from the Windows PowerShell, you should use the Invoke-RestMethod cmdlet. A call to an API is simply a request through HTTP or HTTPS. So, you will need a URL to which the API will be sent. You can find detailed information about the URL to call to get data from API documentation.

How do I call Azure REST API from PowerShell?

To use the Azure Rest API using PowerShell, we first need to connect to the Azure cloud account using the Connect-AzAccount. Once you are connected to the Azure Account, you can use the below authorization header (same has been provided on the MS website) which contains a bearer token to authenticate the rest API.


3 Answers

What you want is PowerShell 3 and its Invoke-RestMethod, ConvertTo-Json, and ConvertFrom-Json cmdlets. Your code will end up looking like:

 $stuff = Invoke-RestMethod -Uri $url -Method Get; 

and there shouldn't even be a need to invoke ConvertFrom-Json on the resulting $stuff => it's already in a usable non-string format.

See http://technet.microsoft.com/en-us/Library/hh849971.aspx for details.

like image 191
Dave Avatar answered Sep 27 '22 21:09

Dave


I created this Get-Http function to make HTTP requests

param([string]$url)  $req = [System.Net.WebRequest]::Create($url) $req.Method ="GET" $req.ContentLength = 0  $resp = $req.GetResponse() $reader = new-object System.IO.StreamReader($resp.GetResponseStream()) $reader.ReadToEnd() 

Dealing with the end result as xml is really easy, however, if you want to process JSON you probably will need some .Net library like JSON.Net.

like image 27
Darrel Miller Avatar answered Sep 27 '22 22:09

Darrel Miller


We use Powershell to query a REST API that deals only with Json style data. It was awkward at first but the below code is all we need to perform most operations:

# Authentication
$webclient = New-Object System.Net.WebClient
$creds = New-Object System.Net.NetworkCredential("MyUsername","MyPassword");
$webclient.Credentials = $creds

# Data prep
$data = @{Name='Test';} | ConvertTo-Json

# GET
$webClient.DownloadString($url) | ConvertFrom-Json

# POST
$webClient.UploadString($url,'POST',$data)

# PUT
$webClient.UploadString($url,'PUT',$data)
like image 45
ShaneC Avatar answered Sep 27 '22 22:09

ShaneC