Build a Weather Pattern Animation with the Dark Sky API [Python]

RapidAPI Team
The Era of APIs
Published in
8 min readMar 4, 2020

A few days back, we published a comparison post on two popular weather service APIs, Dark Sky and OpenWeatherMap. In this post, we are going to show you how to make use of the weather data from Dark Sky API to build some animated visualizations.

In recent years, debates around weather and weather conditions have always sparked arguments on global warming. As much as we want to deny it, we feel it every year, with summers getting hotter and winters shrinking. There is no better way to prove this than using data, and Dark Sky API offers us a lot of possibilities to play with weather parameters.

In this post, we are going to build a python script to capture weather forecasts and present the weather parameters through an animated visualization.

Connect to the Dark Sky API

Overview of Dark Sky API

The Dark Sky API provides both the current forecasts as well as historical weather data for a given location identified by its location coordinates. It offers an extensive set of weather parameters. Apart from the typical data around temperature, humidity, pressure, it also has access to not so frequently observed phenomena such as ozone level and cloud cover.

You can take a closer look at the API endpoints via the Dark Sky API console.

The API endpoints are pretty self-explanatory.

The “GET Forecast” endpoints give you the current weather forecast for a given location, whereas the “GET Time Machine” gives you the historical forecast for a given location on a given day in the past.

How to get access to the Dark Sky API

1. Sign Up for RapidAPI Account

To begin using the Dark Sky API, you’ll first need to sign up for a free RapidAPI developer account. With this account, you get a universal API Key to access all APIs hosted in RapidAPI.

RapidAPI is the world’s largest API marketplace, with over 10,000 APIs and a community of over 1,000,000 developers. Our goal is to help developers find and connect to APIs to help them build amazing apps.

2. Subscribe to Dark Sky API

Once signed in, log in to your RapidAPI account and access the API console. Click on the “Pricing” tab and opt-in for the basic subscription that gives you 100 free API calls to Dark Sky API per month.

Is the Dark Sky API free?

The Dark Sky API is free up to 100 API calls/month. After 100 calls in one month, you’ll be charged $0.001 per additional API request.

3. Test Your API Subscription

It’s time to do a test run of the Dark Sky API.

Select the “GET Forecast” endpoint within the API console. Enter the values for the ‘latitude and ‘longitude’ parameters as shown, and click the Test Endpoint button.

This triggers the API to return the current forecast for New York City, as defined by the location coordinates.

The API response contains a JSON envelope containing several forecasts, including the current, hourly as well as daily forecast. The hourly forecast extends to 48 hours from the present time, and the daily forecast extends to the next seven days.

Connect to the Dark Sky API

How to use the Dark Sky API in Python to Building Animated Weather Patterns

To visualize weather patterns, you first have to build a dataset to accumulate weather data for a range of days. Using the Dark Sky API, there are two ways you can achieve this.

You can either take the hourly or daily forecasts provided with the current forecast returned from the “GET Forecast” endpoint. Alternatively, if you want to consider a more extended range, then “GET Time Machine” is your best friend. With “GET Time Machine,” you can accumulate historical weather forecasts for particular days, such as the beginning of every year, and build a sizable data set to witness the trends.

To keep things simple, and keeping in mind the limits of free API calls under the basic subscription of Dark Sky API, we will use the “GET Forecast” endpoint and build the dataset using the daily forecast for the next seven days.

Let’s write a python script to build a dataset for the forecast of the next seven days for New York City. Before you begin, ensure that you have the right set of tools and libraries installed for the development environment.

  1. Python 3 Runtime: You must have a Python 3 runtime installed.
  2. Requests library: You must have the requests library installed on your Python 3 runtime. You can use the pip command “ pip install requests” to install it.

Open your favorite code editor and create a new file named weather_capture.py. Follow along the step below to build the code logic.

1. Define the imports and globals

To begin with, you have to import the libraries that are used in the script. The script also uses the RapidAPI key to invoke the Dark Sky API. A global variable is defined to contain the key. We have used another global variable to store the location coordinates of New York City.

import sys
import json
import requests
import csv
from datetime import datetime, date, time, timedelta, timezone

LOCATION = "40.73,-73.93"

RAPIDAPI_KEY = "<YOUR_RAPIDAPI_KEY>"

**Make sure to replace the placeholder <YOUR_RAPIDAPI_KEY> with your RapidAPI subscription key.**

2. Define a function for triggering Dark Sky API

Every time the script runs, it makes a call to the Dark Sky API to get the current forecast from the “GET Forecast” endpoint. Let’s define a separate function for that.

def trigger_api():

url = "https://dark-sky.p.rapidapi.com/" + LOCATION

querystring = {"lang":"en","units":"auto"}

headers = {
'x-rapidapi-host': "dark-sky.p.rapidapi.com",
'x-rapidapi-key': RAPIDAPI_KEY
}

response = requests.request("GET", url, headers=headers, params=querystring)

if(200 == response.status_code):
return json.loads(response.text)
else:
return None

The API URL takes the location from the global variable that we defined earlier. The query string defines the language and dimension for the weather parameters.

3. Initialize the Script with Starting Data/Time

We now move to the main logic of the script. In the beginning, the script triggers the API by calling the trigger_api( ) function. Afterward, it captures the timestamp from the returned response to get the current date.

print("Getting Weather Data For Next Sever Days")

