Created
November 12, 2019 21:07
-
-
Save BrandonStiff/10f32d3fe1934cc353ffb0c882865784 to your computer and use it in GitHub Desktop.
Get the Weather using OpenWeatherMap API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Get-Weather | |
{ | |
<# | |
.SYNOPSIS | |
This function makes an API call to openweathermap.org and retrieves the weather for my city. | |
.PARAMETER Zip | |
Specifies the zip code to get the weather for. | |
.PARAMETER Unit | |
Specifies the temperature unit type. Allowed values: imperial (F) | metric (C) | standard (KELVIN) | |
Default is "imperial". | |
.OUTPUTS | |
[PSObject] | |
A PSObject as defined by openweathermap.org: https://openweathermap.org/current#current_JSON | |
.EXAMPLE | |
# Get the weather for Metamora | |
$weather = Get-Weather -Zip 48455 | |
# Show the temp range: | |
$weather.main | |
#> | |
[CmdletBinding()] | |
param | |
( | |
[Parameter(Mandatory)] | |
[string] $Zip, | |
[ValidateSet("imperial","metric","standard")] | |
[string] $Unit = "imperial" | |
) | |
# Get the API Key for authentication: | |
$apiKey = "" | |
if ( Test-Path -Path "./apikey.json" ) | |
{ | |
$apiKey = Get-Content -Path "./apikey.json" -Raw | ConvertFrom-Json | Select-Object -ExpandProperty "apiKey" | |
} | |
else | |
{ | |
throw ("Unable to find apikey.json in the current directory ($(Get-Location).Path)!") | |
} | |
# Construct the base URI: | |
# https://openweathermap.org/current | |
$uri = "https://api.openweathermap.org/data/2.5/weather" | |
# Add all of the URI parameters: | |
$uriParams = ` | |
@{ | |
"zip" = $Zip | |
"APPID" = $apiKey | |
"units" = $Unit | |
} | |
$uriParamString = @() | |
foreach ( $param in $uriParams.GetEnumerator() ) | |
{ | |
$uriParamString += "$($param.Key)=$($param.Value)" | |
} | |
# Join the two together: | |
$fullUri = "$uri`?$($uriParamString -join '&')" | |
# Make the API request: | |
$response = Invoke-WebRequest -Method GET -Uri $fullUri | |
if ( $response.StatusCode -ieq 200 ) | |
{ | |
# Success! | |
$response.Content | ConvertFrom-Json | |
} | |
else | |
{ | |
# Failed: | |
throw ("Unable to contact openweather API!`n$($response.Content)") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment