Post request to rest API using powerhsell
Posted: 2023-Sep-01, 7:19 pm
Hi everyone,
New to powerhsell.
Have this json file: Cannot change json as the api is implemented on this.
Created hashtable using powerhsell as:
Powershell Code to post data:
Now when I run this script, it gives the below error. However, the $response shows both ids and Name fine. The data didn't post to the url though.
New to powerhsell.
Have this json file: Cannot change json as the api is implemented on this.
Code: Select all
[
{
"Id": "yourfirstid",
"Name": "Alex"
},
{
"Id": "yoursecondid",
"Name": "Peter"
}
]
Code: Select all
$Body = {@{Id=yourfirstid; Name=Alex}, @{Id=yoursecondid; Name=Peter}}
Code: Select all
$token = "somevalue"
$url= "http://somepath"
$headers = @{Authorization = "Bearer $token"}
$Body = {@{Id=yourfirstid; Name=Alex}, @{Id=yoursecondid; Name=Peter}}
$JsonBody = $Body | ConvertTo-Json
$response = Invoke-RestMethod -ContentType "application/json" -Uri $url -Method Post -Headers $headers -Body $JsonBody
Write-Output $response
Code: Select all
Invoke-RestMethod : The remote server returned an error: (409) Conflict.
At C:\Users\test\Documents\PostData.ps1:9 char:13
+ $response = Invoke-RestMethod -ContentType "application/json" -Uri $u ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand