Feature documentation#
This section is a documentation of the weatherly API interface.
Version informations#
You can gather version info in two ways:
- weatherly.__version__#
Version of the project following the PEP 440 standard.
For example, this can be
1.2.0a2
- weatherly.version_info#
A named tuple containing version informations. Similiar to
sys.version_info
Clients#
Client#
- defbulk_request
- @event
- defget_astronomical_data
- defget_current_weather
- defget_forecast_data
- defget_future_data
- defget_historical_data
- defget_ip_data
- defget_locations
- defget_marine_data
- defget_sports_data
- defon_error
- defset_language
- class weatherly.Client(api_key: str, lang: Optional[Union[str, Languages]] = None, dt: Optional[int] = None, end_dt: Optional[int] = None, hour: Optional[int] = None, aqi: bool = False, tides: bool = False, **kwargs: Dict[str, Any])#
A WeatherAPI.com client for fetching various weather information
- Parameters:
api_key (
str) – API Key used to authenticate when sending requestslang (Optional[ Union[
str,Languages] ]) – Language from theLanguagesenum or a string representing the language or language code (preferably). To get a list of languages visitLanguages. IfNonethen the default language is used (English)dt (Optional[
int]) – Restrict date output for Forecast and History API method. (Required for History and Future API)end_dt (Optional[
int]) – Restrict date output for History API method. Only works for API on Pro plan and above. (Available for History API)hour (Optional[
int]) – Restricting forecast or history output to a specific hour in a given day.aqi (
bool) – Enable/Disable Air Quality data in forecast API output. Defaults to “no”.tides (
bool) – Enable/Disable Tide data in Marine API output. Defaults to “no”.kwargs (Dict[
str, Any]) – Additional keyword arguments passed by default to requests made by the client
- lang#
Language from the
Languagesenum or a string representing the language or language code (preferably). To get a list of languages visitLanguages. IfNonethen the default language is used (English)- Type:
Optional[
Languages]
- dt#
Restricted date output for Forecast and History API method. (Required for History and Future API)
- Type:
Optional[
int]
- end_dt#
Restricted date output for History API method. Only works for API on Pro plan and above.
- Type:
Optional[
int]
- kwargs#
Additional keyword arguments passed by default to requests made by the client
- Type:
Dict[
str, Any]
- @event#
A decorator that turns a function into an event. For example
import weatherly client = weatherly.Client(api_key=...) @client.event def on_error(func, exc): print(f"An error occured! Function: {func}, error: {str(exc)}")
In the example above, by adding
@client.eventtheon_errorfunction has turned into an error handler functionImportant
The function SHOULD NOT be a coroutine function!
- bulk_request(data: BulkRequest, **kwargs) BulkResponse#
A bulk request allowing you to retrieve data for multiple locations at once
Note
Bulk requests only work on one endpoint, so you cannot use it to get data from multiple endpoints e.g. forecast and current weather
Note
To do a bulk request you should build a
BulkRequestobject and pass it as a data parameter first- Parameters:
data (
BulkRequest) –Data for the bulk request. To build this class consider using two following methods:
import weatherly # 1. by BulkRequest.build req = BulkRequest.build(("my-id", "London"), ("second", "Paris"), endpoint=weatherly.WeatherEndpoints.CURRENT_WEATHER) # 2. by manually setting bulk request params bulk = BulkRequest() bulk.set_endpoint(weatherly.WeatherEndpoints.FORECAST) bulk.add_query(id="my-id", location="Paris") bulk.add_query(id="second", location="London")
kwargs (Dict[
str, Any]) – Additional keyword arguments. You need to think of them manually, look for them in other methods and pass them inkey=valschema. For example:client.bulk_request(req, aqi=True, days=7)
- Returns:
BulkResponse– Results of the bulk request- Raises:
NoLocationFound – Raised when no matching location was found.
InvalidAPIKey – Raised when the API key is invalid
APILimitExceeded – Raised when API key calls limit was exceeded
APIKeyDisabled – Raised when API key is disabled
AccessDenied – Raised when access to given resource was denied
InternalApplicationError – Raised when there was a very rare internal application error
WeatherAPIException – Raised when something else went wrong, that does not have a specific exception class.
- get_astronomical_data(query: str, date: str, **kwargs: Dict[str, Any]) AstronomicalData#
Get astronomical data from Astronomy API
- Parameters:
- Returns:
AstronomicalData– Fetched astronomical data as a class.- Raises:
NoLocationFound – Raised when no location for given query was found
InvalidAPIKey – Raised when the API key is invalid
APILimitExceeded – Raised when API key calls limit was exceeded
APIKeyDisabled – Raised when API key is disabled
AccessDenied – Raised when access to given resource was denied
InternalApplicationError – Raised when there was a very rare internal application error
WeatherAPIException – Raised when something else went wrong, that does not have a specific exception class.
- get_current_weather(query: str, *, lang: Optional[Union[str, Languages]] = None, aqi: Optional[bool] = None, **kwargs: Dict[str, Any]) CurrentWeatherData#
Get current weather data
- Parameters:
query (
str) – Query string - location you want to get weather data forlang (Optional[Union[
str, Languages]]) – Language from theLanguagesenum or a string representing the language or language code (preferably). To get a list of languages visitLanguages.aqi (Optional[
bool]) – Enable/Disable Air Quality data in forecast API output. If nothing is passed, then it defaults to client default value.kwargs (Dict[
str, Any]) – Additional keyword arguments to request
- Returns:
CurrentWeatherData– Current weather data class- Raises:
NoLocationFound – Raised when no location for given query was found
InvalidAPIKey – Raised when the API key is invalid
APILimitExceeded – Raised when API key calls limit was exceeded
APIKeyDisabled – Raised when API key is disabled
AccessDenied – Raised when access to given resource was denied
InternalApplicationError – Raised when there was a very rare internal application error
WeatherAPIException – Raised when something else went wrong, that does not have a specific exception class.
- get_forecast_data(query: str, days: int, *, aqi: Optional[bool] = None, alerts: Optional[bool] = None, lang: Optional[Union[str, Languages]] = None, **kwargs: Dict[str, Any]) ForecastData#
Get forecast data from Forecast API
- Parameters:
query (
str) – Query string, location you want to get forecast data fordays (
int) – Number of days of weather forecast. Value ranges from 1 to 10aqi (Optional[
bool]) – Enable/Disable Air Quality data. Defaults toNone(will use client’s default)alerts (Optional[
bool]) – Enable/Disable alerts data. Defaults toNone(will use client’s default)lang (Optional[Union[:class`str`, :class`Languages`]]) – Language from the
Languagesenum or a string representing the language or language code (preferably). To get a list of languages visitLanguages.kwargs (Dict[
str, Any]) – Additional keyword arguments that will be passed to the request.
- Returns:
ForecastData– Fetched forecast data as a class.- Raises:
NoLocationFound – Raised when no location for given query was found
InvalidAPIKey – Raised when the API key is invalid
APILimitExceeded – Raised when API key calls limit was exceeded
APIKeyDisabled – Raised when API key is disabled
AccessDenied – Raised when access to given resource was denied
InternalApplicationError – Raised when there was a very rare internal application error
WeatherAPIException – Raised when something else went wrong, that does not have a specific exception class.
- get_future_data(query: str, date: str, *, lang: Optional[Union[str, Languages]] = None, **kwargs: Dict[str, Any]) FutureData#
Retrieve future data for given day and query. Uses Future API.
- Parameters:
query (
str) – Query string, location you want to get forecast data fordate (
str) – A date string in format yyyy-mm-dd representing the day you want to get data forlang (Optional[Union[:class`str`, :class`Languages`]]) – Language from the
Languagesenum or a string representing the language or language code (preferably). To get a list of languages visitLanguages.kwargs (Dict[
str, Any]) – Additional keyword arguments that will be passed to the request.
- Returns:
FutureData– Future data for given day and query.- Raises:
NoLocationFound – Raised when no location for given query was found
InvalidAPIKey – Raised when the API key is invalid
APILimitExceeded – Raised when API key calls limit was exceeded
APIKeyDisabled – Raised when API key is disabled
AccessDenied – Raised when access to given resource was denied
InternalApplicationError – Raised when there was a very rare internal application error
WeatherAPIException – Raised when something else went wrong, that does not have a specific exception class.
InvalidDate – Raised when the
dateparameter is invalid (doesn’t match the format or isn’t a date after today)
- get_historical_data(query: str, date: str, *, aqi: Optional[bool] = None, alerts: Optional[bool] = None, lang: Optional[Union[str, Languages]] = None, **kwargs: Dict[str, Any]) ForecastData#
Retrieve historical data for given day and query. Uses History API.
- Parameters:
query (
str) – Query string, location you want to get forecast data fordate (
str) – A date string in format yyyy-mm-dd representing the day you want to get data foraqi (Optional[
bool]) – Enable/Disable Air Quality data. Defaults toNone(will use client’s default)alerts (Optional[
bool]) – Enable/Disable alerts data. Defaults toNone(will use client’s default)lang (Optional[Union[:class`str`, :class`Languages`]]) – Language from the
Languagesenum or a string representing the language or language code (preferably). To get a list of languages visitLanguages.kwargs (Dict[
str, Any]) – Additional keyword arguments that will be passed to the request.
- Returns:
ForecastData– Forecast data for given day and query.- Raises:
NoLocationFound – Raised when no location for given query was found
InvalidAPIKey – Raised when the API key is invalid
APILimitExceeded – Raised when API key calls limit was exceeded
APIKeyDisabled – Raised when API key is disabled
AccessDenied – Raised when access to given resource was denied
InternalApplicationError – Raised when there was a very rare internal application error
WeatherAPIException – Raised when something else went wrong, that does not have a specific exception class.
InvalidDate – Raised when the
dateparameter is invalid (doesn’t match the format or isn’t a date before (or) today)
- get_ip_data(ip_address: str, **kwargs: Dict[str, Any]) IPData#
Look for data for the given IP address.
- Parameters:
- Returns:
IPData– Fetched IP data as a class.- Raises:
NoLocationFound – Raised when either IP address was invalid or no matching location was found.
InvalidAPIKey – Raised when the API key is invalid
APILimitExceeded – Raised when API key calls limit was exceeded
APIKeyDisabled – Raised when API key is disabled
AccessDenied – Raised when access to given resource was denied
InternalApplicationError – Raised when there was a very rare internal application error
WeatherAPIException – Raised when something else went wrong, that does not have a specific exception class.
- get_locations(query: str)#
Get locations for given query
- Parameters:
query (
str) – Query string, a location you are searching for- Returns:
List[
LocationData] – A list ofLocationDataclasses.- Raises:
NoLocationFound – Raised when no location for given query was found
InvalidAPIKey – Raised when the API key is invalid
APILimitExceeded – Raised when API key calls limit was exceeded
APIKeyDisabled – Raised when API key is disabled
AccessDenied – Raised when access to given resource was denied
InternalApplicationError – Raised when there was a very rare internal application error
WeatherAPIException – Raised when something else went wrong, that does not have a specific exception class.
- get_marine_data(query: str, *, tides: Optional[bool] = None, **kwargs: Dict[str, Any]) MarineData#
Get marine data from Marine API
- Parameters:
- Returns:
MarineData– Fetched marine data as a class.- Raises:
NoLocationFound – Raised when no location for given query was found
InvalidAPIKey – Raised when the API key is invalid
APILimitExceeded – Raised when API key calls limit was exceeded
APIKeyDisabled – Raised when API key is disabled
AccessDenied – Raised when access to given resource was denied
InternalApplicationError – Raised when there was a very rare internal application error
WeatherAPIException – Raised when something else went wrong, that does not have a specific exception class.
- get_sports_data(query: str, **kwargs: Dict[str, Any]) SportsData#
Get sports data for a given query. Uses Sports API.
- Parameters:
- Returns:
SportsData– Retrieved sports data as a class.- Raises:
NoLocationFound – Raised when no matching location was found.
InvalidAPIKey – Raised when the API key is invalid
APILimitExceeded – Raised when API key calls limit was exceeded
APIKeyDisabled – Raised when API key is disabled
AccessDenied – Raised when access to given resource was denied
InternalApplicationError – Raised when there was a very rare internal application error
WeatherAPIException – Raised when something else went wrong, that does not have a specific exception class.
Event reference#
Weatherly provides an easy to use event system. There are two ways to register an event function.
First method is to use Client.event() decorator.
import weatherly
client = weatherly.Client("your-api-key")
@client.event
def on_error(func_name, exception):
print(f"Exception occured in {func_name}!")
Second way is to make a custom client class inheriting from Client.
import weatherly
class CustomClient(weatherly.Client):
def __init__(self, api_key):
super().__init__(api_key=api_key)
def on_error(func_name, exception):
print(f"Exception occured in {func_name}!")
Important
All event functions mustn’t be coroutines.
A ValueError is raised when a function is a coroutine.
Error handling#
API calls#
- weatherly.on_api_call_successful(request, response)#
Called when an API call (e.g.
Client.get_current_weather()) was successfully done.- Parameters:
request (
str) – The request URL e.g. https://api.weatherapi.com/v1/endpoint?param=valueresponse (
requests.Response) – Response class
Enums#
Languages#
- class weatherly.Languages#
Languages - an enum representing languages available for use in the WeatherAPI requests.
Attributes are languages and language codes
Sports event type#
Tide height type#
Endpoints#
- class weatherly.WeatherEndpoints#
An enum representing WeatherAPI endpoint used for bulk requests
- CURRENT_WEATHER#
Current weather endpoint
- ASTRO#
Astronomical data enpoint
- FORECAST#
Forecast data enpoint
- FUTURE#
Future weather data endpoint
- HISTORY#
Historical weather data endpoint
- IP_DATA#
IP address info endpoint
- LOCATIONS#
Search/Autocomplete location endpoint
- MARINE#
Marine data endpoint
- SPORTS#
Sports data endpoint
Models#
Warning
Those classes should not be created manually, instead they are returned from methods like get_current_weather of the Client class.
BulkRequest is the only object you should build / create, other classes should not even be modified
Note
When adding a lang parameter to the request only condition_text is translated into requested language.
Base model classes#
- class weatherly.PartialAPIResponse#
Represents a partial response, or a part of a response class from WeatherAPI
- flatten() Dict[str, str]#
Converts a Dict[
str, Any] into a flatten dictionary of type Dict[str,str]For example, given a dictionary
{ "body": { "tag": "p", "content": { "yes": "no" } }, "other": { "one": "two", "three": "four" } }
It will be turned into
{ "body.tag": "p", "body.content.yes": "no", "other.one": "two", "other.three": "four" }
Note
This function does not use recursion, so there won’t be any stack problems with long nested dictionaries
- class weatherly.APIResponse#
Represents a basic response from Weather API. Inherits from
PartialAPIResponse.
Current weather#
- class weatherly.CurrentWeatherData#
Current weather data, a common return type from methods that requests this from WeatherAPI.com.
- location#
Location of the requested weather data
- Type:
- aqi#
Air quality data. Can be
None(if this field of data was not requested)- Type:
Optional[
AirQualityData]
Location#
Air Quality#
- class weatherly.AirQualityData#
Air Quality data
- us_epa_index#
- US - EPA standard.
1 means Good
2 means Moderate
3 means Unhealthy for sensitive group
4 means Unhealthy
5 means Very Unhealthy
6 means Hazardous
- Type:
- gb_defra_index#
UK Defra Index
Index
1
2
3
4
5
6
7
8
9
10
Band
Low
Low
Low
Moderate
Moderate
Moderate
High
High
High
Very High
µgm^-3
0-11
12-23
24-35
36-41
42-47
48-53
54-58
59-64
65-70
71 or more
- Type:
- gb_defra_band#
A band corresponding to the
gb_defra_index- Type:
- us_epa_band#
A band corresponding to the
us_epa_index- Type:
- class weatherly.AlertData#
An alert from WeatherAPI
Future#
IP#
Astronomical#
- class weatherly.AstronomicalData#
Represents astronomical data as a response from WeatherAPI
- location#
Location of the requested data. Is not
Noneonly if this object is returned fromastronomy.jsonendpoint.- Type:
Optional[
LocationData]
Marine#
- cloud
- condition_code
- condition_icon
- condition_text
- dewpoint_c
- dewpoint_f
- feelslike_c
- feelslike_f
- gust_kph
- gust_mph
- headindex_c
- headindex_f
- humidity
- is_day
- precip_in
- precip_mm
- pressure_in
- pressure_mb
- raw
- sig_ht_mt
- swell_dir
- swell_dir_16_point
- swell_ht_ft
- swell_ht_mt
- swell_period_secs
- temp_c
- temp_f
- time
- time_epoch
- uv
- vis_km
- vis_miles
- water_temp_c
- water_temp_f
- wind_degree
- wind_dir
- wind_kph
- wind_mph
- windchill_c
- windchill_f
- class weatherly.MarineHour#
Marine hour, part of
MarineDay, this class contains marine and forecast informations from a specific hour. Inherits from :class`ForecastData` to avoid more messy code
- class weatherly.MarineDay#
Marine day, part of
MarineData, representing a single day with forecast information- hour_data#
A list of
MarineHourobjects representing hourly weather data.- Type:
List[
MarineHour]
- astro#
Astronomical data object
- Type:
- defiter_hours
- class weatherly.MarineData#
Marine data, response from Marine API as a class
- location#
Location of the requested marine data
- Type:
- for ... in iter_hours() Iterator[MarineHour]#
Iterate over all possible hours from this class.
- for x in y
Iterate over hour data from this instance.
- Returns:
Iterator[
MarineHour] – A generator object you can iterate over made ofMarineHour
- class weatherly.TideData#
Represents tide data, part of Marine API response
- tide_type#
Type of height of the tide represented as a
TideHeightenum. Can beLOWorHIGH- Type:
Bulk requests#
- clsBulkRequest.build
- defadd_query
- defset_endpoint
- class weatherly.BulkRequest#
Represents a bulk request params
- endpoint#
Enum representing the endpoint for the request
- Type:
- classmethod build(*queries: List[Tuple[str]], endpoint: WeatherEndpoints)#
Build a bulk request
Note
This function is a class method i.e. does not require initialization. For example:
import weatherly weatherly.BulkRequest.build(...) # <- no initialization needed (no parentheses after BulkRequest)
- Parameters:
queries (List[Tuple[
str]]) – Query data for the request as a list of tuples (id, query)endpoint (
WeatherEndpoints) – Enum representing the endpoint for the request
- set_endpoint(endpoint: WeatherEndpoints) None#
Set the endpoint for the request
- Parameters:
endpoint (
WeatherEndpoints) – Endpoint for the request as an enum
Utility functions#
This library also provides utility (aka helper) functions, that can be easily used.
Find language enum#
Convert a string to an enum#
Exceptions#
- exception weatherly.WeatherlyException#
A base class for all
weatherlyexceptions. Almost all exceptions of this module inherit from this class.Inherits from
Exception.
- exception weatherly.InvalidDate#
Raised when a date (for History/Future API) is invalid.
Inherits from
WeatherlyException.
- exception weatherly.WeatherAPIException(status: int, code: int, message: str, *args)#
The base class for
Clientweather requests exceptions.
- exception weatherly.NoLocationFound(status: int, code: int, message: str, *args)#
Exception like this is raised when no location was found when searching for weather data.
Usually has status code 400 and error code 1006.
Inherits from
WeatherAPIException.
- exception weatherly.InvalidAPIKey(status: int, code: int, message: str, *args)#
Exception like this is raised when provided API key is invalid
Usually has status code 401 and error code 2006.
Inherits from
WeatherAPIException.
- exception weatherly.APILimitExceeded(status: int, code: int, message: str, *args)#
Exception like this is raised when API key has exceeded monthly calls limit.
Usually has status code 400 and error code 2007.
Inherits from
WeatherAPIException.
- exception weatherly.APIKeyDisabled(status: int, code: int, message: str, *args)#
Exception like this is raised when API key has been disabled.
Usually has status code 403 and error code 2008.
Inherits from
WeatherAPIException.
- exception weatherly.AccessDenied(status: int, code: int, message: str, *args)#
Exception like this is raised when API key does not have access to requested resource.
Usually has status code 403 and error code 2009.
Inherits from
WeatherAPIException.
- exception weatherly.InternalApplicationError(status: int, code: int, message: str, *args)#
Exception like this is raised when an internal application error occured. There is nothing to do about it.
Usually has status code 400 and error code 9999.
Inherits from
WeatherAPIException.