Climate Data at Your Command: Navigating NASA Power API with Python

Axel Castro
MCD-UNISON
Published in
4 min readApr 15, 2024
NASA Prediction Of Worldwide Energy Resources

The current post will briefly explain how to use Python to retrieve climate data from the NASA Power API.

Climate information plays a fundamental role in understanding and addressing not only environmental challenges, but also in decision-making in many industries, from agriculture to urban planning and natural resource management. In this article, we will delve into leveraging the NASA Power API to access reliable climate data programmatically using Python. Whether you are a climate scientist, a data enthusiast, or both, the NASA Power API offers a gateway to a wealth of valuable climate information.

Understanding the NASA Power API.

NASA, known for sending humans to the moon and robots to Mars, also offers a wealth of data about our own planet through the “Prediction Of Worldwide Energy Resources (POWER) project. This was initiated with the purpose of improving, from satellite systems, data sets related to Renewable Energy, Sustainable Buildings, and Agroclimatology. Through its API, NASA allows us to access its extensive collection of climate data using custom scripts, which provides great flexibility to users. One of the most impressive features of this API is its global coverage, offering historical data dating back several decades, even if you need climate data from your own backyard. Now that we have covered the fundamental features, we are prepared to delve into the technical aspects of how to interact with the API and extract data from it.

Getting Ready

For this tutorial, we are using Jupyter Notebook, so first, to interact with the NASA Power API, we will need to set up our Python environment. This involves installing the necessary libraries.

import pandas as pd
import numpy as np
import requests
import datetime
import csv

Additionally, we need to create the directories where the data will be downloaded.

subdir = "./data/"
# Input file directory for coordinates
input_coord = 'data/Data_In/Coordinates.csv'
# Output folder directory for raw data
output = "data/Raw/"

# Create the output folder if it doesn't exist
if not os.path.exists(output):
os.makedirs(output)

Moreover, it is necessary to load the dataframe that contains locations with their corresponding latitudes and longitudes. Subsequently, we group these locations into a list of tuples before incorporating them into the API query.

# Read input file for state coordinates
coord = pd.read_csv(input_coord)
# List of coordinates
locations = [(lat, lon) for lat, lon in zip(coord['lat'], coord['lon'])]

There’s just one more step to prepare the query. You need to specify the start and end dates, as well as the parameters you want to download. For this, you can refer to the provided link, where you can find a dictionary of parameters. For this example, we will use the following parameters.

All set! With the following code, you’re now ready to query the NASA POWER API and download the specific climate data you need

# Parameters to download
parameter = 'TS,TS_MAX,TS_MIN,T2M,T2M_MAX,T2M_MIN,T2MDEW,T2MWET,PS,WS2M,RH2M,EVPTRNS,GWETPROF,CLRSKY_DAYS,PRECTOTCORR,SG_DAY_HOURS,MIDDAY_INSOL'

# Select the start date, for example, the first day of the year 2023
start_day = '20230101'
# Select the end date, for example, the current date
end_day = datetime.datetime.now().strftime('%Y%m%d')

# URL for the query, which will download the data in CSV format
base_url = r"https://power.larc.nasa.gov/api/temporal/daily/point?parameters={parameter}&community=RE&longitude={longitude}&latitude={latitude}&start={start_day}&end={end_day}&format=CSV"

Allow the code to do the work for you.

Now, we simply create a loop that goes through each location, identified by its coordinates. This loop is responsible for creating and sending the query URL to the NASA POWER API. If the query is successful, the data will be saved in the output directory that we previously set up.

# Data download by location
# Iterates over the location and their coordinates
for location, latitude, longitude in zip(coord['location'], coord['lat'], coord['lon']):
# Forms the query URL
api_request_url = base_url.format(longitude=longitude, latitude=latitude, parameter=parameter, start_day=start_day, end_day=end_day)
# Makes the API query
response = requests.get(url=api_request_url, verify=True, timeout=30.00)

# If the query was successful, save the file in the output folder
if response.status_code == 200:
content = response.content.decode('utf-8')
filename = f"Data_{location}.csv"
filepath = os.path.join(output, filename)

# Saves the file in the output folder
with open(filepath, 'wb') as file_object:
file_object.write(response.content)

print("Data downloaded")

If everything has gone as planned, you should have a dataframe similar to this one:

And that’s all!

We have successfully executed a customized query to the NASA POWER Project API. In this procedure, we have acquired specific hourly climatic data corresponding to our locations and dates of interest. With this data at our disposal, we are prepared to proceed with the analysis and integrate this climatic information into our project.

--

--