I am trying to send the content of a JSON file to an API using Invoke-WebRequest
. I have validated the JSON file and it's healthy. I can also send the JSON file successfully using a REST Client (Postman and Insomnia), so I know the JSON data and API are fine.
When I send the file using PowerShell, I get a 400 response 400: "The Request Content is not a valid JSON string"
.
I am loading the content of the file using Get-Content $File.FullName -Raw
, this seems to be where the issue is.
function Send-JSONFiles(){
$FilesToUpload = @(Get-ChildItem -Path "$ProgramPath\Uploads" -filter *.json)
$Target = "https://theapi.com/api"
Foreach ($File in $FilesToUpload){
if($Dev){Write-host "Sending" $File.FullName "to" $Target$URI}
Try{
Invoke-WebRequest -uri "$Target" -Method Post -ContentType "application/json" -Headers @{ "Authorization" = "bearer " + $Global:token; "Cache-Control" = "no-cache"; } -Body (Get-Content $File.FullName -Raw)
}Catch{
Write-host $_
Write-host $_.Exception.Response.StatusCode.Value__
Write-host ($_.ErrorDetails.Message).error
}
}
}
I would expect this to work the same as my REST clients. GEt the JSON data from the file and POST it to the target - I'm not sure why this would be breaking the JSON?