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

X
Kelly Peters
By Kelly Peters
Kelly Peters
Kelly Peters
Currently Tomorrow.io's Director of Marketing, Kelly Peters is a growth-focused marketing leader with 10+ years of experience driving strategic communications and demand-focused initiatives for brands like CNBC, NBCUniversal, Dicks Sporting Goods, and JazzHR. At Tomorrow.io, she leads a dynamic team of growth and AI marketers in driving revenue with bold storytelling, radical creativity, and, above all else, human connection. Kelly graduated from Syracuse University and lives in Pittsburgh, PA.
Feb 28, 2022ยท 12 min, 8 sec

How to Use a Weather API

Tomorrow.io's weather API offers over 80 data layers including weather parameters like snow, ice, and rain.

Most people think of weather applications as simple reporting tools to tell them the temperature and conditions for their local area. While this is true for most individuals, businesses can leverage the power of a weather API for far more benefits to protect their assets and keep employees safe. These benefits can also help individuals and your local community to give them insights into weather patterns. Overall, a weather API has numerous benefits that help keep people safe and give them (and businesses) lead time to better prepare for severe conditions.ย 

What Can a Weather API Do for You?

The type of weather data beneficial to your community depends on your location. Wildfire data might not be beneficial for someone in a tropical environment, but tracking floods and heavy rains would be something beneficial for people in tropical environments and flood zones. In most cases, tracking weather data and making predictions can help the community as a whole, but weather APIs also have some enterprise benefits that could be used for business purposes only.

First, let’s look at a real-world scenario that would help individuals within a community. Weโ€™ll take the recent example of severe freezes predicted to hit Texas in February 2022. Severe freezing weather was expected to affect Texas again, and weather data collected from a weather API could help pinpoint geolocations to better warn residents and businesses. Severe weather conditions were expected to affect power sources, and previous freezing weather temperatures left 4.5 million people without power in 2021. The results from not being prepared threatened lives, and freezing temperatures without power was the direct cause for 246 deaths across affected areas.

An Insights Dashboard and Map view from Tomorrow.ioโ€™s platform shows threats from ice and falling temperatures across Cetral Texas beginning Wednesday night.

An Insight Dashboard and Map view from Tomorrow.ioโ€™s platform showing weather conditions across specific regions in Texas.

For businesses, leveraging a weather API has several benefits depending on your location, but most enterprise organizations have strategic office locations to service customers and build revenue. A weather API can track conditions at these specific office locations, but it can also help with safety of employees, improve supply chain delivery routes, or help support customers better during specific times of the day. Here are just a few examples of ways a weather API can help run your business more smoothly:

  • Trucking and supply chain businesses can use a weather API to determine the best path for shipments to avoid severe weather that would cause delivery delays.
  • Sports organizations can determine weather conditions at a specific sporting event to warn spectators to wear appropriate clothes and prepare stadiums for weather conditions such as rain, snow, or heat.
  • Restaurants that have outside seating can determine if it should be available instead of allowing patrons to deal with unforeseen circumstances and ruin their experience.
  • In severe hurricane or tornado conditions, utility organizations can be prepared to respond quickly after the threat is over.
  • Aviation has long used weather data to control flight paths for airline, pilot and passenger safety.
  • Severe winds and rain might require businesses to board up windows or take precautions for flooding.
  • For businesses with employees that commute, for their safety it would be beneficial to know when icy weather could affect roads and allow these employees to stay home and work for the day.
  • Technology functionality is often disrupted by extreme heat or cold, and weather predictions can help businesses prepare for failover.

Making Simple Calls to a Weather API to Collect Weather Data

Using the Tomorrow.io API, we can show you several simple weather API calls to show what it can do for you and how to use a weather API for the first time. Letโ€™s look at the four main Tomorrow.io API endpoints.

Tomorrow.io's weather API makes using wather data easy and effective.

For most API programmers, the Timeline, Map, and Events endpoints are the primary endpoints for applications. The Route endpoint is available to premium customers. Here is a brief overview of each one:

  • Timeline: Collect several data points to get weather conditions across a specific timeframe. For example, collect data for the entire day (24 hours) minute by minute to determine weather conditions for the given timeframe.
  • Map: Use this endpoint to map out conditions in a visual way for your users. For example, show users a visual representation of weather conditions (e.g., rain clouds) in their hometown or place of work.
  • Events: Get a list of events from your insights. Insights are a collection of weather data that meet a specific condition set in your insight configuration (e.g., get a list of times when the geographic region experiences heavy rain or wind), and events are weather conditions that could affect the community (e.g., fires, floods or hurricanes).
  • Route (premium): For premium users, you can track weather conditions along navigational routes. For example, this endpoint is beneficial for shipping companies to route the best path with optimal weather conditions for truckers to take across a geographic location.

