Do you must combine exterior information from internet companies into your PowerShell scripts? On this sensible tutorial, you’ll learn to question REST APIs utilizing PowerShell and parse the outcomes with none fuss. We’ll construct a reusable software that handles errors gracefully and returns clear, structured information.
Let’s discover this by working with a free API from postcodes.io that gives UK postal code information.
The Fundamentals: Making Your First API Name
The best solution to question a REST API with PowerShell is utilizing the Invoke-WebRequest
cmdlet. Consider it as a command-line internet browser – it reaches out to any URL and downloads no matter content material is accessible.
$outcome = Invoke-WebRequest -Uri 'http://api.postcodes.io/random/postcodes'
While you run this command, you’ll get again a number of properties, however an important ones are:
- StatusCode – Ought to be 200 for a profitable request
- Content material – The precise information returned by the API
Let’s take a look at what’s in that Content material property:
What you’ll see is JSON information containing postal code info. However there’s a catch – this content material is only a string:
$outcome.Content material.GetType().FullName
# Returns: System.String
To really work with this information in PowerShell, you must convert it from JSON to things. Right here’s how:
$objResult = $outcome.Content material | ConvertFrom-Json
$objResult.outcome
The Higher Method: Utilizing Invoke-RestMethod
Whereas Invoke-WebRequest
works, PowerShell has a greater cmdlet particularly designed for working with REST APIs: Invoke-RestMethod
. Right here’s the magic – it routinely converts JSON responses into PowerShell objects:
$response = Invoke-RestMethod -Uri 'http://api.postcodes.io/random/postcodes'
$response.outcome
A lot easier, proper? No guide JSON conversion wanted!
Constructing a Reusable Device
Let’s take this to the following degree and construct a reusable script. We’ll create a software that may:
- Settle for completely different API endpoints
- Deal with errors gracefully
- Return properly formatted outcomes
Right here’s our script (put it aside as Get-RandomPostCode.ps1):
[CmdletBinding()]
param(
[Parameter()]
[string]$Uri = 'http://api.postcodes.io/random/postcodes'
)
$response = Invoke-RestMethod -Uri $Uri -SkipHttpErrorCheck -StatusCodeVariable respStatus
if ($respStatus -ne 200) {
throw "API question failed: $_"
} else {
[PSCustomObject]@{
Postcode = $response.outcome.postcode
Nation = $response.outcome.nation
Area = $response.outcome.area
Latitude = $response.outcome.latitude
Longitude = $response.outcome.longitude
JSONFullResponse = $response
}
}
Let’s break down what this script does:
- Accepts a customized URI parameter with a default worth
- Makes use of -SkipHttpErrorCheck and -StatusCodeVariable for higher error dealing with
- Returns a clear customized object with simply the properties we care about
- Consists of the total JSON response if wanted for troubleshooting
To make use of the script:
# Get a random postcode utilizing the default API endpoint
.Get-RandomPostCode.ps1
# Strive a customized endpoint (this may exhibit error dealing with)
.Get-RandomPostCode.ps1 -Uri 'https://oops.postcodes.io'
A Word About Error Dealing with
In PowerShell 7+, now we have some good options for dealing with API errors. The -SkipHttpErrorCheck
parameter tells PowerShell to not throw errors into the error stream (avoiding that scary crimson textual content), whereas -StatusCodeVariable
lets us test the HTTP standing code ourselves.
If you happen to’re utilizing an older model of PowerShell, you need to use this various error dealing with strategy:
$ErrorActionPreference="Cease"
attempt {
$response = Invoke-RestMethod -Uri $Uri
$response.outcome
} catch {
throw "API question failed: $_"
}
Professional Suggestions
- At all times test the standing code – simply because an API responded doesn’t imply it labored
- Take into account returning customized objects as a substitute of uncooked API responses – it makes your scripts extra skilled and simpler to work with
- Embody the total API response in your output objects for troubleshooting
Subsequent Steps
Now that you know the way to work with REST APIs in PowerShell, you may:
- Combine information from any internet service into your scripts
- Construct wrapper capabilities on your favourite APIs
- Create instruments that mix information from a number of sources
The probabilities are infinite! Simply keep in mind – at all times test the API’s documentation for authentication necessities and price limits earlier than constructing manufacturing instruments.
What APIs are you planning to combine with PowerShell? Let me know within the feedback!