wiki:BISONApi
Last modified 5 years ago Last modified on 05/06/13 10:25:18

BISON API

Python script for automating download of data from http://bison.usgs.ornl.gov

#BISON_API.py
#
# Description: Downloads data from the USGS BISON portalusing its API
#  (http://bison.usgs.ornl.gov/services.html)
#
# April 2013
# John.Fay@duke.edu

import sys, os, urllib, json

def GetBisonData(FIPS):
    OutCSV = "C:\Temp\BISON_API\%s.txt" %FIPS

    # Set up the URL
    server = "http://bison.usgs.ornl.gov/api/search?count=1000000"
    county = "&countyFIPS=%s" %FIPS
    URL = server + county

    # Get the data
    print "Sending request: %s" %URL
    data = json.load(urllib2.urlopen(URL))
    recs = data["data"]

    # Creat the CSV and write headers
    print "Writing results"
    fileObj = open(OutCSV,'w')
    columns = recs[0].keys()
    #Write the column headers
    for col in columns:
        if col <> columns[-1]:
            fileObj.write("%s\t" %col)
        else:
            fileObj.write("%s\n" %col)

    #Loop through the records and write to the file
    for obs in recs:
        for col in columns:
            if col <> columns[-1]:
                fileObj.write("%s\t" %(obs[col]).encode('utf-8'))
            else:
                fileObj.write("%s\n" %(obs[col]).encode('utf-8'))

    fileObj.close()
    print "Finished"

# Run for the set of fips
for FIPS in ("06043","06039","06019","06107"):
    GetBisonData(FIPS)