Tomorrow.io's Resilience Platform is Here. Learn More.

X
Tomorrow.io
By Tomorrow.io
Tomorrow.io
Tomorrow.io
Sep 30, 2020ยท 9 min, 52 sec

The Developer’s Guide to Using a Weather API

climacell platform

Table of Contents

What does a weather API do?

Use cases for a weather API

Exploring endpoints in a weather API

Steps involved in Weather API integration

Tips for using weather APIs more effectively

 

Accurate weather information and forecasts are essential elements in critical decision-making scenarios. Both enterprises and individuals consumers rely on current and future weather patterns to run their daily operations and manage risks successfully.ย 

Because of this, the increased demand for accurate weather information has pushed the developer community to invest in building reliable weather apps.

If youโ€™re looking to build a high-precision forecasting app, this article will help you make the best use of a weather API.

What does a weather API do?

Weather APIs provide access to current, historical, and forecast weather data for different locations worldwide. They give access to basic weather information such as humidity, temperature, precipitation, wind speed, wind direction, cloud cover, visibility, and more.

Some also provide additional information on air quality, fire index, road-risks, and pollen. With a weather API, you get all this data for multiple locations regardless of the platforms, devices, technologies, or programming language youโ€™re using.ย 

With a weather API, you can:

  • Process and interpret a broad mix of weather data
  • Use historical records to discover weather trends and patterns
  • Integrate weather monitoring and alerting functionalities on a wide range of applications
  • Access weather and air quality forecasts for any point or city on earth

Use cases for a weather API

Weather information plays an instrumental role in decision-making scenarios. Different industries rely on weather APIs to gather rich weather data and generate deep insights for optimizing business processes and reducing operational costs.ย 

Hereโ€™s a glimpse of some areas that would derive unlimited value from data provided by weather APIs.

  • Government agencies – Helps local and federal agencies enhance public safety by preparing for extreme weather conditions such as storms and hurricanes.
  • Agricultural production – Adjusting the agricultural calendar, improving irrigation infrastructure, changing crop types and varieties, pest and disease control, etc.
  • Trucking and logistics โ€“ Weather data helps in planning safe routes, improving driver safety, minimizing transport delays, and preventing transportation hazards.
  • Aviation – Airlines and drones tap weather data to predict turbulence, identify the best possible path of flight, and improve emergency response.
  • Energy and utilities โ€“ Utility companies use weather data to protect vulnerable stations and transmission infrastructure, thus minimizing service outages and increasing public safety.
  • Insurance – Insurance companies can measure actuarial risks and tweak premiums for different services and locations.
  • Outdoor activities – Allows better planning of outdoor events and activities such as professional games, skiing, boating, skydiving, and more.

As you can see, improved forecasts and meteorological information are very helpful regardless of whether the industry has a direct or indirect connection with weather. This is where a weather API comes in handy – and it can help save not only millions of dollars but also lives.

Exploring endpoints in a weather API

Every weather API has multiple endpoints or types of data that a user can request. To get the most out of the API, you must understand all supported endpoints since they form the basis for all requests made to the API.ย 

www.tomorrow.io supports the following endpoints:

  • Historical โ€“ It allows users to fetch past weather data
  • Real-time โ€“ It enables users to fetch accurate real-time weather information for any location.
  • Forecast – It provides minute-by-minute forecast data up to 360 minutes, hourly forecasts up to 108 hours, and daily forecasts up to 15 days.

Other than these, there is an endpoint for alerts as well as one for maps. When using the API, you can query one or multiple endpoints using a single request.

Steps involved in weather API integration

The following five steps are followed when using any weather API in your application.

Choosing a weather API providerย 

Start by choosing a reliable and hyper-accurate weather API for your forecast needs. The www.tomorrow.io Weather API provides as many data points for different weather and air quality aspects.

With the trial version, you can try out the service before subscribing to a paid plan.
With 1000 calls per day limit on the free version, itโ€™s more than enough for small projects. For a larger enterprise, the paid version would offer more options and more in-depth functionality for any project.

Getting the API key

Like the vast majority of APIs, weather providers use API keys for secure HTTPS authentication. This means every user must provide a valid key in every API request. Otherwise, the API will return an error.ย 

For Tomorrow.io users, you can obtain the API key on the Dashboard, as shown below.

www.tomorrow.io free weather api key

Once you have the key, you can provide it in the request header or pass it as a query parameter.

//API key passed in Query parameters
curl --request POST \
--url 'https://api.www.tomorrow.io/v3/locations?apikey=API_KEY' \
--header 'content-type: application/json'


//API key passed in Request Header
curl --request GET \ 
--url 'https://api.www.tomorrow.io/v3/locations' \
--header 'content-type: application/json'
--header 'apikey: API_KEY'

Making the API call

To call our API, we must first obtain coordinates for the target location. Using Tel Aviv as an example, the city coordinates will be as follows:

tel aviv coordinates

Next, we pass in the target URL, location coordinates, and request parameters to this basic call function.

