NAME
Weather::API::Base - Base/util module for Weather API clients
SYNOPSIS
### Using Helper Functions
use Weather::API::Base qw(:all);
# Get time in YYYY-MM-DD HH:mm:ss format, local time zone
my $datetime = ts_to_date(time());
# Convert a date to unix timestamp
my $ts = datetime_to_ts('2024-01-12 13:46:40');
# Convert 10 mph to kph
my $result = convert_units('mph', 'kph', 10);
### Building a Weather API client
use parent 'Weather::API::Base';
use Weather::API::Base qw(:all);
# Constructor
sub new {
my ($class, %args) = @_;
return $class->SUPER::new(%args);
}
# Getting an HTTP::Response
sub get_response {
my $self = shift;
my $url = shift;
return $self->_get_ua($url);
}
# Getting scalar contents or data structure from response
sub get {
my $self = shift;
my $resp = shift;
return $self->_get_output(wantarray, $resp);
}
DESCRIPTION
Weather::API::Base is a base class for simple Perl Weather API clients. Apart from handling JSON/XML API responses, it offers useful utility functions.
It was mainly created to make maintenance of Weather::OWM, Weather::Astro7Timer and Weather::WeatherKit easier by factoring out common code.
In the unlikely event that you'd like to base your own Weather or similar API module on it, look at those modules for more help on how to do it.
It is more useful as a util module for the time and unit conversion functions.
CONSTRUCTOR
new
my $base = Weather::API::Base->new(
timeout => $timeout_sec?,
agent => $user_agent_string?,
ua => $lwp_ua?,
units => $units?,
error => $die_or_return?,
debug => $debug?,
output => $output,
scheme => $url_scheme?
);
Creates a Weather::API::Base object. As explained, you'd normally use a module that inherits from this, but i base class sets these defaults:
(
timeout => 30,
agent => "libwww-perl $package/$version",
units => 'metric',
error => 'return',
output => 'json',
scheme => 'https',
);
Parameters:
timeout
: Timeout for requests in secs. Default:30
.agent
: Customize the user agent string. Default:libwww-perl $package/$version"
ua
: Pass your own LWP::UserAgent to customize further. Will overrideagent
.error
: If there is an error response with the main methods, you have the options todie
orreturn
it. Default:return
.debug
: If debug mode is enabled, API URLs accessed are printed in STDERR when calling_get_ua
. Default:false
.scheme
: You can usehttp
as an option if it is supported by the API and you have trouble building https support for LWP in your system. Default:https
.output
: Output format/mode.json/xml
are automatically supported for decoding. Default:json
.
PRIVATE METHODS
These are to be used when subclassing.
_get_output
$self->_get_output(wantarray, $response);
$response
should be an HTTP::Response object, unless $self-
{curl}> is true in which case it should be a string. On wantarray
a Perl hash (or array) will be returned by decoding a JSON/XML response (if $self-
{output}> is json/xml
) or just the decoded content as a value for the data
key otherwise.
_get_ua
my $resp = $self->_get_ua($url);
Will either use $self-
{ua}> or create a new one and fetch the $url
with it. If the URL does not contain the scheme, it will be applied from $self-
{scheme}>.
HELPER FUNCTIONS
Exportable helper/utility functions:
convert_units
my $result = convert_units($from, $to, $value);
Can convert from/to various units that are used in weather:
Wind: kmh, mph, m/s, Bft, knot
Temp: K, F, C
Rainfall & distance: mm, in, m, km, mi
Pressure: atm, mbar, mmHg, kPa
Use the above units as string parameters. Example:
$result = convert_units('atm', 'mmHg', 1); # Will return 760 (mmHg per 1 atm)
If you try to convert between non convertible units, the croak message will list the valid conversions from the 'from' units.
Note that the Beaufort scale (Bft
) is an empirical scale that is usually used as whole numbers (converting to a range of +/- 0.5 Bft in other units), but the convert function will actually give you the approximate floating point value based on an accepted empirical function.
ts_to_date
my $datetime = ts_to_date($timestamp, $utc?);
There are many ways to convert unix timestams to human readable dates, but for convenience you can use ts_to_date
, which is a very fast function that will return the format YYYY-MM-DD HH:mm:ss
in your local time zone, or YYYY-MM-DD HH:mm:ssZ
in UTC if the second argument is true.
datetime_to_ts
my $ts = datetime_to_ts($datetime, $utc?);
Fast function that accepts YYYY-MM-DD
or YYYY-MM-DD HH:mm:ssZ?
and converts to a timestamp (for midnight in the former case). Will use local timezone unless you either pass a true second argument or use datetime with the Z
(Zulu time) suffix. Accepts any date/time divider, so strict ISO with T
will work as well.
RELATED WEATHER MODULES
A quick listing of Perl modules that are based on Weather::API::Base:
Weather::Astro7Timer
If you are interested in astronomy/stargazing the 7Timer! weather forecast might be very useful. It uses the standard NOAA forecast, but calculates astronomical seeing and transparency. It is completely free, no API key needed.
Weather::OWM
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::WeatherKit
An alternative source for multi-source forecasts is Apple's WeatherKit (based on the old Dark Sky weather API). It offers 500k calls/day for free, but requires a paid Apple developer account.
AUTHOR
Dimitrios Kechagias, <dkechag at cpan.org>
BUGS
Please report any bugs or feature requests on GitHub.
GIT
https://github.com/dkechag/Weather-API-Base
LICENSE AND COPYRIGHT
This software is copyright (c) 2024 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.