Tomorrow.io has a few other endpoints useful for your weather tracking, but the above four are the most commonly used. The Insights endpoint lets you collect data only when a specific condition is met. For example, you can get a list of times when wind speed meets hurricane categories. The Insights endpoints allow you to use several parameters to get only the timeframes and conditions that you need. We have preset insights for several weather conditions such as hurricane, fire, thunderstorms, floods, fog, tornadoes and many more. You can use pre-made insights or create a custom one that fits your interests. Insights are tied to locations, so you must set up a geolocation in your Tomorrow.io dashboard for your account.

Alerts and notifications are two more useful endpoints that tie into insights. The Insights endpoint is used to collect data based on your own input parameters, but the Alerts endpoint triggers when a specific threshold is met. You might get insights on hurricanes in the area, but you only want to trigger an alert when winds reach a specific parameter threshold. Alerts and notifications work hand-in-hand by hooking to your insights feed, triggering an alert, and then using notifications to send a message to your users.

Returning Timeline Data for a Timeframe

Letโ€™s first take a look at the Timeline endpoint. This endpoint is beneficial for basic data collection. If you want to get data for a specific date, you must determine how much data is collected based on the time duration and time steps. For example, suppose that you want to collect weather data for the next day. You set the dates and time and input the increments, such as getting data for every hour, every minute, or every 30 minutes. This collection is the basis of your weather application that you can use to display information to your users.ย 

Here is an example cURL call:

curl --request GET \
--url 'https://api.tomorrow.io/v4/timelines?location=607f3e4188a6a60007947b82&fields=precipitationIntensity%2CprecipitationType%2CwindSpeed%2CwindGust%2CwindDirection%2Ctemperature%2CtemperatureApparent%2CcloudCover%2CcloudBase%2CcloudCeiling%2CweatherCode&units=metric&timesteps=1h&apikey=YOUR_API_KEY' \
--header 'Accept: application/json'

In the above GET request, we use a weather API to get data for 24 hours, but notice that the call specifies the data collected. Here is a truncated data set returned by the above call:

{
    โ€œdataโ€: {
      โ€œtimelinesโ€: [
        {
          โ€œtimestepโ€: โ€œ1hโ€,
          โ€œstartTimeโ€: โ€œ2022-02-10T22:00:00Zโ€,
          โ€œendTimeโ€: โ€œ2022-02-15T10:00:00Zโ€,
          โ€œintervalsโ€: [
            {
              โ€œstartTimeโ€: โ€œ2022-02-10T22:00:00Zโ€,
              โ€œvaluesโ€: {
                โ€œprecipitationIntensityโ€: 0,
                โ€œprecipitationTypeโ€: 0,
                โ€œwindSpeedโ€: 3.19,
                โ€œwindGustโ€: 6.5,
                โ€œwindDirectionโ€: 275.63,
                โ€œtemperatureโ€: 17.13,
                โ€œtemperatureApparentโ€: 17.13,
                โ€œcloudCoverโ€: 0,
                โ€œcloudBaseโ€: null,
                โ€œcloudCeilingโ€: null,
                โ€œweatherCodeโ€: 1000
              }
            },
            {
              โ€œstartTimeโ€: โ€œ2022-02-10T23:00:00Zโ€,
              โ€œvaluesโ€: {
                โ€œprecipitationIntensityโ€: 0,
                โ€œprecipitationTypeโ€: 0,
                โ€œwindSpeedโ€: 2.17,
                โ€œwindGustโ€: 3.79,
                โ€œwindDirectionโ€: 255.21,
                โ€œtemperatureโ€: 14.47,
                โ€œtemperatureApparentโ€: 14.47,
                โ€œcloudCoverโ€: 0,
                โ€œcloudBaseโ€: null,
                โ€œcloudCeilingโ€: null,
                โ€œweatherCodeโ€: 1000
              }
            }
          ]
        }
      ]
    }
  }

The full response has the full 24 hours, but the above JSON contains the first two sets. Data is returned in reverse order, so these two sets contain data for the last 2 hours of the day. It has several weather factors including a weather code. Weather codes give you more end-user friendly ways to display conditions, including icons. They also tell you if the condition is mixed and if it will persist throughout the day. The Tomorrow.io API has a library of weather icons that help you visually display information to your users in a friendly way.

Visually Display Weather Using Tile Output

