Use PowerShell to interact with REST APIs

API's are quickly becoming foundational for every SaaS product out there. They provide a gateway into interacting with the product without having to go through the exercise of a full integration with the product. You can use all kinds of methods and code languages to interact with APIs. This is just how PowerShell does it.


param(
    [Parameter(Mandatory=$true)]
    [string] $accountEndpoint = "",
    
    [Parameter(Mandatory=$true)]
    [string] $client_id = "",
    
    [Parameter(Mandatory=$true)]
    [string] $client_secret = ""
)
$DateStamp = get-date -uformat "%Y-%m-%d@%H-%M-%S"

$token = Invoke-RestMethod -Method Post -Uri "https://$($accountEndpoint)/auth/connect/token" `
    -Body @{
        grant_type="client_credentials";
        client_id=$client_id;
        client_secret=$client_secret;
        scope="api"
    }

Invoke-RestMethod -Method Get -Uri "https://api.cloudcheckr.com/api/best_practice.json/get_best_practices_v3?access_key=bearer $($token.access_token)&use_account=All%20Azure%20Accounts" | ConvertTo-Json | Out-File ".\data\azure_best_practice_checks_$($DateStamp).json"


Note: Invoke-RestMethod also assumes the output is converted from JSON into PowerShell objects, which is why I needed to convert it back. Invoke-WebRequest can also be used and is better for dealing with HTML results.


This example is to get Best Practice Checks available from Cloudcheckr. Cloudcheckr is a tool used to scan an Azure tenant, read all kinds of information about it, and display that information without having to login to the Azure Portal itself. It provides insight into and checks to ensure Best Practices are followed for things like, Network Security Groups having all inbound ports enabled-which is dumb, don't do dumb shit. It also scans VM's usage properties and offers suggestions for cost savings by reducing a VM's size or the possibility of combining workloads from multiple "idle" VMs. There are other tools out there that do this, like Flexera, and vCommander. These fall into the category of Cloud Management Platforms, and are a layer on top of Cloud resources that orchestrate, but allow a company like a Managed Services Provider to give access to Customer business units without having to onboard them directly into the native cloud environment.