1

I am making an API call to a system that is supposed to return a list of names.

$headers=@{}
$headers.Add("Accept", "application/json;charset=UTF-8")

$headers.Add("Authorization", "secretkey")


$people= Invoke-RestMethod -Uri 'https://someAPI' -Method GET -Headers $headers

$people.fullname #Expecting names with åäö, but does not work.

When I use the API call on the developers website, it shows the people's names with ÅÄÖ , for instance, "Anna Ängberg" , but when I run the Invoke-RestMethod command in Powershell, the name becomes "Anna ängberg". Clearly an encoding issue.

How do I modify the script to force the encoding? There is no "encoding" flag to Invoke-RestMethod. I do not want to use Invoke-WebRequest because that does not return the result as a powershell object that I want to work with.

I have tried adding to Invoke-Restmethod the following:

 -ContentType "application/json;charset=UTF-8"
 -ContentType "application/json;charset=UTF-16"

And both forms in the Accept Header as well

Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206
Agneum
  • 727
  • 7
  • 23
  • In short: In the absence of `charset` information in the _response_ header, PowerShell interprets the string returned as ISO-8859-1-encoded. If the de-facto encoding differs (e.g, UTF-8) and you have no way of getting the service to include `charset` information to its response, you'll have to manually _re-encode_ the response string and decode it again - see the linked duplicate for details. – mklement0 Feb 10 '22 at 14:32
  • Okay, so seems I am forced with Invoke-WebRequest then. – Agneum Feb 10 '22 at 16:34
  • No, for one, Invoke-RestMethod does not support -ContentType. And I also believe it already returns a powershell object, not the raw JSON. So I'd have to convert from and to JSON multiple times. If I change it I instead get this error: "Exception calling "GetBytes" with "1" argument(s): "Array cannot be null. Parameter name: chars"". It's not a big deal, as | ConvertFrom-Json using the WebRequest method converts it back. – Agneum Feb 10 '22 at 16:53
  • Ah, good points - then using `Invoke-WebRequest` and re-encoding of the `.Content` string (as shown in the duplicate), and then applying `ConvertFrom-Json` is probably the better approach. – mklement0 Feb 10 '22 at 16:55
  • (As an inconsequential aside [`Invoke-RestMethod`](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/invoke-restmethod?view=powershell-5.1) does support `-ContentType`, as of at least v5.1) – mklement0 Feb 10 '22 at 17:00

0 Answers0