Search code examples
powershellwebclientwebrequest

How do I find the XML error returned by an API call using Powershell?


I've got an API that I'm trying to test. The API returns specific comments on errors.

Example:

<errors>
    <error>distance.out.of.range</error>
</errors>

When querying the API in Chrome or Firefox, I see this XML.

However, when querying with IE or with Powershell (both WebClient and WebRequest), I'm only able to see the "400" exception. I can't find the XML drilling down into the exception.

Handling the exception with a try/catch is fine, but I'm missing out on understanding the specifics of the failed query. How can I find the XML?


Solution

  • I think you have to read the stream from the exception object

    $req = [system.Net.WebRequest]::Create($url)
    try {
        $res = $req.GetResponse()
    } catch [System.Net.WebException] {
        $res = $_.Exception.Response
    }
    

    $res will have a method called GetResponseStream() that you can use to read the data.