Post request to rest API using PowerShell

Microsoft Windows
Post Reply
QATest
Posts: 1
Joined: 2023-Sep-01, 7:03 pm

Post request to rest API using PowerShell

Post by QATest »

Hi everyone,

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"
  }
]
Created hashtable using powerhsell as:

Code: Select all

$Body = {@{Id=yourfirstid; Name=Alex}, @{Id=yoursecondid; Name=Peter}}
Powershell Code to post data:

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
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.

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
Last edited by Simon Sheppard on 2023-Oct-17, 11:24 am, edited 1 time in total.
Reason: typo
User avatar
Simon Sheppard
Posts: 190
Joined: 2021-Jul-10, 7:46 pm
Contact:

Re: Post request to rest API using PowerShell

Post by Simon Sheppard »

I don't know what's wrong with your script, but you might find it helpful to compare it with this example over on StackOverflow:
https://stackoverflow.com/questions/677 ... ested-json
Post Reply