Kaden Shaw
Kaden Shaw

Reputation: 11

Accessing weather information with NOAA

I was following a tutorial at https://towardsdatascience.com/getting-weather-data-in-3-easy-steps-8dc10cc5c859 and ran into a problem, if I copied and pasted the code exactly how they had it, it worked fine. However, if I change the station ID then I got an error, it doesn't matter which station I changed it to.

import requests
import numpy as np
import pandas as pd
import json
from datetime import datetime
import matplotlib.pyplot as plt


Token = 'YourTokenHere'

station_id = 'GHCND:USW00023129'
station_id1 = 'GHCND:USC00107689'
station_id2 = 'GHCND:USW00003122'

#initialize lists to store data
dates_temp = []
dates_prcp = []
temps = []

#for each year from 2015-2019 ...
for year in range(2015, 2017):
    year = str(year)
    print('working on year '+year)
    
    #make the api call
    r = requests.get('https://www.ncdc.noaa.gov/cdo-web/api/v2/data?datasetid=GHCND&datatypeid=TAVG&limit=1000&stationid='
                     +station_id1+'&startdate='+year+'-01-01&enddate='+year+'-12-31', headers={'token':Token})
    
    
    #load the api response as a json
    d = json.loads(r.text)
    #get all items in the response which are average temperature readings
    avg_temps = [item for item in d['results'] if item['datatype']=='TAVG']
    #get the date field from all average temperature readings
    dates_temp += [item['date'] for item in avg_temps]
    #get the actual average temperature from all average temperature readings
    temps += [item['value'] for item in avg_temps]

If I use station_id GHCND:USW00023129 it works fine. If I use station_id1 or 2 (or any other station_id, I've tried several) I get this error:

runfile('D:/Code/Weather/Weather.py', wdir='D:/Code/Weather')
working on year 2015
Traceback (most recent call last):

  File "D:\Code\Weather\Weather.py", line 36, in <module>
    avg_temps = [item for item in d['results'] if item['datatype']=='TAVG']

KeyError: 'results'

Thanks

Upvotes: 1

Views: 1995

Answers (1)

mdoc-2011
mdoc-2011

Reputation: 2997

"results" is returning a key error because your .get is not returning a response. It seems that NOAA has updated their api formats at some time, and a lot of the material out there is not quite working anymore, including the referenced Towards Data Science article.

If you are just getting started, this format will return a json file with results, and hopefully you can adapt it from there:

import requests
import json
from datetime import datetime

token = 'yourtoken'

url = "http://www.ncdc.noaa.gov/cdo-web/api/v2/data?datasetid=GHCNDMS&startdate=1776-07-04&enddate=1776-09-04"
headers = {"token":token}

r = requests.get(url, "dataset", headers = headers).text
print(r)
response = json.loads(r)
response = response['results']
response = response[0]
print(response)

Upvotes: 0

Related Questions