Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell v3 Invoke-RestMethod

I am attempting to make use of the new invoke-restmethod cmdlet to POST a JSON file and have succesfully done so. However, I do not receive a response from the webserver like I did when using CURL. For what I'm trying to accomplish I need to take info from the reposne to the POST and use this for another POST command.

Can someone please explain how I can get the expected response from the server? Below are the two commands 1st in CURL, 2nd using Invoke-RestMethod. The curl command will perform the correct POST and return a response. The Powershell command will perform the correct POST but will not return a response.

Thanks

edit: The main thing I believe I am trying to get from ps output is the "response headers" ie. the output below from a curl command

 < HTTP/1.1 201 Created
 < Date: Thu, 26 Jul 2012 01:20:06 GMT
 < Server: Apache
 < X-EM7-Implemented-methods: GET,PUT,POST
 < X-Powered-By: ScienceLogic,LLC - EM7 API/Integration Server
 < Location: /ticket/321750
 < X-EM7-status-message: ticket /ticket/321750 added.
 < X-EM7-status-code: CREATED
 < Content-Length: 830
 < Content-Type: application/json
 < 

Curl Command

 curl -f -v -s -k --no-sessionid -H X-em7-beautify-response:1 -H content-  type:application/json https://URLHERE --data-binary  @jsonfile.json

Powershell Code

 $cert=New-Object System.Security.Cryptography.X509Certificates.X509Certificate2("certfile.crt")
 $json = Get-Content jsonfile.json
 $cred = Get-Credential -Message "Enter Credentials"

 Invoke-RestMethod -Uri https://URLHERE -Credential $cred -Body $json -Certificate $cert -ContentType application/json -Method POST
like image 837
floyd Avatar asked Jul 25 '12 23:07

floyd


People also ask

What is the difference between invoke-RestMethod and invoke-WebRequest?

Invoke-RestMethod - unlike Invoke-WebRequest - has deserialization built in: with a JSON response, it automatically parses the JSON text returned into a [pscustomobject] graph as if ConvertFrom-Json had been applied to it.

Can PowerShell make API calls?

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.


1 Answers

After some fishing around I discovered the cmdlet Invoke-WebRequest. This cmdlet is basically identical to Invoke-RestMethod other than the fact that it returns the headers as well as response.

like image 184
floyd Avatar answered Oct 10 '22 21:10

floyd