The Map endpoint returns tile information so that you can build a map with an overlay of weather condition as a visual representation. For example, suppose that you want to get tiles that display cloud cover over a geo-specific location on a map. The map itself can be pulled from a map API such as Google Maps, and then the tiles returned from the weather API overlay cloud images over the map.

Planning and Designing a Weather Application for Android

Basic map layout using tiles with minimal zoom levels

You can zoom in and out based on the detail of the map. The higher the zoom level, the more tiles you get. Tomorrow.io supports zoom levels 1-12. The more you zoom in, the more you can cover a more localized area such as your state, city, or zip code.

The following JavaScript code is a small application that pulls tiles and displays them over a Google Map:ย 

// get your key from app.tomorrow.io/development/keys
const API_KEY = 'add your API key here';

// pick the field (like temperature, precipitationIntensity or cloudCover)
const DATA_FIELD = 'cloudCover';

// set the ISO timestamp (now for all fields, up to 6 hour out for precipitationIntensity)
const TIMESTAMP = (new Date()).toISOString();

// initialize the map
var map = L.map('map', {
ย  ย  minZoom: 3,
ย  ย  maxZoom: 10
}).setView([42.355438, -71.059914], 7);

// set the streetview
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
ย  ย  attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);

// inject the tile layer
L.tileLayer(`https://api.tomorrow.io/v4/map/tile/{z}/{x}/{y}/${DATA_FIELD}/${TIMESTAMP}.png?apikey=${API_KEY}`, {
ย  ย  attribution: '&copy; <a href="https://www.tomorrow.io/weather-api">Powered by Tomorrow.io</a>',
}).addTo(map);

The result is a cloud-covered map that displays to your users.

A visual representation of clouds covering a specific geographic area using Tomorrow.io's weather API.

A visual representation of clouds covering a specific geographic area.

Trigger Alerts and Notifications with Event Information

Events are specific conditions that trigger from insight data. Remember that insights can be from predefined categories or your own customized insight data. For example, you might want to trigger an event when hurricane winds reach severe conditions.ย 

As an example, the following React code monitors insight data for floods, winter conditions, temperature and wind conditions and pulls any events based on severity from this data.ย 

import * as React from "react";
import Chart from "react-google-charts";
import axios from 'axios';

