Making a PowerShell invoke-restmethod request

2.2k views Asked by At

I have been challenged to get a response from an api with powershell.

I have little to no experience with powershell, but have at least been able to get a response from the API provider, but not a response i can use, so i hope someone can help me. The photo is of the documentaion i have Documentation

What i can't figure out is how i send the message that i want a response for. The command is the specific api that i need to use, and it has some inputs as seen in the photo.

Input to API: StreetName BuildingIdentifier Floor Suite DistrictCode

This is what i got so far.

$uri = 'SomeUrl.com'
$command = '/Ois/RealUnit/Address'
$token = 'SomeSecureToken'
$contentType = 'application/json'
$secureToken = ConvertTo-SecureString $token -AsPlainText -force


$webResult = Invoke-RestMethod -Method get -Uri $uri -ContentType $contentType -Token $secureToken
write-output $webResult

What i know but i don't know how to use or i it has to be used is as follows.

  • Request URL: https://SomeUrl.com/Ois/RealUnit/Address
  • Response body: is JSON and i only need the response for "unitUse"
  • Response Code: I also know that a good response gives the code 200
  • Curl: I also know that something called CURL looks a bit like this curl -X POST --header 'Content-Type: application/x-www-form-urlencoded' --header 'Accept: application/json' -d 'StreetName=STREET&BuildingIdentifier=123&Floor=12&Suite=th&DistrictCode=1234' 'https://SomeUrl.com/Ois/RealUnit/Address'
  • Reponse Header: Looks like this { "access-control-allow-headers": "Content-Type", "access-control-allow-methods": "GET, POST, PUT, DELETE, PATCH, OPTIONS", "access-control-allow-origin": "*", "cache-control": "private", "content-length": "7604", "content-type": "application/json; charset=utf-8", "date": "Tue, 08 Mar 2022 13:21:27 GMT", "server": "Microsoft-IIS/8.5", "strict-transport-security": "max-age=31536000", "vary": "Accept", "x-aspnet-version": "4.0.30319", "x-powered-by": "ServiceStack/5.10 NET45 Win32NT/.NET, ASP.NET" }
1

There are 1 answers

3
Hofa On
$uri = 'https://SomeUrl.com/Ois/RealUnit/Address'
$token = 'SomeSecureToken'
$contentType = 'application/json'
$secureToken = ConvertTo-SecureString $token -AsPlainText -force
$Body = @{
    StreetName = "STREET"
    BuildingIdentifier = 123
    Floor = 12
    Suite = "th"
    DistrictCode = 1234
}

$webResult = Invoke-RestMethod -Method POST -Uri $uri -ContentType $contentType -Token $secureToken -Body $Body
write-output $webResult

I can't really remember if you have to convert body to JSON data or if the 'Invoke-RestMethod' does it automatically. In any case: this is how you could do it:

$webResult = Invoke-RestMethod -Method POST -Uri $uri -ContentType $contentType -Token $secureToken -Body ($Body | ConvertTo-Json)