Making a PowerShell POST request if a body param starts with '@'

live2learn picture live2learn · Mar 1, 2016 · Viewed 134.5k times · Source

I want to make a POST request in PowerShell. Following is the body details in Postman.

{
  "@type":"login",
  "username":"[email protected]",
  "password":"yyy"
}

How do I pass this in PowerShell?

Answer

Harald F. picture Harald F. · Mar 1, 2016

You should be able to do the following:

$params = @{"@type"="login";
 "username"="[email protected]";
 "password"="yyy";
}

Invoke-WebRequest -Uri http://foobar.com/endpoint -Method POST -Body $params

This will send the post as the body. However - if you want to post this as a Json you might want to be explicit. To post this as a JSON you can specify the ContentType and convert the body to Json by using

Invoke-WebRequest -Uri http://foobar.com/endpoint -Method POST -Body ($params|ConvertTo-Json) -ContentType "application/json"

Extra: You can also use the Invoke-RestMethod for dealing with JSON and REST apis (which will save you some extra lines for de-serializing)