class App extends React.Component {

ย  static defaultProps = {
ย  ย  ย  // get your key from app.tomorrow.io/development/keys
ย  ย  ย  // ideally the request will be proxied by another server-side service, keeping the key secure
ย  ย  ย  apikey: "add your API key here",
ย  ย  ย  // pick the location, as a latlong pair array, GeoJSON geometry or predefined ID
ย  ย  ย  location: "5d6472a671330c000899876e",
ย  ย  ย  // list the insights, can also include custom insights for monitored locations
ย  ย  ย  insights: ["winter", "wind", "temperature", "floods"],
ย  ย  ย  // set the safety buffer around the location, applicable only to insight categories only
ย  ย  ย  buffer: 20
ย  };

ย  constructor(props) {
ย  ย  super(props);
ย  ย  this.state = { events: [] };
ย  };

ย  componentDidMount = () => {
ย  ย  const props = this.props;
ย  ย  const {insights, location, apikey} = props;
ย  ย  // request all events matching the insights for the above-mentioned location
ย  ย  axios({
ย  ย  ย  method: "post",
ย  ย  ย  // set the Events POST endpoint as the target URL
ย  ย  ย  url: `https://api.tomorrow.io/v4/events?apikey=${apikey}`,
ย  ย  ย  data: {
ย  ย  ย  ย  location,
ย  ย  ย  ย  insights,
ย  ย  ย  },
ย  ย  })
ย  ย  ย  .then((response) => {
ย  ย  ย  ย  console.log(response);
ย  ย  ย  ย  this.setState({events: response.data.data.events})
ย  ย  ย  })
ย  ย  ย  .catch((error) => {
ย  ย  ย  ย  console.log(error);
ย  ย  ย  });
ย  }

ย  // build a table of the eventValues to be shown on hover
ย  renderTooltip = (eventValues) => {
ย  ย  return `<table style="width:50px">${Object.keys(eventValues).map((key) =>
ย  ย  ย  typeof eventValues[key] == "object"
ย  ย  ย  ย  ? null
ย  ย  ย  ย  : `<tr><td><strong>${key}</strong></td><td>${eventValues[key]}</td></tr>`
ย  ย  ).join("")}</table>`;
ย  }
ย 

ย  render() {
ย  ย  // configure unique colors, per severity level
ย  ย  const colors = {
ย  ย  ย  "unknown": "#b6c0cc",
ย  ย  ย  "minor": "#ffff42",
ย  ย  ย  "moderate": "#ff7800",
ย  ย  ย  "severe": "#eb002c",
ย  ย  ย  "extreme": "#b80d0a"
ย  ย  };
ย  ย  let data = [
ย  ย  ย  // set the columns of the timeline chart, whereas Name is shown next to each bar and tooltip on hover
ย  ย  ย  [
ย  ย  ย  ย  { type: "string", id: "title" },
ย  ย  ย  ย  { type: "string", id: "Name" },
ย  ย  ย  ย  { type: "string", role: "style" },
ย  ย  ย  ย  { type: "string", role: "tooltip" },
ย  ย  ย  ย  { type: "date", id: "Start" },
ย  ย  ย  ย  { type: "date", id: "End" },
ย  ย  ย  ],
ย  ย  ย  // map all resolved events to the array structure mentioned above, in an orderly fashion
ย  ย  ย  ...this.state.events.map((event) => [
ย  ย  ย  ย  event.eventValues.title,
ย  ย  ย  ย  `severity: ${event.severity} ย  - ย  certainty: ${event.certainty} ย  - ย  urgency: ${event.urgency}`,
ย  ย  ย  ย  colors[event.severity],
ย  ย  ย  ย  this.renderTooltip(event.eventValues),
ย  ย  ย  ย  new Date(event.startTime),
ย  ย  ย  ย  new Date(event.endTime),
ย  ย  ย  ]),
ย  ย  ];
ย  ย  return (
ย  ย  ย  <div>
ย  ย  ย  ย  {this.state.events.length > 0 && (
ย  ย  ย  ย  ย  <div
ย  ย  ย  ย  ย  ย  style={{
ย  ย  ย  ย  ย  ย  ย  margin: "auto",
ย  ย  ย  ย  ย  ย  ย  padding: "5% 5%",
ย  ย  ย  ย  ย  ย  ย  display: "flex",
ย  ย  ย  ย  ย  ย  ย  flex: "auto",
ย  ย  ย  ย  ย  ย  ย  flexFlow: "row wrap",
ย  ย  ย  ย  ย  ย  }}
ย  ย  ย  ย  ย  >
ย  ย  ย  ย  ย  ย  <Chart
ย  ย  ย  ย  ย  ย  ย  width={"100%"}
ย  ย  ย  ย  ย  ย  ย  height={"100vh"}
ย  ย  ย  ย  ย  ย  ย  chartType="Timeline"
ย  ย  ย  ย  ย  ย  ย  loader={<div>Loading Events</div>}
ย  ย  ย  ย  ย  ย  ย  data={data}
ย  ย  ย  ย  ย  ย  ย  options={{
ย  ย  ย  ย  ย  ย  ย  ย  tooltip: { isHtml: true },
ย  ย  ย  ย  ย  ย  ย  ย  colors: Object.values(colors),
ย  ย  ย  ย  ย  ย  ย  }}
ย  ย  ย  ย  ย  ย  ย  rootProps={{ "data-testid": "7" }}
ย  ย  ย  ย  ย  ย  />
ย  ย  ย  ย  ย  </div>
ย  ย  ย  ย  )}
ย  ย  ย  </div>
ย  ย  );
ย  }
}

export default App;

The React code creates a basic dashboard so that users can monitor these events. To see more of this application, see the Tomorrow.io Github repository to download and review the way you can use event data to monitor weather conditions.

Use the Tomorrow.io weather API to send alerts and notifications to users

The above dashboard monitors severity and displays it in the userโ€™s browser, but you can also use the Tomorrow.io weather API to send alerts and notifications to users. For example, alerts and notifications are useful for businesses with several locations around the world during specific catastrophes or conditions when employees might be unable to get to the office or work from home due to outages.ย 

Conclusion

The first step to fully leveraging a weather API is to figure out how you want to use it. It could be a dashboard to help businesses stay updated on conditions to improve supply chain efficiency and employee safety, or it could be a personal project that helps you monitor weather conditions for your community.

The code snippets we shared are just a very small way the Tomorrow.io API can help you create weather monitoring applications that fit your business or personal needs. Itโ€™s easy to use, gives you accurate minute-by-minute information, and makes it easy for you to send notifications to affected individuals. It can improve your business productivity by keeping employees informed and safe, and it can improve the way your business ships and packs products and services that save money by avoiding severe conditions.

 

Tomorrow.io's weather API offers a best-in-class interface with 80+ data layers to choose from historical, real-time, and forecast weather data.

Sign Up for the Tomorrow.io Weather API for Free

Try Now