param( [Parameter(Mandatory = $true, HelpMessage="CIS userid to authenticate with")] [string] $cisuserid, [Parameter(Mandatory = $true, HelpMessage="CIS password to authenticate with")] [string] $cispassword ) # Sample PowerShell script to highlight REST API interactions # This script will: # - list state resources # - check if a given state resource exists # - create a new state resource # - update the state description (using PUT and also PATCH) # - delete the state resource #--- Start of invalid SSL certificate hack # This stuff here is just to make it work with a non-valid SSL certificate, like self-signed ones. # Would not be needed on a "real" production site with a valid, professional SSL certificate add-type @" using System.Net; using System.Security.Cryptography.X509Certificates; public class TrustAllCertsPolicy : ICertificatePolicy { public bool CheckValidationResult( ServicePoint srvPoint, X509Certificate certificate, WebRequest request, int certificateProblem) { return true; } } "@ [System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy #--- End of invalid SSL certificate hack # Advanced REST Web API URL to call $restApiRoot = 'https://myrestapi.com' # create HTTP Basic Auth header using cis userid and password $authHeader = 'Basic ' + [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($cisuserid + ':' + $cispassword)) # create HTTP headers dictionary, and include additional headers to indicate type of request and type of response desired $headers = @{'Authorization' = $authHeader; 'Content-Type' = 'application/json'; 'Accept' = 'application/json'} $result = $null # === GET LIST # Get a list of states (using optional querystrings for page number, page size, order, and filter condition try { # request page 1 with pagesize set to 5 for any states with code greater than OH, and sort the results by state code descending $url = $restApiRoot + "/data/state" $url = $url + "?" # append querystring separator $url = $url + "page=1" # optional querystring to select page number (default 1) $url = $url + "&pagesize=5" # optional querystring to select page size (default 50) $url = $url + "&order=-code" # optional querystring to specify output sort order (code descending, default is O_Key ascending) $url = $url + "&where=code gt 'OH'" # optional querystring to filter the selection using basic ODATA expression syntax $result = Invoke-RestMethod -Method Get -Uri $url -Headers $headers } catch { write-host "Invoke-RestMethod (GET list) failed with message: '" $_ "'" } if ($result -ne $null) { # parse the response contents as needed - it is already converted to a powershell object! #Get number of items $count = $result._embedded.state.Count write-host "Request returned $count state items" write-host "First state returned was " $result._embedded.state[0].code "/" $result._embedded.state[0].description write-host "Last state returned was " $result._embedded.state[$count-1].code "/" $result._embedded.state[$count-1].description } # === GET ONE $state1 = $null # Get a single state resource - eg the 'CA' resource (California) try { $url = $restApiRoot + "/data/state/CA" $result = Invoke-RestMethod -Method Get -Uri $url -Headers $headers } catch { write-host "Invoke-RestMethod (GET one) failed with message: '" $_ "'" } if ($result -ne $null) { # parse the response contents as needed - it is already converted to a PowerShell object! if ($result.code -eq "CA") { write-host "State resource CA successfully retrieved" write-host "O_Key (PK) = " $result.O_Key } else { write-host "State resource CA was not returned" } } # === POST # Create a new state object with code 'Z1' and description 'Test - delete me' $state1 = @{} $state1.code = "Z9" $state1.description = "Z9 test - delete me" $state1.disabled = $true $newurl = $null $statejson = convertto-json $state1 try { $url = $restApiRoot + "/data/state" $result = Invoke-WebRequest -Method Post -Uri $url -Headers $headers -Body $statejson if ($result.StatusCode -eq 201) { # response header "Location" property indicates the URL of the newly created resource $newurl = $result.Headers.Location # Since the Advanced REST API returns the full new object in the response as well, you could also retrieve the self link from that... $state1 = convertfrom-json $result.content $newurl = $state1._links.self # since the O_Code of the new object represents its resource id, we could also use that to infer the new resource URL... $newurl = $restApiRoot + "/data/state/" + $state1.o_Code Write-Host "New state resource created: " $newurl } } catch { write-host "Invoke-WebRequest (POST) failed with message: '" $_ "'" $state1 = $null $newurl = $null } if ($newurl -ne $null) { # === PUT # Update the newly created state object by adjusting the description using PUT # (normally we would do a GET on the resource first, but we already have the current resource so we'll skip getting it again) $state1.description = $state1.description + " too" $statejson = ConvertTo-Json $state1 try { $result = Invoke-WebRequest -Method Put -Uri $newurl -Headers $headers -Body $statejson if ($result.StatusCode -eq 200) { Write-Host "State resource $newurl successfully updated via PUT" } else { Write-Host "State resource $newurl failed to update with PUT: response code $($result.StatusCode)" } } catch { write-host "Invoke-WebRequest (PUT) failed with message: '" $_ "'" } # === PATCH # Update the newly created state object by adjusting the description using PATCH # PATCH has many variations and powerful features - we will simply instruct it to update the description and disabled flags using op/replace $patch1 = @{ op = "replace"; path = "/description"; value = "new description 2"} $patch2 = @{ op = "replace"; path = "/disabled"; value = $false} $patchjson = ConvertTo-Json ($patch1, $patch2) try { $result = Invoke-WebRequest -Method Patch -Uri $newurl -Headers $headers -Body $patchjson if ($result.StatusCode -eq 200) { Write-Host "State resource $newurl successfully updated via PATCH" } else { Write-Host "State resource $newurl failed to update with PATCH: response code $($result.StatusCode)" } } catch { write-host "Invoke-WebRequest (PATCH) failed with message: '" $_ "'" } # === DELETE # Delete the newly created state resource again to clean up try { $result = Invoke-WebRequest -Method Delete -Uri $newurl -Headers $headers if ($result.StatusCode -eq 200 -or $result.StatusCode -eq 204) { Write-Host "State resource $newurl successfully deleted" } else { Write-Host "State resource $newurl failed to delete: response code $($result.StatusCode)" } } catch { write-host "Invoke-WebRequest (DELETE) failed with message: '" $_ "'" } }