Created
August 19, 2017 17:22
-
-
Save adamabernathy/52f45c079e63eafcb910a7ef931299a2 to your computer and use it in GitHub Desktop.
Python example using urllib, urllib2 and json to interface with the SL Mesonet API
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from urllib import urlencode | |
from urllib2 import Request, urlopen, URLError, HTTPError | |
import json | |
def fetch_data(service, parameters={}, debug=False): | |
'''Calls the Mesonet API service and returns data as a dictionary''' | |
baseurl = 'https://api.mesowest.net/v2/' | |
_parameters = urlencode(parameters) | |
payload = None # Set default to None, so you can catch errors later | |
req = Request(baseurl + service, _parameters) | |
try: | |
response = urlopen(req) | |
except URLError as e: | |
if hasattr(e, 'reason'): | |
print 'We failed to reach a server Reason: ', e.reason | |
elif hasattr(e, 'code'): | |
print 'The server couldn\'t fulfill the request. Error code: ', e.code | |
else: | |
# Looks like everything worked, so parse the JSON response and send it back to the user. | |
print 'Payload\n: %s' % response.read() if debug else '' | |
try: | |
payload = json.loads(response.read()) | |
except: | |
print 'JSON decode error. More than likely a CSV response.' | |
return | |
return payload | |
if __name__ == "__main__": | |
api_response = fetch_data('networks', {'token' : 'demotoken'}) | |
# To make sure it worked | |
if api_response is not None: | |
for item in api_response['SUMMARY']: | |
print item, api_response['SUMMARY'][item] | |
else: | |
print 'Rhut Rhow! There was a problem with the response and it could not be parsed.' | |
# Now for the timeseries verificiation | |
api_response = fetch_data( | |
'stations/timeseries', | |
{ | |
'token' : 'demotoken', | |
'stid': 'KSLC', | |
'start': 199701010000, | |
'end': 201506020000, | |
'vars': 'wind_speed' | |
}, | |
debug=True | |
) | |
# To make sure it worked | |
if api_response is not None: | |
for item in api_response['SUMMARY']: | |
print item, api_response['SUMMARY'][item] | |
else: | |
print 'Rhut Rhow! There was a problem with the response and it could not be parsed.' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment