CodexBloom - Programming Q&A Platform

PowerShell 7.3 - How to Properly Invoke a REST API with Authentication and Handle JSON Responses?

👀 Views: 11 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-05
PowerShell REST API JSON Authentication

I'm converting an old project and I'm working on a PowerShell script that needs to call a REST API requiring bearer token authentication... I've managed to get the token successfully, but I'm having trouble with the `Invoke-RestMethod` call to the API endpoint. The API returns JSON data, and I need to extract specific fields from this response. Here's the relevant part of my code: ```powershell # Get the bearer token $tokenResponse = Invoke-RestMethod -Uri 'https://api.example.com/token' -Method Post -Body 'client_id=your_client_id&client_secret=your_client_secret' -ContentType 'application/x-www-form-urlencoded' $bearerToken = $tokenResponse.access_token # Now, call the API with the token $headers = @{ 'Authorization' = "Bearer $bearerToken" } $response = Invoke-RestMethod -Uri 'https://api.example.com/data' -Method Get -Headers $headers ``` When I run this code, I get an behavior: `Invoke-RestMethod : The remote server returned an behavior: (401) Unauthorized.` I verified that the token is valid, as I'm able to call the token endpoint successfully and obtain a correct token. I've also checked the API documentation and it specifies that the `Authorization` header must be formatted correctly. I've tried debugging by printing the `$bearerToken` and comparing it to the expected token format, and everything looks fine. Additionally, I've tested the API with tools like Postman and it works without any issues. Is there something I'm missing in my PowerShell script, or could there be a specific requirement for the `Invoke-RestMethod` that I need to address? Any guidance on how to diagnose this scenario further would be greatly appreciated! I've been using Powershell for about a year now.