0

Hi I am trying to execute below ways to run the POST call in power shell

option 1:

$Body="{ \`"cartItem\`" : {\`"sku\`" : \`"RG1219013\`", \`"qty\`" : \`"1\`",  \`"quoteId\`" : \`"QRAeZdoFbieEWHjrRs5X0G1tHRE4el30\`"  }}"

option 2:

$Body=@"
{ \"cartItem\" : {\"sku\" : \"RG1219013\", \"qty\" : \"1\",  \"quoteId\" : \"QRAeZdoFbieEWHjrRs5X0G1tHRE4el30\"  }}
"@

option3 :

$Body = @{
    cartItem =
    {
        sku = 'RG1219013'
        qty = '1'
        quoteId = 'QRAeZdoFbieEWHjrRs5X0G1tHRE4el30'
    }
} 

$Json = (ConvertTo-Json $Body)

Execute:

$Header = @{ "Content-Type" = "application/json" }
Invoke-RestMethod -Method Post -Body $Body -Uri $UriAddtoCart -Header $Header

In option 1 and option 2 I am getting Bad request (400) and option 3 it's internal error (500)

Below jason respond successfully through postman

{
    "cartItem" :
    {
        "sku" : "RG1219013",
        "qty" : "1",
        "quoteId" : "QRAeZdoFbieEWHjrRs5X0G1tHRE4el30"
    }
}

Is there anything missing here?

5
  • option 3 looks fine, option 1 and 2 are tricky to escape correctly so i'd prefer option3 other theese. error 500 means something on the server-side is going wrong and does not neccesairily mean your request or json is bad. do you get any error message from that webservice ? are you missing something in the header ? Commented Jul 6, 2019 at 11:28
  • @D.J.Yes I get the response when I tried same thing with Postman. Only that Content-Type header is there Commented Jul 6, 2019 at 11:39
  • 5
    You missing a @ sign after cartItem = in option 3 (this way you assign it a function), Thus: cartItem = {... should be: cartItem = @{... (check the actual content of the $Json file) Commented Jul 6, 2019 at 11:48
  • @iRon That's it. All good. Commented Jul 6, 2019 at 12:04
  • 1
    @iRon you should post that as an answer Commented Jul 6, 2019 at 12:39

1 Answer 1

1

The Json file is missing a @ sign after cartItem = in option 3 (this way a function is assigned to the cartItem property rather than a HashTable)
This will get clear if you output the $Json file (e.g. Write-Host $Json).

Thus:

$Body = @{
    cartItem =
    {
        sku = 'RG1219013'
        ...

Should be:

$Body = @{
    cartItem =
    @{
        sku = 'RG1219013'
        ...
Sign up to request clarification or add additional context in comments.

Comments

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.