api_response = trigger_api()

current_date = datetime.fromtimestamp(api_response["currently"]["time"])

4. Parse API Response To Build The Weather Dataset

As we saw earlier, the API response returns multiple forecasts, including daily forecasts for the next seven days. We pick up a few essential parameters from the daily forecast and dump them in a CSV file with a timestamp in YYYYMMDD format.

with open('Weather_Data-' + current_date.strftime("%m-%d-%Y") +  '.csv', 'w',newline='') as csv_file:

csv_writer = csv.writer(csv_file)

csv_writer.writerow(["Parameter","Time", "Value"])

for record in api_response["daily"]["data"]:

try:

time = record["time"]
tempH = record["temperatureHigh"]
tempL = record["temperatureLow"]
humidity = int(record["humidity"] * 100)
cloud = int(record["cloudCover"] * 100)


time_of_day = datetime.fromtimestamp(time).strftime("%Y%m%d")

print("Adding Record for " + time_of_day)
csv_writer.writerow(["Temp High",time_of_day,tempH])
csv_writer.writerow(["Temp Low",time_of_day,tempL])
csv_writer.writerow(["Humidity",time_of_day,humidity])
csv_writer.writerow(["Cloud Cover",time_of_day,cloud])

except TypeError as e:

print(e)
print("Type Error...Ignoring")

except csv.Error as e:

print(e)
print("CSV Error...Ignoring")


csv_file.close()

This will build a CSV record for the next seven days that contains the highest temperature, lowest temperature, humidity, and cloud cover for each day.

We add the customary exception checks and scope definition for __main__ context to give a final look to the script.

import sys
import json
import requests
import csv
from datetime import datetime, date, time, timedelta, timezone

LOCATION = "40.73,-73.93"

RAPIDAPI_KEY = "<YOUR_RAPIDAPI_KEY>"

def trigger_api():

url = "https://dark-sky.p.rapidapi.com/" + LOCATION

querystring = {"lang":"en","units":"auto"}

headers = {
'x-rapidapi-host': "dark-sky.p.rapidapi.com",
'x-rapidapi-key': RAPIDAPI_KEY
}

response = requests.request("GET", url, headers=headers, params=querystring)

if(200 == response.status_code):
return json.loads(response.text)
else:
return None

if __name__ == "__main__":

try:

print("Getting Weather Data For Next Sever Days")

api_response = trigger_api()

current_date = datetime.fromtimestamp(api_response["currently"]["time"])

with open('Weather_Data-' + current_date.strftime("%m-%d-%Y") + '.csv', 'w',newline='') as csv_file:

csv_writer = csv.writer(csv_file)

csv_writer.writerow(["Parameter","Time", "Value"])

for record in api_response["daily"]["data"]:

try:

time = record["time"]
tempH = record["temperatureHigh"]
tempL = record["temperatureLow"]
humidity = int(record["humidity"] * 100)
cloud = int(record["cloudCover"] * 100)


time_of_day = datetime.fromtimestamp(time).strftime("%Y%m%d")

print("Adding Record for " + time_of_day)
csv_writer.writerow(["Temp High",time_of_day,tempH])
csv_writer.writerow(["Temp Low",time_of_day,tempL])
csv_writer.writerow(["Humidity",time_of_day,humidity])
csv_writer.writerow(["Cloud Cover",time_of_day,cloud])

except TypeError as e:

print(e)
print("Type Error...Ignoring")

except csv.Error as e:

print(e)
print("CSV Error...Ignoring")


csv_file.close()

except Exception as e:

print("Major Exception ...Aborting")
sys.exit(e)

5. Run the script

Now the script is ready to generate the weather dataset for New York City.

In case you want to capture the weather dataset from some other area, change the value of the LOCATION global variable to contain the latitude and longitude coordinates of the city, and we are good to go.

Run the script via the Python3 interpreter. The CSV file will be created in the same path as the script. Open the file to check that the data is captured correctly for the parameters we have extracted from the API response.

6. Visualize the Weather Patterns

There are scores of data visualization libraries that you can use to visualize this dataset. However, instead of writing additional code, why not use some of the well-known tools that can readily ingest the data.

Gapminder is one such tool that visualizes data in the form of animated patterns. It is part of the Gapminder foundation started by late Hans Rosling, a Swedish expert who has famously used this tool to tell stories with data about the impending realities of the world. Since climate change is also one such critical issue, this tool is well suited for showcasing the worsening weather patterns around the globe.

You can download the Gapminder tool from here.

Once you install the Gapminder tool, you can directly import the generated dataset and build a visualization pattern of the weather parameters that we have captured.

See video here: https://rapidapi.com/blog/wp-content/uploads/2020/02/Gapminder_Screencast.mp4?_=1

Voila!

You are now witnessing the weather patterns in the form of an animated line chart.

Connect to the Dark Sky API

Conclusion

If you find this idea interesting, then you can try extending this dataset. With the help of historical weather patterns, you can build a large dataset to get more fascinating trends.

In case you are wondering how this is possible, take a look at this Video by the great Hans Rosling himself, telling a story of how the world has changed in the last 200 years.

https://youtu.be/BPt8ElTQMIg

Now it’s your time to build a similar story with Dark Sky API that shows how the world weather has changed in the last few years.

Originally published at https://rapidapi.com on March 4, 2020.

--

--