3

I'm trying to get data back from an API online using Powershell with the command Invoke-WebRequest -UseBasicParsing $request_string -Method Get -Headers $headers) but am getting back Invoke-WebRequest : The remote server returned an error: (403) Forbidden.

I am supplying a $headers dictionary. Strangely, I can access the API using Postman, Python, and cURL. It's only when using Powershell commands that I get the 403 error. In fact, I used Postman's Code Snippet feature to generate my Powershell code, and it still doensn't work! Postman's Powershell Code Snippet was:

$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("Authorization", "Bearer {removed for security}")

$response = Invoke-RestMethod '{removed for security}' -Method 'GET' -Headers $headers
$response | ConvertTo-Json

To recap, both Invoke-WebRequest and Invoke-RestMethod don't work.

Any help here is much appreciated.

Thanks!

Christian Baumann
  • 3,188
  • 3
  • 20
  • 37
Python Developer
  • 551
  • 1
  • 8
  • 18
  • 1
    try this at the top of your script: [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12; – Gerrit Geeraerts Jul 08 '22 at 00:41
  • I tried it, but still get the same error. In fact, I tried all the options ("SystemDefault,Ssl3,Tls,Tls11,Tls12,Tls13") except for Ssl3 (because the protocol is not supported on my work computer), and all returned a 403 error. Any other suggestions? I appreciate the first one! – Python Developer Jul 08 '22 at 18:00
  • nvm, figured it out. see the answer – Python Developer Jul 08 '22 at 18:37

1 Answers1

1

Figured it out on my own.

The API vendor enforced https requirement instead of just http. Apparently, Postman, Python, and cURL can figure that out on their own and change the request accordingly, but Powershell cannot.

Python Developer
  • 551
  • 1
  • 8
  • 18