4

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?

1 Answer 1

14

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
Sign up to request clarification or add additional context in comments.

1 Comment

Note that if $data is an array you do not want to use a pipe, because null and empty arrays are not iterated with pipes, meaning that there will be no output. $null -eq (@() | ConvertTo-Json) #=> true. Instead pass it in as the first argument. ConvertTo-Json @() #=> "[]" and ConvertTo-Json $null #=> "null"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.