Mon. Oct 14th, 2019

SVMAKERS.ORG

Shenango Valley Makers

Introduction to weatherstack’s Real-Time & Historical World Weather API

Welcome. If you require accurate real-time world weather data for your client, company, website or application, weatherstack is a comprehensive service to consider. In addition to current weather and 14 day worldwide forecasts, the weatherstack API provides historical weather data as far back as 2008. And, weatherstack is an affordable, easy to use, well-documented weather data API.

weatherstack provides weather data in 40 languages from Arabic to Zulu and measurement units for metric, scientific or English. For example, temperatures can be returned as Celsius, Kelvin or Fahrenheit.

iHome page of apilayer’s weatherstack API service, a current, past and future forecast global weather data API

As a REST API, weatherstack can be used from any programming language and developer examples for PHP, Python, Nodejs, jQuery, Go and Ruby are provided.

And weatherstack is well established, it has more than 75,000 customers.

apilayer is the service provider that provides weatherstack. This is my seventh article about its services, and I’ve grown to be a fan of the simplicity and accessibility of those services. They all provide similar pricing models, sign up, quickstart guides and clearly structured documentation.

Here are a few of apilayer’s services, I’ve written about previously:

If you’ve used one of these services before, starting with the weatherstack API will be familiar to you.

If you require reliable real-time global weather data and 7 and 14-day forecasts, you can count on weatherstack’s rock solid uptime and performance as well as its helpful customer support.

And, if you’re a startup or independent developer, apilayer always offers a generous free plan with all its services, and the weatherstack API is no different. Free accounts offer 1,000 API requests per month.

APIXU Customers are Welcome

weatherstack has acquired APIXU, an early leader in weather data and forecast APIs, and greatly enhanced its service offerings.

The weatherstack API is a newly enhanced version of APIXU, a trusted weather forecast API

The weatherstack API is a newly enhanced version of APIXU, a trusted weather forecast API

Existing APIXU customers should get in touch with weatherstack by October 14, 2019 for a special offer.

Let’s start exploring the weatherstack service. Since it’s free to get started, you can register for an account and try out the services as you follow my introduction.

Getting Started with the weatherstack API

To get started exploring weatherstack’s forecast data services, you’ll need to register for an account, the free account level is great for exploring the API.

Get Your Free weatherstack API Key

weatherstack's pricing page showing Free, Basic $9.99, Professional $49.99, Business $99.99 and custom Enterprise plans

weatherstack’s pricing page showing Free, Basic $9.99, Professional $49.99, Business $99.99 and custom Enterprise plans

The Sign Up Form

Once you’ve chosen a plan you’ll be asked to complete a Sign Up form. It’s very straightforward:

weatherstack API sign up form. The example shown is the free plan with email, password, name and address information. The image shows the below the scroll portion of the form for Company Details and Google CAPTCHA at the right

weatherstack API sign up form. The example shown is the free plan with email, password, name and address information. The image shows the below the scroll portion of the form for Company Details and Google CAPTCHA at the right.

Once you click Sign Up, a welcome letter with links to the documentation will arrive in your email.

The welcome email from the weatherstack api global forecast service provides a link to API documentation and their customer support email

The welcome email from the weatherstack API global forecast service provides a link to API documentation and their customer support email.

Let’s check out the dashboard, which customers of other apilayer services will immediately recognize. If you use one apilayer service, getting started with any other is quite simple.

The weatherstack API Dashboard

weatherstack’s API dashboard provides your API key and a simple 3 step quickstart guide:

Step 1 – Your API Access Key
Your API access key provides access to the weatherstack API. It’s required to be included as a parameter in every call. You can also reset the key to secure a new one whenever you wish.

EDITOR NOTE: I’ve reset my API key since the screenshot below.

The weatherstack API 3-Step Quickstart Guide for getting started using the service.

The weatherstack API 3-Step Quickstart Guide for getting started using the service.

Step 2 – Reviewing the Six API Endpoints

The weatherstack quick start provides a simple tabbed base dialog for exploring its five endpoints: Current Weather data, Historical Weather data, Time-Series of Historical Weather data, Weather Forecasts up to 14 days in the future and a Location Lookup for auto-complete.

