Invoke-WebRequest, POST with parameters

PowershellRest

Powershell Problem Overview


I'm attempting to POST to a uri, and send the parameter username=me

Invoke-WebRequest -Uri http://example.com/foobar -Method POST

How do I pass the parameters using the method POST?

Powershell Solutions


Solution 1 - Powershell

Put your parameters in a hash table and pass them like this:

$postParams = @{username='me';moredata='qwerty'}
Invoke-WebRequest -Uri http://example.com/foobar -Method POST -Body $postParams

Solution 2 - Powershell

For some picky web services, the request needs to have the content type set to JSON and the body to be a JSON string. For example:

Invoke-WebRequest -UseBasicParsing http://example.com/service -ContentType "application/json" -Method POST -Body "{ 'ItemID':3661515, 'Name':'test'}"

or the equivalent for XML, etc.

Solution 3 - Powershell

This just works:

$body = @{
 "UserSessionId"="12345678"
 "OptionalEmail"="[email protected]"
} | ConvertTo-Json
 
$header = @{
 "Accept"="application/json"
 "connectapitoken"="97fe6ab5b1a640909551e36a071ce9ed"
 "Content-Type"="application/json"
} 
 
Invoke-RestMethod -Uri "http://MyServer/WSVistaWebClient/RESTService.svc/member/search" -Method 'Post' -Body $body -Headers $header | ConvertTo-HTML

Solution 4 - Powershell

Single command without ps variables when using JSON as body {lastName:"doe"} for POST api call:

Invoke-WebRequest -Headers @{"Authorization" = "Bearer N-1234ulmMGhsDsCAEAzmo1tChSsq323sIkk4Zq9"} `
                  -Method POST `
                  -Body (@{"lastName"="doe";}|ConvertTo-Json) `
                  -Uri https://api.dummy.com/getUsers `
                  -ContentType application/json

See more: Power up your PowerShell

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionkylexView Question on Stackoverflow
Solution 1 - PowershellJellezillaView Answer on Stackoverflow
Solution 2 - PowershellrobView Answer on Stackoverflow
Solution 3 - PowershellFrancesco MantovaniView Answer on Stackoverflow
Solution 4 - PowershellGorvGoylView Answer on Stackoverflow