Powershell: How to get REST API data in JSON format rather than XML using invoke-restmethod
Summary:
I was exploring a REST API interface for an internal tool being built. Being that I'm so accustomed to powershell, I wanted to explore how I could get data from it. The Invoke-RestMethod is perfect for this, but I was having issues getting data back in straight json format. Data kept coming back in ugly as hell xml format by default.
Details:
The short answer was that I need to make a hash table to pass to the -Header parameter of the invoke-method cmdlet. Basically, it looks like this:
Once I did this, I received the data back in json format and powershell automatically captures it as a system.array object. Making it immensely easier to work with rather than the xml return. See below pictures as examples of the difference.
As you can see, the return I received when in json looks like any other object return from something like powercli whereas the xml return is this ridiculous mess. Not all Rest API endpoints work in the same fashion. Some will return json by default, but listing the "Accept" = "application/json" in your request header doesn't seem to hurt those that don't unless you want a different type of return.
I was exploring a REST API interface for an internal tool being built. Being that I'm so accustomed to powershell, I wanted to explore how I could get data from it. The Invoke-RestMethod is perfect for this, but I was having issues getting data back in straight json format. Data kept coming back in ugly as hell xml format by default.
Details:
The short answer was that I need to make a hash table to pass to the -Header parameter of the invoke-method cmdlet. Basically, it looks like this:
$Headers = @{"Accept" = "application/json"} Invoke-RestMethod -URI "https://myrestapi/endpoint" -Method:Get -Headers $Headers
Once I did this, I received the data back in json format and powershell automatically captures it as a system.array object. Making it immensely easier to work with rather than the xml return. See below pictures as examples of the difference.
Json returned data. |
xml returned data |
Comments