CodexBloom - Programming Q&A Platform

PowerShell 7.3 - implementing Using Invoke-RestMethod for API Requests with JSON Payload

πŸ‘€ Views: 251 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-10
powershell api json PowerShell

I'm stuck trying to I'm testing a new approach and I'm sure I'm missing something obvious here, but I'm struggling with sending a JSON payload to an API using `Invoke-RestMethod` in PowerShell 7.3... When I try to send the request, I receive a 400 Bad Request behavior, despite my payload looking correct. Here’s my code: ```powershell $Uri = "https://api.example.com/v1/resource" $Body = @{ name = "Sample Name" description = "This is a sample description." } | ConvertTo-Json $Headers = @{ 'Content-Type' = 'application/json' 'Authorization' = 'Bearer your_token_here' } $response = Invoke-RestMethod -Uri $Uri -Method Post -Body $Body -Headers $Headers ``` I've double-checked the API documentation, and it specifies that the payload should be in JSON format. However, the API responds with: ``` { "behavior": "Invalid input" } ``` I also tried using `-UseBasicPasing` flag, but it didn’t change the result. To debug, I printed the `$Body` variable and it shows: ```json { "name": "Sample Name", "description": "This is a sample description." } ``` It looks like the JSON is formatted correctly. I made sure to validate the endpoint and ensure that my token is still valid. Can someone guide to figure out what might be going wrong here? Is there something specific I should check regarding the headers or the JSON structure? Thanks in advance! This is my first time working with Powershell LTS. How would you solve this? I'd be grateful for any help. I'm working in a Linux environment. I'd be grateful for any help.