Skip to content

Commit

Permalink
Added function to call County Business Patterns API
Browse files Browse the repository at this point in the history
  • Loading branch information
crisjf committed May 22, 2020
1 parent aa80ea2 commit 471893f
Showing 1 changed file with 49 additions and 0 deletions.
49 changes: 49 additions & 0 deletions APICalls.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,53 @@ def fetch(url,params=None,nAttempts=5,quietly=True):
def qprint(s,quietly):
print((s if not quietly else ''),end=('' if quietly else '\n'))

def CBPCall(geoList=None,geoLevel='metropolitan statistical area/micropolitan statistical area',NAICS_lvl=None,query=None,base_url = 'https://api.census.gov/data/2017/cbp',quietly=True):
'''
Wrapper to call the census API to get data from the County Business Patterns.
Parameters
----------
geoList : list
List of selected geocodes.
If not provided it will retrieve all geos.
geoLevel : str
Either 'metropolitan statistical area/micropolitan statistical area', 'us', 'county' or 'state'
NAICS_lvl : int
NAICS level at which to filter. If not provided it will not get the data by NAICS.
If zero is provided, it will return the unfiltered table.
query : dict (optional)
If provided, it will override the query generated by the given parameters.
'''
if NAICS_lvl is not None:
if NAICS_lvl not in range(2,7):
raise NameError('NAICS level not supported')
if query is None:
query = {'get':'ESTAB,EMP,GEO_ID'}
if NAICS_lvl is None:
query['NAICS2017'] = '00'
else:
query['NAICS2017'] = '*'
if geoList is None:
query['for'] = '{}:*'.format(geoLevel)
else:
query['for'] = '{}:{}'.format(geoLevel,','.join(geoList))
else:
NAICS_lvl = None

if not quietly:
print(query)
r = fetch(base_url,params=query)
if not quietly:
print(r.url)
df = pd.DataFrame(r.json()[1:],columns=r.json()[0])
if NAICS_lvl is not None:
if NAICS_lvl!=0:
df = df[df['NAICS2017'].astype(str).str.len()==NAICS_lvl]
df['EMP'] = df['EMP'].astype(float)
df['ESTAB'] = df['ESTAB'].astype(float)
return df

def ZBPCall(zipcodeList=None,NAICS_lvl=None,query=None,base_url = 'https://api.census.gov/data/2017/zbp',quietly=True):
'''
Wrapper to call the census API to get data from the Zip Code Business Patterns.
Expand Down Expand Up @@ -66,6 +113,8 @@ def ZBPCall(zipcodeList=None,NAICS_lvl=None,query=None,base_url = 'https://api.c
if not quietly:
print(query)
r = fetch(base_url,params=query)
if not quietly:
print(r.url)
df = pd.DataFrame(r.json()[1:],columns=r.json()[0])
if NAICS_lvl is not None:
if NAICS_lvl!=0:
Expand Down

0 comments on commit 471893f

Please sign in to comment.