Screenshot of list of the five weatherstack API endpoints: Current Weather, Historical Weather, Historical Time-Series weather data, Weather Forecast, and Location Lookup

Screenshot of the list of the five weatherstack API endpoints: Current Weather, Historical Weather, Historical Time-Series weather data, Weather Forecast, and Location Lookup.

The quickstart provides a graphical overview of each of the weatherstack API endpoints in a series of tabs. Here’s an example of one of them, and you can click each to see the others:

weatherstack API Quickstart Make API Request screenshot with tabbed examples for Current Weather, Historical weather data, Time-Series weather data and forecast data

weatherstack API Quickstart Make API Request screenshot with tabbed examples for Current Weather, Historical weather data, Time-Series weather data, and forecast data.

Let’s try one of the APIs to see how easy it is to use weatherstack’s weather forecasting data. In the screenshot above, I clicked the api.weatherstack.com… link example in the Current tab:

http://api.weatherstack.com/current?access_key=xxxxxxxx&query=New%20York

It immediately provided a JSON response string:

{"request":{"type":"City","query":"New York, United States of America","language":"en","unit":"m"},"location":{"name":"New York","country":"United States of America","region":"New York","lat":"40.714","lon":"-74.006","timezone_id":"America/New_York","localtime":"2019-09-20 15:21","localtime_epoch":1568992860,"utc_offset":"-4.0"},"current":{"observation_time":"07:21 PM","temperature":25,"weather_code":113,"weather_icons":["https://assets.weatherstack.com/images/wsymbols01_png_64/wsymbol_0001_sunny.png"],"weather_descriptions":["Sunny"],"wind_speed":0,"wind_degree":278,"wind_dir":"W","pressure":1023,"precip":0,"humidity":30,"cloudcover":0,"feelslike":25,"uv_index":7,"visibility":16,"is_day":"yes"}}

