Skip to main content

How to Format API Requests to Loop through All TracksTracts in a County

Source Link

How to Format API Requests to Loop through All Tracks in a County

I wrote this code to get specific ACS data for a set of years for all the tracts in Wake County (id 37187) in the state of North Carolina. I've read the census example of how to format the code to get it for certain counties, but haven't been able to figure that out with this implementation. What do I need to put in my predicates["for"] variable to do this?

import requests
import pandas as pd

HOST, dataset = "https://api.census.gov/data", "acs/acs1"

get_vars = ['B25045_001E', 'B25045_001M']
get_vars = ["NAME"] + get_vars

print(get_vars)

predicates = {}
predicates["get"] = ",".join(get_vars)
#not sure how to add to this
predicates["for"] = "state:37"

# initialize data from collector

dfs = []
columns = ["ID", "Estimate", "Estimate_moe", "ID", "Year", "RMOE"]
for year in range(2011, 2018):
    base_url = "/".join([HOST, str(year), dataset])
    r = requests.get(base_url, params=predicates)
    df = pd.DataFrame(columns=r.json()[0], data=r.json()[1:])
    # add column to hold year value
    df["year"] = year
    df['B25045_001M'] = df['B25045_001M'].astype(int)
    df['B25045_001E'] = df['B25045_001E'].astype(int)

    df["RMOE"] = 100 * df['B25045_001M'] / df['B25045_001E']
    dfs.append(df)


nc = pd.concat(dfs)
print(nc.head)