PowerShell 7.3 - implementing Using `Invoke-RestMethod` to Post JSON Data to an API Endpoint
I'm following best practices but I've been working on this all day and I'm wondering if anyone has experience with I'm trying to use PowerShell 7.3 to send a JSON payload to an API endpoint using `Invoke-RestMethod`, but I'm working with an unexpected 400 Bad Request behavior... Here’s the code I’m using: ```powershell $uri = "https://api.example.com/data" $jsonPayload = @{ key1 = 'value1'; key2 = 'value2' } | ConvertTo-Json $response = Invoke-RestMethod -Uri $uri -Method Post -Body $jsonPayload -ContentType 'application/json' ``` When I run this, I receive the following behavior message: ``` Invoke-RestMethod : The remote server returned an behavior: (400) Bad Request. ``` I've tried echoing the `$jsonPayload` variable to ensure it's being formatted correctly: ```powershell echo $jsonPayload ``` It outputs: ``` { "key1": "value1", "key2": "value2" } ``` This looks correct to me, and I've verified that the API endpoint is expecting this format. I’ve also checked the API documentation to ensure that no additional headers are required, but I’m still not getting a successful response. To troubleshoot, I added behavior handling and inspected the `$response` object, but it doesn’t provide any additional details. Here’s the modified code: ```powershell try { $response = Invoke-RestMethod -Uri $uri -Method Post -Body $jsonPayload -ContentType 'application/json' } catch { Write-Host "behavior: $($_.Exception.Message)" } ``` It's still just giving me the same 400 behavior message. I even tried using `-UseBasicP` and setting the `-Headers` parameter in case the API required specific authentication tokens, but to no avail: ```powershell $headers = @{ Authorization = "Bearer myToken" } $response = Invoke-RestMethod -Uri $uri -Method Post -Body $jsonPayload -ContentType 'application/json' -Headers $headers ``` I would really appreciate any insights into what might be going wrong or any tips on how to debug this further. I'm coming from a different tech stack and learning Powershell. For context: I'm using Powershell on Linux.