I placed this in a web-based JSON parser (e.g. http://json.parser.online.fr) so I can more clearly show you this is local data for the example city, New York, United States of America. The location data provides us the GPS coordinates and local time. And the current data provides the observation time, temperature, weather_code and icons which you can use in your application, as well as a textual weather description and more:

 weatherstack API example results of current weather data in New York in JSON format

weatherstack API example results of current weather data in New York in JSON format.

The weatherstack documentation provides extensive definitions for all its weather data making it easy for developers to come up to speed on weather information:

Excerpt of current weather forecast definitions from the weatherstack API. Terms such as observation time, wind speed, wind degree and UV index

Excerpt of current weather forecast definitions from the weatherstack API. Terms such as observation time, wind speed, wind degree and UV index.

To finish the Quickstart and move on, let’s dive into the API more closely.

Screenshot of last step of the weatherstart API Quickstart, Integrate into your application

Screenshot of the last step of the weatherstack API Quickstart, Integrate into your application.

Integrate the weatherstack API into your application

Now I will walk through each of the weather forecast and weather data APIs. The documentation from weatherstack, like all apilayer services, is well-organized and intuitive to use.

Retrieve Current Weather

Top excerpt of documentation for requesting current weather forecast from weatherstack API

Top excerpt of documentation for requesting current weather forecast from weatherstack API

First, let’s retrieve the current weather for my location, Seattle. To begin, I just pasted the request in my browser bar using my access key. But you can also see examples by clicking Run API Request which is available throughout the documentation. If you’re following along with your own account, the Run API Request button will use your unique access key, so it’s ready for you to use now.

https://api.weatherstack.com/current?access_key=xxxxxxxxxxxxxx&query=seattle

The data is returned as unformatted JSON, here’s a more readable version:

 Response data as JSON for current weather from Seattle - via weatherstack API

Response data as JSON for current weather from Seattle – via weatherstack API

The weatherstack documentation provides clear and in-depth definitions of the weather data structures it returns. Here’s an example:

Top excerpt of documentation for response of current weather data from the weathercast API

Top excerpt of documentation for the response of current weather data from the weathercast API.

And as I showed in the quickstart above, the documentation provides extensive definitions for all its technical weather data. This makes it easier for developers to come up to speed on the meaning of weather terminology provided in the results.

In addition, weatherstack returns a numeric weather code and a link to an associated weather icon.

Included in all current conditions and past weather data is a universal weather condition code, such as 116 in the Seattle weather results above. You can download all available weather codes using this link: https://weatherstack.com/site_resources/weatherstack-weather-condition-codes.zip

weatherstack also provides a URL to an icon image you can use which represents the weather condition visually. For example, here is the icon for clear skies:

Response JSON data from weatherstack for the current condition includes a weather_icons URL argument, in the example a clear sky night rendered as a sliver of moon against a dark evening sky

Response JSON data from weatherstack for the current condition includes a weather_icons URL argument, in the example a clear sky night rendered as a sliver of the moon against a dark evening sky.

Retrieve Historical Weather

Top excerpt of documentation from historical weather method for the weatherstack API

Top excerpt of documentation from historical weather method for the weatherstack API

Here, I’ll make a historical weather request using my browser or you can click Run API Request from your browser. I’m seeking the weather from Denver, Colorado on January 15, 2015, in 12-hour intervals.

https://api.weatherstack.com/historical?access_key=xxxxx&query=denver&historical_date=2015-01-21&hourly=12

In addition to the location data and current weather, historical weather returns data at the lower right below:

Response data to a city's historical weather request from the weatherstack API

Response data to a city’s historical weather request from the weatherstack API

Next, I’ll request historical weather data from a day over a three month period from 2019 in hourly intervals.

https://api.weatherstack.com/historical?access_key=xxxxx&query=denver&historical_date=2019-01-20;2019-02-20;2019-03-20&hourly=1

As you can request more days and shorter hourly intervals, weatherstack responds with a great quantity of data. To help visualize this in the tutorial, I’ve divided the response below into three columns.

The left column shows the request return three days of historical data as JSON arrays. The middle column shows one such day’s historical array and the right column shows each hourly array.

A simplified visual representation of response data for three days of a city's hourly historical weather data via the weatherstack API

A simplified visual representation of response data for three days of a city’s hourly historical weather data via the weatherstack API

The historical day response includes a plethora of data such as astrological sunrise and sunset, daily average temperature and uv_index.

The hourly day response includes even more detail such as temperature, wind speed and direction, weather icons you can use in your application, weather descriptions, dewpoint, wind chill, and more.

The documentation provides explanations for all of the variables returned by the weather data API.

Retrieve Historical Time-Series Weather Data

Top excerpt of documentation for requesting historical time-series weather data from the weatherstack API

Top excerpt of documentation for requesting historical time-series weather data from the weatherstack API

The Historical Time-Series Weather Data makes it easier to obtain data for a short or extended timeframe of consecutive dates. Below, I request historical weather data between January 21st, 2019 and February 1st, 2019 for Tokyo, Japan.

https://api.weatherstack.com/historical?access_key=xxxxxxxxxx&query=Tokyo&historical_date_start=2019-01-21&historical_date_end=2019-02-01

The response again includes a lot of data. Below, at left I’ve compressed the series of twelve days of Tokyo weather data and at right expanded the response data for a single day:

Response for historical time-series weather data for twelve consecutive days of city weather via weatherstack API

Response for historical time-series weather data for twelve consecutive days of city weather via weatherstack API

The response data for each day includes astrological data such as sunrise and sunset as well as the days minimum and maximum temperatures, UV index, and snowfall.

Retrieve the Weather Forecast

Top excerpt of documentation for retrieving the weather forecast for a city or cities via the weatherstack API.

Top excerpt of documentation for retrieving the weather forecast for a city or cities via the weatherstack API.

Here I request a current weather forecast for one day in New York by the hour:

https://api.weatherstack.com/forecast?access_key=xxxxx&query=New%20York&forecast_days=1&hourly=1

In the response below, you can see again on the left that the forecast hours are returned in an array, and each hour includes a wealth of weather data:

Response data for a city weather forecast by the hour via the weatherstack API

Response data for a city weather forecast by the hour via the weatherstack API

The forecast data includes projections for temperature, wind speed, and direction, textual weather descriptions, codes and icons, precipitation, humidity, pressure, chance of rain and wind, etc.

Of course, you can also request a 7 day or 14-day multi-day forecast but this requires a Professional or Business Plan.

Autocomplete Location

Parameters for weatherstack's autocomplete location lookup which assists in identifying the exact city from a planet full of overlapping names. E.g. London, England and London, Ontario, Canada

Parameters for weatherstack’s autocomplete location lookup which assists in identifying the exact city from a planet full of overlapping names. E.g. London, England and London, Ontario, Canada.

Since we live in a world of overlapping city names, weatherstack provides a location lookup method called autocomplete. Autocomplete can be used to implement real-time autocomplete input fields so users can quickly select the city which they would like weather data from.

Or, if you have a city name that is not unique, you can use location lookup to determine the proper query.

For example, I have friends near Troy, New York but there is also a Troy, Michigan. You can use the autocomplete method to determine how to query for weather in Troy, New York:

https://api.weatherstack.com/autocomplete?access_key=XXXXXX&query=troy
Determining unique characteristics for a city, autocomplete location lookup from the weatherstack API. Using the response, you can use GPS coordinates for future weatherstack API calls

Determining unique characteristics for a city, autocomplete location lookup from the weatherstack API. Using the response, you can use GPS coordinates for future weatherstack API calls.

From the response data, I can use the 42.728, -73.692 GPS coordinates for Troy, New York as an alternative query parameter in future requests for weather data. For example, the following query works well, returning weather for Watervliet a neighboring hamlet to Troy:

https://api.weatherstack.com/current?access_key=xxxxxx&query=42.728,-73.692

Querying by GPS coordinates is an advanced use of the weatherstack API location query which I will describe in the next section.

Beyond the Basics of the weatherstack API

In addition to the standard weather data queries I’ve described above, weatherstack offers special ways to leverage the power of its service.

Advanced Uses of the Location Query

Documentation of alternative weatherstack queries, query by city name, by postal code, by GPS coordinates, by IP address and fetch:ip, which determines the requester's location

Documentation of alternative weatherstack queries, query by city name, by postal code, by GPS coordinates, by IP address and fetch:ip, which determines the requester’s location.

The weatherstack API offers five different ways to request weather from a location:

  1. Query by city, e.g. query = New York
  2. Query by Postal Code or Zip Code, e.g. query = 99501
  3. Query by GPS coordinates as we did in the example, query=42.728,-73.692
  4. Query by IP address, the weatherstack server identifies the location of the given IP address
  5. Query by “fetch:ip” which is a cool way to tell the server to auto-detect the requester’s IP address so it can determine the user’s location

Units, specifying

When making weatherstack API requests, you can use a “units” parameter to customize the measurements returned to you. The default units are set to metric but there are three units available for you to choose from:

1. Metric, use units = m, for temperature in Celsius, wind speed in Kilometers per Hour, pressure in Millibar, precipitation in Millimeters and snow in Centimeters.

2. Scientific, use units = s, for temperature in Kelvin, wind speed in Kilometers per Hour, pressure in Millibar, precipitation in Millimeters and snow in Centimeters.

3. English, use units = f, for temperature in Fahrenheit, wind speed in Miles per Hour, pressure in Millibar, precipitation and snow in Inches.

Choosing a language

The weatherstack API can provide weather data results in 40 different languages. You can add the language parameter to customize the results. The default language is English.

The languages available include: Arabic, Bengali, Bulgarian, Chinese Simplified, Chinese Traditional, Czech, Danish, Dutch, Finnish, French, German, Greek, Hindi, Hungarian, Italian, Japanese, Javanese, Korean, Mandarin, Marathi, Polish, Portuguese, Punjabi, Romanian, Russian, Serbian, Sinhalese, Slovak, Spanish, Swedish, Tamil, Telugu, Turkish, Ukrainian, Urdu, Vietnamese, Wu (Shanghainese), Xiang, Yue (Cantonese), and Zulu.

JSONP Callbacks

weatherstack also supports JSONP callbacks. For example, if you specify a function name as a “callback” parameter, the response will call the function with the results on its return.

For example, the response will be returned so as to call YOUR_FUNCTION() with the response data:

https://api.weatherstack.com/current?access_key=xxxxxx&query=New%20York&callback=YOUR_FUNCTION

When using JavaScript, in my experimentation, it was easier just to have the AJAX success method call my functions with the response data. But, what happens when you’re calling the API from a different language?

Here’s an example of using the callback method from PHP, to call a JavaScript function on the page to display the data:

   


'.$json.''; curl_close($ch); ?>

The weatherstack API query is made via PHP cURL. My specified callback is the JavaScript function name processResult(), which must be defined before the API call.

The results will be displayed as a string on the page and sent to the JavaScript console with a structured example.

Programming Language Examples

weatherstack, like most apilayer services, provides programming examples for many of the most popular languages such as those included here: PHP, Python, Node.js, jQuery, Go and Ruby.

Here’s an example for Python:

# coding: utf-8
import requests
params = {
  'access_key': 'YOUR_ACCESS_KEY',
  'query': 'New York'
}
api_result = requests.get('https://api.weatherstack.com/current', params)
api_response = api_result.json()
print(u'Current temparture in %s is %d℃' % (api_response['location']['name'], api_response['current']['temperature']))

And, here’s an example in Nodejs:

const axios = require('axios');
const params = {
  access_key: 'YOUR_ACCESS_KEY',
  query: 'New York'
}
axios.get('https://api.weatherstack.com/current', {params})
  .then(response => {
    const apiResponse = response.data;
    console.log(`Current temparture in ${apiResponse.location.name} is ${apiResponse.current.temperature}℃`);
  }).catch(error => {
    console.log(error);
  });

Upgrading Your Account

weatherstack is a subscription-based service and your chosen plan renews automatically each month. You can upgrade, downgrade or cancel anytime.

You might want to upgrade your account for any one or combination of these reasons:

  • To use SSL encryption, available on Standard accounts and above
  • To obtain 7-day weather forecast data in up to 40 languages and perform bulk queries, available on Professional accounts and above
  • To obtain 14-day weather forecast data, available on Business accounts and Enterprise

From the weatherstack Dashboard, visit your Subscription Plan page:

Pricing table showing upgrade and downgrade options for the weatherstack API data forecast and weather history service

Pricing table showing upgrade and downgrade options for the weatherstack API data forecast and weather history service.

And, weatherstack provides a page to calculate your usage statistics in the current period and historically over time. Just visit your Dashboard and click API Usage (I’ve just recently been using my account so the usage is over a brief timeframe.):

The Dashboard's API Usage page displays the number of API requests all time as well as a statistical daily log for your internal tracking

The Dashboard’s API Usage page displays the number of API requests all time as well as a statistical daily log for your internal tracking.

You can use this log to help you in deciding to upgrade or downgrade subscription levels. For example, Free plans are allowed 1,000 calls per month whereas Professional are allowed 300,000 and Business level 1,000,000. If that isn’t enough to meet your requirements, contact weatherstack for a custom enterprise plan.

In Conclusion

I hope you’ve enjoyed this introduction to weatherstack’s vast ever expanding history of the earth’s global weather past, present and future. It’s an outstanding weather history and weather forecast data service and weather API.

I always enjoy catching up with the apilayer team and writing about their new projects. They are sharp technologists providing powerful services with affordable prices, easy to integrate APIs and high performing scalable technologies.

weatherstack is an essential weather forecasting and historical weather API for many Internet websites, applications and business metrics. Check out their suite of products and you’ll likely find more that interest you.

apilayer and weatherstack appreciate your questions, comments and feedback. You can also follow them on Twitter @apilayernet and the apilayer Facebook page.

About apilayer

weatherstack is the latest service from apilayer, an established leader in service APIs. apilayer aims to help developers and businesses automate and outsource complex processes by serving them with dedicated and handy programming interfaces.

Two other products by apilayer include ipstack, the free IP Geolocation API, userstack, the free user agent lookup and device detection API, both of which I wrote about recently for ProgrammableWeb.

Go to Source
Author: <a href="https://www.programmableweb.com/user/%5Buid%5D">jeffreifman</a>