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 30 degrees Celsius to Fahrenheit
my $result = convert_units('C', 'F', 30);
### 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 the response contents as a scalar or decoded to a data structure
sub get {
my $self = shift;
my $resp = shift;
return $self->_get_output($resp, wantarray);
}
DESCRIPTION
Weather::API::Base is a base class for simple Perl Weather API clients. Apart from handling JSON and XML API responses (JSON and XML::Simple required respectivelly), it offers utility functions for time and unit conversions, specifically useful for weather-related APIs.
This module was mainly created to streamline maintenance of the Weather::OWM, Weather::Astro7Timer and Weather::WeatherKit modules by factoring out shared code. In the unlikely event that you'd like to base your own weather or similar API wrapper module on it, look at the implementation of those modules for guidance.
CONSTRUCTOR
new
my $base = Weather::API::Base->new(
timeout => $timeout_sec?,
agent => $user_agent_string?,
ua => $lwp_ua?,
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 the base class sets these defaults:
(
timeout => 30,
agent => "libwww-perl $package/$version",
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($response, wantarray);
$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 speed: km/h, mph, m/s, Bft, kt
Temp: K, F, C
Rainfall & distance: mm, in, m, km, mi
Pressure: atm, mbar, mmHg, kPa, hPa
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. For example convert_units('km/h', 'mm', 10)
will croak with the speed units (km/h, mph, m/s, Bft, kt) that are available to convert from km/h.
Note that the Beaufort scale (Bft
) is an empirical scale commonly used in 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 timestamps 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.