Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Powershell Invoke-Restmethod to return body of http 500 code response

Invoke-RestMethod call returns only very unhelpful exception below and does not (as far as I can tell) allow you to collect the body content (JSON object shown in fiddler trace results). This seems a pretty bad implementation if so because http 500 definition is pretty specific that client should return the body of the response to help troubleshoot... Am I missing something?

invoke-restmethod -method Post -uri "https://api-stage.enviance.com/ver2/EqlService.svc/eql" -Body (ConvertTo-Json $eqlhash)  -Headers @{"Authorization"="Enviance $session"} 

invoke-restmethod : The remote server returned an error: (500) Internal Server Error. At line:1 char:9...

Fiddler trace below

HTTP/1.1 500 Internal Server Error Connection: close Date: Thu, 12 Sep 2013 17:35:00 GMT Server: Microsoft-IIS/6.0 X-Powered-By: ASP.NET X-AspNet-Version: 2.0.50727 EnvApi-Version: 2.0,2.0 EnvApi-Remaining-Calls: 994,994 EnvApi-Remaining-Interval: 2684,2684 Cache-Control: no-cache Pragma: no-cache Expires: -1 Content-Type: text/csv; charset=utf-8

{"errorNumber":0,"message":"Current user has no rights to retrieve data from table 'CustomFieldTemplate'"}

like image 497
JorgeSandoval Avatar asked Sep 12 '13 18:09

JorgeSandoval


People also ask

What is invoke-RestMethod in PowerShell?

Description. The Invoke-RestMethod cmdlet sends HTTP and HTTPS requests to Representational State Transfer (REST) web services that return richly structured data. PowerShell formats the response based to the data type. For an RSS or ATOM feed, PowerShell returns the Item or Entry XML nodes.

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

Invoke-RestMethod is perfect for quick APIs that have no special response information such as Headers or Status Codes, whereas Invoke-WebRequest gives you full access to the Response object and all the details it provides.

What is PowerShell invoke-WebRequest?

The Invoke-WebRequest cmdlet sends HTTP and HTTPS requests to a web page or web service. It parses the response and returns collections of links, images, and other significant HTML elements. This cmdlet was introduced in PowerShell 3.0.


1 Answers

The other answer does get you the response, but you need an additional step to get the actual body of the response, not just the headers. Here is a snippet:

try {         $result = Invoke-WebRequest ... } catch {         $result = $_.Exception.Response.GetResponseStream()         $reader = New-Object System.IO.StreamReader($result)         $reader.BaseStream.Position = 0         $reader.DiscardBufferedData()         $responseBody = $reader.ReadToEnd(); } 
like image 66
Noah Stahl Avatar answered Sep 20 '22 20:09

Noah Stahl