Forum Discussion
Problem outputting hashtable to JSON
Is it valid to send a header as a hashtable rather than JSON when using Invoke-RestMethod?
I think you're getting confused with the content type of the body versus the header.
As the Microsoft Docs link above states, the header has to be compatible with the IDictionary interface.
IDictionary Interface (System.Collections) | Microsoft Docs
If you expand the "Derived" link in that article, you can see that PowerShell's [hashtable] (full type name is [System.Collections.Hashtable]) and [ordered] (full type name is [System.Collections.Specialized.OrderedDictionary]) are both in that list, meaning they are compatible with the "-Headers" parameter, as per the Microsoft Docs article linked above for Invoke-RestMethod.
The "-Body" parameter is a completely different story. -Body can be any type you like (more or less), including JSON.
Again, referring back to the Invoke-RestMethod, if you look at the specification for the "-Body" parameter, you will see it's listed as "<Object>" ([System.Object]), which is the base class for all object types.
So, in short, we have:
| -Headers | IDictionary |
| -Body | Object |
Now, as I mentioned before, the data type produced from ConvertTo-Json is String [Systm.String] which is not compatible with IDictionary.
This is precisely what your error message is telling you. It is saying, "hey, I cannot convert a System.String into System.Collections.IDictionary!" (which means any of those compatible types listed under "Derived", as mentioned earlier.)
So, this is the detailed explanation for your question above.
The short answer is this:
Yes, it is valid to send the header using a [hashtable] (or [ordered] - or any other collection type from the Derived list.)
In fact, it's more than "valid", it's required that you use a hash table (in contrast to a string, which will not work, as you're already seeing), as per the specification within the Microsoft Docs for Invoke-RestMethod.
So, get rid of the "| ConvertTo-Json" statements from your "$Header" lines and everything will work the way you anticipated it would.
Here is your code adjusted to exclude the call to ConvertTo-Json on the $Header variable.
# $Headers hashtable
$Headers = [ordered]@{
"FTX-KEY" = $API;
"FTX-TS" = $FTX_TS;
"FTX-SIGN" = $Signature1;
"FTX_SubAccount" = $FTX_SubAccount}
$Headers
# The following Body is presented as JSON as expected
$Body = [ordered]@{
"market" = $Market;
"price" = $Price2;
"type" = $OrderType;
"size" = $Size} | ConvertTo-JSON -Compress
$Body # data presented as JSON as expected
Cheers,
Lain
- porkopopsMay 27, 2022Copper ContributorThanks for the detailed answer Lain. I appreciate it. I received an education on how to use the Microsoft documentation too, which I clearly needed 🙂
Thanks again