Public API: Example data retrieval script

Overview

Requirements

Script example

Attachments

Overview

This is a practical example of how to use API calls through a PowerShell script. The logic in this script can also be adapted for use in other scripting or programming languages, such as Python. The PowerShell file can be downloaded under the Attachments.

The script is built to retrieve a list of available / configured environments. To learn more about environments, see Environments. It's configured to ignore certificate errors if you are using a self-signed certificate. For details on certificates, see Managing Certificates. You can utilize the authentication mechanisms within the script for any API endpoint. Depending on the specific API call, you can modify or retrieve data. 

Requirements

To run the script, you will need the following:

Script example

# basic information
# role based access API
[string]$publicApiSecret = 'Mrayu0uASFiMR_sXf1Lcsz9VJbZB3vsl9erban8yvMk'

#url without https
$baseUrl = 'loginenterprise.my.url'

# if something goes wrong (e.g. authentication) we stop processing this script
$ErrorActionPreference = 'Stop'

# WARNING: ignoring SSL/TLS certificate errors is a security risk
$code = @"
public class SSLHandler
{public static System.Net.Security.RemoteCertificateValidationCallback GetSSLHandler()
{return new System.Net.Security.RemoteCertificateValidationCallback((sender, certificate, chain, policyErrors) => { return true; });}
}
"@
Add-Type -TypeDefinition $code

# WARNING: ignoring SSL/TLS certificate errors is a security risk
[System.Net.ServicePointManager]::ServerCertificateValidationCallback = [SSLHandler]::GetSSLHandler()


# this is only required for older version of PowerShell/.NET
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls -bor [Net.SecurityProtocolType]::Tls11 -bor [Net.SecurityProtocolType]::Tls12

# Define authorization header
$Header = @{
"Accept" = "application/json"
"Authorization" = "Bearer $publicApiSecret"
}

# Define body contents
$Body = @{
"orderBy" = "Name"
"direction" = "desc"
"count" = "20"
}

#Parameters of the API command
$Parameters = @{
Uri = 'https://' + $baseUrl + '/publicApi/v6/tests/'
Headers = $Header
Method = 'GET'
body = $Body
ContentType = 'application/json'
}

#request data with call to the public api environments URL
$Results = Invoke-RestMethod @Parameters

#display each environment in the results
ForEach ($item in $Results.items)
{
Write-Host $item
}

Attachments