const request = require('request');request(url, function (err, response, body) {
if(err){
console.log('error:', error);
} else {
console.log('body:', body);
}
}

As illustrated in the code snippet above, we start by using the request package. Next, we pass a target URL and a callback function that holds three arguments: err, response, and body.

If the request is erroneous, we simply log the error. If the request is successful, all contents are logged into the response body.ย 

The code should look like this:

const request = require('request');

const options = {
method: 'GET',
url: 'https://api.www.tomorrow.io/v3/weather/realtime',
qs: {
lat: '32.0853',
lon: '-34.7818',
unit_system: 'si',
fields: 'precipitation,wind_gust,humidity,wind_speed,temp,visibility',
apikey: '9efRx8KrGKa6ME0ORWIJz7TaNjuRQAvb'
}
};

request(options, function (error, response, body) {
if (error) throw new Error(error);

console.log(body);
});

Analyzing the response

A successful API call usually returns a JSON file with the response property as an array of objects. As an example, the API request in the previous step returns the following values:

{
"lat":32.0853
"lon":-34.7818
"temp":{
"value":25.31
"units":"C"
}
"wind_speed":{
"value":2.94
"units":"m/s"
}
"wind_gust":{
"value":3.63
"units":"m/s"
}
"visibility":{
"value":10
"units":"km"
}
"humidity":{
"value":74.81
"units":"%"
}
"precipitation":{
"value":0
"units":"mm/hr"
}
"observation_time":{
"value":"2020-09-14T10:39:13.307Z"
}
} 

This is the unminified version, which is then parsed and fed into an output HTML template.

Enhancing interactivity

After verifying that the API implementation is correct and users can get weather data for any location, it is time to extend your application’s functionality by doing some post-integration enhancements.

One such enhancement is to add real-time alerts and notifications to your system. To do this, you need to call the Tomorrow.io predefined alerts endpoint. Alternatively, you can create custom alerts that are triggered when weather conditions hit or exceed a specified limit.

Other than notifications and warning signals, you can also:

  • Improve the look of your UI
  • Add a search function
  • Integrate maps
  • …and more.

The bottom line here is that there’s no limit to the functionality or features you can embed inside your weather app. You’re only limited by your creativity and imagination.ย 

Tips for using weather APIs more effectivelyย 

There are a number of aspects that come into play when optimizing requests to a weather API, and most of these boil down to speed. Following the practices below will optimize your API requests and ensure your scripts run faster.

Choose a weather API that supports your needs

Before choosing a weather API, you should first understand your forecasting goals. Some applications will require running request scripts every five minutes while others will run on an hourly basis. The forecast interval will depend on your use case.

If you need to send a huge volume of automated scripts within a short time frame, then choose an API package that supports the desired number of calls.ย 

Otherwise, you could end up surpassing the maximum number of daily hits on your account. This kind of limitation when fetching data will hurt your forecast needs.

Integrate maps for enhanced visual interpretation

Maps layers are a valuable addition to any weather application. They give users a better visual representation of weather data and other elements featured in the API. To integrate maps, you can use popular mapping libraries like Google Maps, OpenLayers, or Mapbox.

Using the code below, we can inject Tomorrow.io tiles into MapBox and create a responsive client-side map.

mapboxgl.accessToken = '<Enter your Mapbox access token>';
const CC_API_KEY = '<Enter your Tomorrow.io API key>';
const CC_DATA_FIELD = '<Enter the selected data fields >';
const CC_TIMESTAMP = 'now'; // or any other ISO 8601 timestamp

var map = (window.map = new mapboxgl.Map({
container: 'map',
zoom: 3,
center: [7.5, 58],
style: 'mapbox://styles/mapbox/light-v10',
antialias: true
}));
map.on('load', function () {
map.addSource('www.tomorrow.io-api', {
"type": 'raster',
"tiles": [`https://api.www.tomorrow.io/v3/weather/layers/${CC_DATA_FIELD}/${CC_TIMESTAMP}/{zoom}/{coord.x}/{coord.y}.png?apikey=${CC_API_KEY}`],
"tileSize": 256,
"attribution": '&copy; <a href="https://www.www.tomorrow.io/weather-api">Weather Data Powered by Tomorrow.io</a>'
});
map.addLayer({
"id": "radar-tiles",
"type": "raster",
"source": "www.tomorrow.io-api",
"minzoom": 1,
"maxzoom": 12
});
});

The result is a map image in PNG format covering the specified coordinates.

www.tomorrow.io platform

Remove unnecessary data in your requests

A weather API provides loads of information for each of the supported endpoints. Most clients do not require every single weather or air quality data attribute, as supplied in the default response. As such, developers can tweak the parameter fields to decrease the size of JSON response documents.

By reducing the size of the response to include only relevant fields, every API call will need lesser bandwidth and memory footprint. While reducing the file size by some bytes may not substantially make or break the application, it will help improve load times and performance.

Understand error codes

Typically, if an API request is successful, the error property will be null. However, if the request contains an error or warning, the response property will be an empty array while the error property will contain an HTTP error code followed by an optional description of the error.

For instance, the Tomorrow.io Weather API indicates the outcome of requests using conventional HTTP response codes.ย 

As illustrated in the snippet below, codes in the 4XX range indicate input errors in the query, such as invalid parameters or restricted access. On the other hand, 5XX codes signal a server error (which rarely happens).

//www.tomorrow.io Error Codes

//400 Bad Request
{
"statusCode": 400,
"errorCode": "BadRequest",
"message": "Message body content not allowed."
}

//401 Unauthorized
{
"message": "You must provide a valid authentication method"
}

//403 Forbidden
{
"message": "You cannot consume this service"
}

//429 Too Many Requests
{
"message": "API rate limit exceeded" 
}

//500 Error
{
"statusCode": 500,
"errorCode": "InternalError",
"message": "There was an Internal Error"
}

Having a clear understanding of the error codes makes it easier to identify problems and fix poor implementations.

Finally, do not be afraid to ask for help. The best weather providers will always have a support team in place to provide assistance. In case you’re stuck, feel free to reach out to their staff or developer communities that consume the API for professional help.

There you go! You have all it takes to access hyper-accurate weather data to inform your decision making processes. Take advantage of Tomorrow.io’s high-precision forecasts alongside its proactive alerting and outsmart the weather like never before.

See Tomorrow.io in Action!

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

TOS(Required)

Sign Up for the Tomorrow.io Weather API for Free

Try Now