0

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?

Arbiter
  • 450
  • 5
  • 26
  • 1
    To see what request is really being sent, use a tool such as [Fiddler](https://stackoverflow.com/q/24936541/503046). Maybe there's something wrong with headers or payload data is converted incorrectly upon reading. – vonPryz Jun 14 '19 at 11:24
  • @vonPryz Thanks, that's a great idea - I've not used a tool like this before, thanks for the link – Arbiter Jun 14 '19 at 11:41
  • You can also use online tools like [this](https://webhook.site/) to test your requests (of course redact personal/confidential data first) and quickly compare how they look. – Robert Dyjas Jun 14 '19 at 11:56

0 Answers0