Powershell Invoke-Restmethod w/ JSON Body

59 Views Asked by At

Hope someone can help.

I'm trying to send a REST POST message using the Invoke-Rest method command to a sms service. When I use postman to send the request I'm able to send the message. However, when I try to do it in powershell I keep getting the following error and I'm unable to figure it out:

Invoke-RestMethod : {"error":"Validation error"}
At C:\Users\MTROTT\OneDrive - Volvo Cars\Projects\SMS API\mike.ps1:15 char:1
+ Invoke-RestMethod -Uri "$url" -Method Post -Body $mike -ContentType " ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
    + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand

I'm using the below code:

$url = "https://1234.com/api/send"

# Define the JSON body of the POST request
$body_json = [ordered]@{
    "apikey" = "KEY"
    "from" = "FRNR"
    "to" = "TONR"
    "message" = "test"
    "twoway" = "false"
    "conversation" = "CONV123"
    "checknumber" = "true"
} | ConvertTo-Json

Invoke-RestMethod -Uri $url -Method Post -Body $body_json -ContentType "application/json"

Kinda new to this so I would appreciate any help I can get.

Let me know if you need more info8 :)

I've tried Invoke-Webrequest but still the same result.

1

There are 1 best solutions below

2
Douda On

I'd assume it's linked to the way you handle your body, and you don't have any headers to send your query

Also don't believe you need a ordered hashtable to do that

$url = "https://1234.com/api/send"

$headers = @{
    "Authorization" = "your token if you need to use it"
    "Content"       = 'application/json' # If the content type needs to be setup in the header instead. Otherwise you can delete this line
}

$body = @{
    apikey       = "KEY"
    from         = "FRNR"
    to           = "TONR"
    message      = "test"
    twoway       = "false"
    conversation = "CONV123"
    checknumber  = "true"
} 

$params = @{
    Method      = 'POST'
    Uri         = $url
    headers     = $headers
    Body        = $body | ConvertTo-Json
    ContentType = 'application/json'
}

Invoke-RestMethod @params

PS: I would also confirm where you need to setup your token. Most likely not in the body, but in the header. Check the documentation of your api, you feel free to provide it in comments below