API examples using PowerShell

API examples using PowerShell

PowerShell is a powerful, cross-platform command-line shell and scripting language developed by Microsoft. It's built on the .NET framework, making it an excellent tool for automating system administration tasks, managing environments, and interacting with services.

This document will guide you through using a custom PowerShell module to interact with our API. By leveraging this module, you can streamline routine tasks, automate data retrieval, and manage resources efficiently, all from the command line.

Example PowerShell module for calling the SC//Reliantâ„¢ platform API

The following is a PowerShell module that can be used to make API calls on the command line. When using this module, simply add local environment variables named API_TOKEN and API_KEY with the authentication token and secret key provided to you by SC//Reliant.

# RPMAPI.psm1
function Get-RPMSignature {
    param(
        [string]$Path,
        [string]$Timestamp,
        [string]$SecretKey
    )
    $stringToSign = "$Path $Timestamp"
    $hmac = [System.Security.Cryptography.HMACSHA256]::new([System.Text.Encoding]::UTF8.GetBytes($SecretKey))
    $signatureBytes = $hmac.ComputeHash([System.Text.Encoding]::UTF8.GetBytes($stringToSign))
    return ($signatureBytes | ForEach-Object { "{0:x2}" -f $_ }) -join ""
}
function Invoke-RPMAPI {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [string]$Customer,
        [Parameter(Mandatory)]
        [ValidateSet("GET", "POST", "PUT", "PATCH", "DELETE")]
        [string]$Method,
        [Parameter(Mandatory)]
        [string]$Path,
        [string]$Params,
        [switch]$ShowVerbose
    )
    $Server = "https://platform.reliant.io/"
    if ($Server[-1] -ne "/") {
        throw "Server URL must end with a slash."
    }
    $Token = $env:API_TOKEN
    $SecretKey = $env:API_KEY
    if (-not $Token -or -not $SecretKey -or $Token -eq "..." -or $SecretKey -eq "...") {
        throw "Fill the API_KEY and API_TOKEN environment variables with your user data before proceeding."
    }
    $HeadersToDisplay = @("x-rate-limit", "x-current-rate", "retry-after")
    # Split path and query parameters
    $uriBuilder = [System.UriBuilder]::new($Server)
    if ($Path.StartsWith("/")) {
        $Path = $Path.Substring(1)
    }
    if ($Path -match "([^?]+)(\?(.*))?") {
        $purePath = $matches[1]
        $queryString = $matches[2]  # this does not have '?', but if it does, fix below
    } else {
        $purePath = $Path
        $queryString = $null
    }
    $uriBuilder.Path = $purePath
    if ($queryString) {
        # Just in case, trim leading '?'
        if ($queryString.StartsWith("?")) {
            $queryString = $queryString.Substring(1)
        }
        $uriBuilder.Query = $queryString
    }
    $uri = $uriBuilder.Uri.AbsoluteUri
    $timestamp = (Get-Date).ToString("o")
    # Calculate signature using pure path only
    $signature = Get-RPMSignature -Path "/$purePath" -Timestamp $timestamp -SecretKey $SecretKey
    $body = $null
    if ($Params) {
        try {
            $json = ConvertFrom-Json $Params
            $body = $json | ConvertTo-Json -Compress
        } catch {
            throw "Failed to parse parameters as JSON."
        }
    }
    # Setup headers
    $headers = @{
        "X-Auth-Token"    = $Token
        "X-Auth-Signature"= $signature
        "X-Timestamp"     = $timestamp
        "Content-Type"    = "application/json"
        "Accept"          = "application/vnd.reliantsec-v1+json"
        "X-Customer"      = $Customer
    }
    if ($ShowVerbose) {
        Write-Host "> Doing a request to '$uri'"
    }
    try {
        [Net.ServicePointManager]::Expect100Continue = $false
        $response = Invoke-RestMethod -Uri $uri -Method $Method -Body $body -Headers $headers -TimeoutSec 300 -ErrorAction Stop
        if ($ShowVerbose) {
            if ($response.PSObject.Properties) {
                Write-Host "< Response code: 200 (OK)"
                # Custom headers are not captured by Invoke-RestMethod; displaying them would require HttpWebRequest for full header access.
            }
        }
        $response | ConvertTo-Json -Depth 10
    } catch {
        if ($_.Exception.Response) {
            $reader = New-Object System.IO.StreamReader($_.Exception.Response.GetResponseStream())
            $responseBody = $reader.ReadToEnd()
            Write-Host "< HTTP Error: $($_.Exception.Response.StatusCode)"
            Write-Host $responseBody
        } else {
            throw $_
        }
    }
}
Export-ModuleMember -Function Invoke-RPMAPI

Using the PowerShell script

Once you have the PowerShell module saved in your development environment, you can use the following syntax to make calls against the SC//Reliant API. The file name you use for the PowerShell module is subjective, but our examples use RPMAPI.psm1.

  1. Open PowerShell.
  2. Import the RPMAPI.psm1 module into PowerShell.
    Import-Module -Name RPMAPI.psm1
  3. Use the Invoke-RPMAPI cmdlet with the -Customer, -Method, and -Path arguments to make the API call.
    Invoke-RPMAPI -Customer <customer_code> -Method <verb> -Path <api_endpoint>
    As an example, to list all locations for the sit tenant you would use the following PowerShell command.
    Invoke-RPMAPI -Customer sit -Method GET -Path api/locations
    You can also simply use Invoke-RPMAPI and PowerShell will prompt you for the required arguments.