Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the body of a web request that returned 400 Bad Request from Invoke-RestMethod

When I run the following statement

Invoke-RestMethod "https://api.mysite.com/the/endpoint" `     -Body (ConvertTo-Json $data) `     -ContentType "application/json" `     -Headers $DefaultHttpHeaders `     -Method Post 

the endpoint returns 400 Bad Request, which causes PowerShell to show the following not-so-helpful message:

Invoke-WebRequest : The remote server returned an error: (400) Bad Request. At line:1 char:1 + Invoke-WebRequest "https://api.mysite.com/the/endpoint" -Body  ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~     + CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebException     + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand

How do I get the body of the response, which might tell me what was wrong with the request I sent?

like image 653
Tomas Aschan Avatar asked Mar 14 '16 11:03

Tomas Aschan


1 Answers

There is a known issue with PowerShell Invoke-WebRequest and Invoke-RestMethod where the shell eats the response body when the status code is an error (4xx or 5xx). Sounds like the JSON content you are looking for is evaporating in just this manner. You can fetch the response body in your catch block using $_.Exception.Response.GetResponseStream()

    try {     Invoke-RestMethod "https://api.mysite.com/the/endpoint" `         -Body (ConvertTo-Json $data) `         -ContentType "application/json" `         -Headers $DefaultHttpHeaders `         -Method Post     }     catch {         $streamReader = [System.IO.StreamReader]::new($_.Exception.Response.GetResponseStream())         $ErrResp = $streamReader.ReadToEnd() | ConvertFrom-Json         $streamReader.Close()     }      $ErrResp 
like image 140
brendan62269 Avatar answered Sep 23 '22 00:09

brendan62269