Weather::WeatherKit - Apple WeatherKit REST API client
use Weather::WeatherKit;
my $wk = Weather::WeatherKit->new(
team_id => $apple_team_id, # Apple Developer Team Id
service_id => $weatherkit_service_id, # WeatherKit Service Id
key_id => $key_id, # WeatherKit developer key ID
key => $private_key # Encrypted private key (PEM)
);
# Request current weather:
my $report = $wk->get(
lat => $lat, # Latitude
lon => $lon, # Longitude
dataSets => 'currentWeather'
);
# Request forecast for 8 days, use Weather::API::Base helper functions
# for ISO dates, and get full HTTP::Response object to check for success
use Weather::API::Base qw(:all);
my $response = $wk->get_response(
lat => $lat,
lon => $lon,
dataSets => 'forecastHourly',
hourlyStart => ts_to_iso_date(time()),
hourlyEnd => ts_to_iso_date(time()+8*24*3600)
);
if ($response->is_success) {
my $json = $response->decoded_content;
} else {
die $response->status_line;
}
Weather::WeatherKit provides basic access to the Apple WeatherKit REST API (v1). WeatherKit replaces the Dark Sky API and requires an Apple developer subscription.
Pease see the official API documentation for datasets and usage options as well as the required attribution.
It was made to serve the apps Xasteria and Polar Scope Align, but if your service requires some extra functionality, feel free to contact the author about it.
my $wk = Weather::WeatherKit->new(
team_id => "MLU84X58U4",
service_id => "com.domain.myweatherapp",
key_id => $key_id,
key => $private_key?,
key_file => $private_key_pem?,
language => $lang_code?,
timeout => $timeout_sec?,
expiration => $expire_secs?,
ua => $lwp_ua?,
curl => $use_curl?
);
Required parameters:
team_id
: Your 10-character Apple developer Team Id - it can be located on the Apple developer portal.service_id
: The WeatherKit Service Identifier created on the Apple developer portal. Usually a reverse-domain type string is used for this.key_id
: The ID of the WeatherKit key created on the Apple developer portal.key_file
: The encrypted WeatherKit private key file that you created on the Apple developer portal. On the portal you download a PKCS8 format file (.p8), which you first need to convert to the PEM format. On a Mac you can convert it simply:openssl pkcs8 -nocrypt -in AuthKey_<key_id>.p8 -out AuthKey_<key_id>.pem
key
: Instead of the.pem
file, you can pass its contents directly as a string. If both are providedkey
takes precedence overkey_file
.
Optional parameters:
language
: Language code. Default:en_US
.timeout
: Timeout for requests in secs. Default:30
.ua
: Pass your own LWP::UserAgent to customise the agent string etc.curl
: If true, fall back to using thecurl
command line program. This is useful if you have issues adding http support to LWP::UserAgent, which is the default method for the WeatherKit requests. It assumes thecurl
program is installed in$PATH
.expiration
: Token expiration time in seconds. Tokens are cached until there are less than 10 minutes left to expiration. Default:7200
.
my $report = $wk->get(
lat => $lat,
lon => $lon,
dataSets => $datasets
%args?
);
my %report = $wk->get( ... );
Fetches datasets (weather report, forecast, alert...) for the requested location. Returns a string containing the JSON data, except in array context, in which case, as a convenience, it will use JSON to decode it directly to a Perl hash.
Requires LWP::UserAgent, unless the curl
option was set.
If the request is not successful, it will die
throwing the HTTP::Response->status_line
.
lat
: Latitude (-90 to 90).lon
: Longitude (-18 to 180).dataSets
: A comma-separated string of the dataset(s) you request. Example supported data sets:currentWeather, forecastDaily, forecastHourly, forecastNextHour, weatherAlerts
. Some data sets might not be available for all locations. Will return empty results if parameter is missing.%args
: See the official API documentation for the supported weather API query parameters which you can pass as key/value pairs.
my $response = $wk->get_response(
lat => $lat,
lon => $lon,
dataSets => $datasets
%args?
);
Same as get
except it returns the full HTTP::Response from the API (so you can handle bad requests yourself).
my $jwt = $wk->jwt(
iat => $iat?,
exp => $exp?
);
Returns the JSON Web Token string in case you need it. Will return a cached one if it has more than 10 minutes until expiration and you don't explicitly pass an exp
argument.
iat
: Specify the token creation timestamp. Default istime()
.exp
: Specify the token expiration timestamp. Passing this parameter will force the creation of a new token. Default istime()+7200
(or what you specified in the constructor).
The parent class Weather::API::Base contains some useful functions e.g.:
use Weather::API::Base qw(:all);
# Get time in ISO (YYYY-MM-DDTHH:mm:ss) format
my $datetime = ts_to_iso_date(time());
# Convert 30 degrees Celsius to Fahrenheit
my $result = convert_units('C', 'F', 30);
See the doc for that module for more details.
Although WeatherKit is supposed to provide 10 days of forecast, at some point users started getting 400
errors when requesting (e.g. with hourlyEnd
) more than 8 or 9 days of forecast. If you encounter this issue, limit your forecast request to 9 or 8 days in the future.
Some Perl modules for current weather and forecasts from other sources:
OpenWeatherMap uses various weather sources combined with their own ML and offers a couple of free endpoints (the v2.5 current weather and 5d/3h forecast) with generous request limits. Their newer One Call 3.0 API also offers some free usage (1000 calls/day) and the cost is per call above that. If you want access to history APIs, extended hourly forecasts etc, there are monthly subscriptions. Weather::OWM is from the same author as this module and similar in use.
The 7Timer! weather forecast is completely free and would be of extra interest if you are interested in astronomy/stargazing. It uses the standard NOAA forecast, but also calculates astronomical seeing and transparency. It can be accessed with Weather::Astro7Timer, which is another module similar to this (same author).
Dimitrios Kechagias, <dkechag at cpan.org>
Please report any bugs or feature requests either on GitHub (preferred), or on RT (via the email bug-weather-weatherkit at rt.cpan.org
or web interface).
I will be notified, and then you'll automatically be notified of progress on your bug as I make changes.
https://github.com/dkechag/Weather-WeatherKit
This software is copyright (c) 2023 by Dimitrios Kechagias.
This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.