Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use JSON to Powershell Invoke-RestMethod?

I am trying to invoke the API using this request. This request is working fine in Postman. But how can I convert it to PowerShell Invoke-RestMethod?

This is what I tried.

$token = "abcdef123456"
$url = "https://example.com/OVAV1/triggercalls/1"
$header = @{"Authorization"='abdcdef123456'}

$body =
{
"requestid": "<Echo back field>",
"templatename": "Line_Down",
"templateid": "abcde12345",
"noofrecords": 1,
"variableinfo": [
{
"<<MOBILE_NUMBER>>": "123456789",
"<<UNIQUE_CALL_IDENTIFIER>>": "A001",
"<<LinkType>>": "PRI",
"<<HostName>>": "HOSTNAME"
}
]
}

$request = Invoke-RestMethod -Uri $url -Headers $header -Body $body -ContentType "application/json" -Method Post

$request

I tried the JSON code in Postman. It's working fine. How can I use the same JSON code in PowerShell?

like image 723
adj009 Avatar asked Sep 05 '25 03:09

adj009


1 Answers

You can't put JSON data into PowerShell code like that. Put it in a here-string and it should work:

$body = @"
{
    "requestid": "<Echo back field>",
    "templatename": "Line_Down",
    "templateid": "abcde12345",
    "noofrecords": 1,
    "variableinfo": [
        {
            "<<MOBILE_NUMBER>>": "123456789",
            "<<UNIQUE_CALL_IDENTIFIER>>": "A001",
            "<<LinkType>>": "PRI",
            "<<HostName>>": "HOSTNAME"
        }
    ]
}
"@

You could also define the data as a hashtable and convert it to a JSON string:

$data = @{
    "requestid"    = "<Echo back field>"
    "templatename" = "Line_Down"
    "templateid"   = "abcde12345"
    "noofrecords"  = 1
    "variableinfo" = @(
        @{
            "<<MOBILE_NUMBER>>"          = "123456789"
            "<<UNIQUE_CALL_IDENTIFIER>>" = "A001"
            "<<LinkType>>"               = "PRI"
            "<<HostName>>"               = "HOSTNAME"
        }
    )
}

$body = $data | ConvertTo-Json
like image 111
Ansgar Wiechers Avatar answered Sep 07 '25 19:09

Ansgar Wiechers