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

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

{ "@type":"login", "username":"", "password":"yyy"
}

How do I pass this in PowerShell?

3 Answers

You should be able to do the following:

$params = @{"@type"="login"; "username"=""; "password"="yyy";
}
Invoke-WebRequest -Uri -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 -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)

3

Use Invoke-RestMethod to consume REST-APIs. Save the JSON to a string and use that as the body, ex:

$JSON = @'
{"@type":"login", "username":"", "password":"yyy"
}
'@
$response = Invoke-RestMethod -Uri "" -Method Post -Body $JSON -ContentType "application/json"

If you use Powershell 3, I know there have been some issues with Invoke-RestMethod, but you should be able to use Invoke-WebRequest as a replacement:

$response = Invoke-WebRequest -Uri "" -Method Post -Body $JSON -ContentType "application/json"

If you don't want to write your own JSON every time, you can use a hashtable and use PowerShell to convert it to JSON before posting it. Ex.

$JSON = @{ "@type" = "login" "username" = "" "password" = "yyy"
} | ConvertTo-Json
0

@Frode F. gave the right answer.

By the Way Invoke-WebRequest also prints you the 200 OK and a lot of bla, bla, bla... which might be useful but I still prefer the Invoke-RestMethod which is lighter.

Also, keep in mind that you need to use | ConvertTo-Json for the body only, not the header:

$body = @{ "UserSessionId"="12345678" "OptionalEmail"=""
} | ConvertTo-Json
$header = @{ "Accept"="application/json" "connectapitoken"="97fe6ab5b1a640909551e36a071ce9ed" "Content-Type"="application/json"
}
Invoke-RestMethod -Uri "" -Method 'Post' -Body $body -Headers $header | ConvertTo-HTML

and you can then append a | ConvertTo-HTML at the end of the request for better readability

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like