PowerShell Quick API Basic Function
Overview
Since I use this all the time and keep coming back to it, I figured it would be much easier to save the post, knowing that I'll need it at least ten more times this week. This only makes an API call for JSON formats and saving the object and extracting the information I need is easy from here.
Function Call-API {
Param(
[Parameter(Mandatory=$true)][string]$apiparam
)
Process
{
$apiwebclient = New-Object System.Net.WebClient
$resultset_json = $apiwebclient.DownloadString($apiparam) | ConvertFrom-Json
$apiwebclient.Dispose()
return $resultset_json
}
}
On my cloud VMs, I want to be as strict as possible with memory and CPU so that I can horizontally scale as needed. One trick I'll do here that you see is dispose everything that I create. Sometimes, I'll go a step further and flush everything at the end of my script:
[System.GC]::Collect()
In Practice (Blockchain) and Extended
Because the base function above this is easy, I can extend this further - using one of my favorite APIs - blockchain:
Function Extract-Blockchain {
Param(
[Parameter(Mandatory=$true)][string]$wallet
)
Process
{
$blockchainapi = "https://blockchain.info/address/" + $wallet + "?format=json&offset=0"
$extractall = New-Object System.Net.WebClient
$resultsetjson = $extractall.DownloadString($blockchainapi) | ConvertFrom-Json
$extractall.Dispose()
return $resultsetjson
}
}
$resultset = Extract-Blockchain -wallet $wallet
### In this example, these are the two pieces I'm looking for:
$resultset.txs.size
$resultset.txs.time
### My garbage collection
[System.GC]::Collect()
The key with the above is that it shows how easy it is to extend the base API function if needed, as the parameter string for the API will often be formatted differently. Since I like configuration tables or configuration files the most for re-usability, extending functions, building on top of functions, or making slight adjustments to them makes everything easy.
Upvoted you