import os
import requests
# Set the three keys once, as above, before you start Jupyter
# Say whether each key is set, without ever printing the key itself
for name in ["CENSUS_KEY", "FRED_KEY", "EIA_KEY"]:
print(f"{name}: {'set' if os.environ.get(name) else 'MISSING'}")
census_key = os.environ.get("CENSUS_KEY")
fred_key = os.environ.get("FRED_KEY")
eia_key = os.environ.get("EIA_KEY")
# Every request in this chapter says who is asking, as chapter 1's did; put your own address here
HEADERS = {"User-Agent": "WebDataScience/1.0 (your-email@colorado.edu)"}
# CENSUS_KEY: set
# FRED_KEY: set
# EIA_KEY: set11 Government Data APIs
- Keep API keys out of your notebooks, in environment variables, and check that each one is set without printing it
- Find what an API offers before you ask for it: go from a table on the Census Bureau’s website to its group and variables in the API, and get the same numbers back for a state, a county, and a city
- Ask FRED to transform a series before it sends it: percent changes, annual averages, and other units and frequencies
- Ask the EIA to filter its data before it sends it, with routes, facets, data columns, and sorting, and page through a large result with
offsetandlength - Join two agencies’ data on a shared identifier, through a crosswalk when their codes differ, and check the rows that don’t match
- Trace a number on an agency’s website to the API request that returns it
Run this chapter’s code as you read: open the companion notebook (see Appendix A for all of them).
11.1 Public Data by Mandate
Government APIs exist because a law or a public charter says the data must be published, not because publishing it suits a business plan. This chapter uses three of them:
- The U.S. Census Bureau. The Constitution requires a count of the population every ten years, and the Bureau’s American Community Survey (ACS) asks a sample of households about income, housing, work, and much else every year.
- FRED (Federal Reserve Economic Data), from the Federal Reserve Bank of St. Louis. FRED collects more than 800,000 time series from the agencies that produce them, among them the Bureau of Labor Statistics, the Bureau of Economic Analysis, and the Census Bureau, and serves them in one format.
- The U.S. Energy Information Administration (EIA). The Department of Energy Organization Act of 1977 made the EIA the department’s statistical agency, and it publishes what the country produces, buys, and pays for energy, state by state.
As a result, these APIs embody the openness value described in Chapter 3: public data, freely accessible, maintained by public mandate rather than platform goodwill. They also tend to be more stable than commercial offerings, since an agency doesn’t pivot its business model or get acquired. But they are often less polished: the documentation can be dense, variable names cryptic, and error messages unhelpful.
Each of the three teaches one general idea about APIs, which you will meet again in every API you use:
| API | The idea | What you’ll do |
|---|---|---|
| Census | What can I ask for? | Find a table’s group and its variables in the API’s catalogs before asking for data |
| FRED | Let the server compute | Ask for percent changes and annual averages instead of computing them |
| EIA | Let the server filter | Narrow a route to one state, one sector, and one column, and page through the rest |
11.2 API Key Management
Each of these APIs asks for an API key: a unique string that identifies your application, tracks your usage, and enforces rate limits. Proper key management is a professional practice that applies to every authenticated API in this book and beyond.
11.2.1 Get Your Keys
This chapter uses three keys, all free. Request them now: most arrive in minutes, but the Census key works only after you click the link in its email. Each one gets a name, the environment variable your code will read it from:
- The Census Bureau: request a key at https://api.census.gov/data/key_signup.html, and store it as
CENSUS_KEY. - FRED (Federal Reserve Economic Data): create a free FRED account, request a key at https://fred.stlouisfed.org/docs/api/api_key.html, and store it as
FRED_KEY. - The EIA (U.S. Energy Information Administration): request a key at https://www.eia.gov/opendata/register.php, and store it as
EIA_KEY.
Never hardcode API keys in your notebooks. If you share your notebook (on GitHub, in a class submission, with a collaborator), your key goes with it. Store each key as an environment variable instead, and read it at the top of your notebook.
11.2.2 Setting Environment Variables
An environment variable is a name and a value that a program receives from whatever started it, once, when it starts. A terminal reads its settings when it opens, and Jupyter receives its variables from the terminal or app that started it. Neither notices a variable set afterward. So whichever way you set a key, finish with a fresh start:
- Quit Jupyter if it’s running: in JupyterLab, File → Shut Down, or press Control-C in the terminal that’s running it and confirm. In VS Code, quit VS Code itself. Restarting the kernel isn’t enough: a new kernel gets its variables from the Jupyter that is still running, which never received the key.
- Close the terminal where you set the key, and open a new one: on Windows, a new Anaconda Prompt or Command Prompt. If you start Jupyter from Anaconda Navigator, quit Navigator and open it again.
- Check, then start Jupyter from the new terminal, as each way below shows.
Set the keys once, in one of two places:
In the
webdataenvironment. Conda can store variables with an environment, and sets them whenever the environment is active, whether you start Jupyter from a terminal or from Anaconda Navigator. This is the simpler choice for this course. In a terminal (on Windows, the Anaconda Prompt), run one line per key, with your own key in the quotes:The variables arrive only when the environment is activated, so follow the three steps above. Quit Jupyter if it’s running, close this terminal, and open a new one. In the new one, activate the environment, check that a key is set without printing it, and start Jupyter:
From Anaconda Navigator, quit it, open it again, choose the
webdataenvironment, and launch Jupyter.conda env config vars list -n webdatashows what is set; it prints the keys themselves, so don’t paste its output anywhere.In your shell. Each operating system has its own way to store a variable for every program you start afterward. Use the one for yours, with your own keys in the quotes.
macOS. The Mac’s terminal runs zsh, its default shell, which reads the file
~/.zshrceach time a terminal opens. Open it in a text editor from the terminal (nanosaves with Control-O and quits with Control-X), and add one line per key at the end:Then follow the three steps above. Quit Jupyter if it’s running, close this terminal, and open a new one, which reads the new
~/.zshrc. In the new one, check that a key is set without printing it, and start Jupyter from it:A Jupyter started from Anaconda Navigator on a Mac doesn’t read
~/.zshrc, which is one reason to prefer thewebdataenvironment.Linux. Most Linux systems run bash, which reads
~/.bashrc. The lines are the same; only the file differs:Then quit Jupyter if it’s running, close this terminal, open a new one, check, and start Jupyter from it:
Windows. In a Command Prompt or the Anaconda Prompt,
setxstores a variable for your user account, one line per key:Variables set with
setx“are available in future command windows only, not in the current command window,” as Microsoft’s documentation puts it. So quit Jupyter if it’s running, close the prompt, open a new one, check, and start Jupyter from it:
The Missing Manual’s Chapter 34: Environment Variables and Secrets explains both, and a third way, a .env file read by python-dotenv.
11.2.3 Reading the Keys in Python
Every code block in the rest of this chapter assumes census_key, fred_key, eia_key, and HEADERS are defined. os.environ.get() returns None for a variable that isn’t set; os.environ["CENSUS_KEY"], with square brackets, raises a KeyError instead. Either way, the variable isn’t there.
11.2.4 When a Key Says MISSING
If a line says MISSING, or os.environ["CENSUS_KEY"] raises KeyError, the Python running your notebook received no variable by that name. Setting it somewhere isn’t enough: it has to be set where Jupyter can see it, before Jupyter starts. The usual causes:
- Jupyter started before the variable was set, or from somewhere else.
exportsets a variable in one terminal window, for the programs you start from that window afterward. A Jupyter that was already running, or that you started from Anaconda Navigator, another terminal, or VS Code, never receives it. Quit Jupyter and start it again from the terminal where you ranexport, or store the keys in thewebdataenvironment, which every way of starting Jupyter in it receives. Restarting the kernel from inside Jupyter doesn’t help: the new kernel gets its variables from the same Jupyter. exportran in a notebook cell. A cell such as!export CENSUS_KEY="..."starts a shell, sets the variable in that shell, and closes it; the notebook’s Python never sees it, and your key is now saved in the notebook.exporton Windows. Windows has noexportcommand. Usesetx, as above, then open a new prompt:setxchanges only windows opened after it.conda env config vars set, without reactivating. The variables arrive the next time the environment is activated. Quit Jupyter, close the terminal, open a new one, runconda activate webdata(or quit and reopen Navigator), and then start Jupyter.- A different name. The name must match exactly, in capitals:
CENSUS_KEY, notcensus_keyorCENSUS_API_KEY.
When you can’t find the cause and need to keep working, ask for the missing keys in the notebook itself. getpass() shows a password box under the cell; what you paste isn’t displayed, isn’t saved in the notebook, and lasts until the kernel restarts:
from getpass import getpass
# Ask only for keys that are missing; what you paste stays out of the notebook
for name in ["CENSUS_KEY", "FRED_KEY", "EIA_KEY"]:
if not os.environ.get(name):
os.environ[name] = getpass(f"{name} isn't set. Paste it here: ")
census_key = os.environ["CENSUS_KEY"]
fred_key = os.environ["FRED_KEY"]
eia_key = os.environ["EIA_KEY"]To use it:
- Run the cell. If a key is missing, a box opens under the cell, with the words
CENSUS_KEY isn't set. Paste it here:. In VS Code, the box opens at the top of the window instead. If every key is set, the cell does nothing, so it is safe to leave in a notebook you run from the top. - Click in the box, paste the key, and press Enter. Nothing shows as you paste, or only dots, so you can’t check what you pasted: copy the whole key again if you’re unsure. The box asks again for each key that’s missing.
- Wait for the cell to finish. Until you press Enter, the cell shows
[*]and no other cell will run. A notebook that seems stuck on this cell is waiting for you: look for the box. - Run the cells below it. They read the keys from
os.environas usual. If a request then fails as if the key were wrong, the box may have been left empty or the paste cut short: run this cell again, and it asks again.
Paste the key only into the box. The words between the quotation marks in getpass(...) are the question it asks, and they’re saved with the notebook like any other code; a key typed there is a key in the notebook. Treat this as a stopgap: the next time you start Jupyter, it asks again. Fix the cause when you have time.
The Census Bureau, FRED, and the EIA all take the key as a parameter in the URL, so the address requests sends, response.url, contains your key. Print a response’s JSON, never its URL, and never paste a URL from an error message into a forum or a pull request without deleting the key first. For the same reason, this chapter’s code doesn’t stop a failed request with response.raise_for_status(), the usual way: its message, 400 Client Error: Bad Request for url: …, holds the whole URL, key and all, and a notebook you submit keeps the message in its output. Each request checks the status itself instead, and stops with the agency’s own reason, the first 200 characters of its answer. None of the three agencies repeats the key in that answer (checked in November 2026):
11.2.5 Alternative: A JSON Configuration File
Some projects keep keys in a local configuration file instead of environment variables. Create a file called api_keys.json containing {"census": "your-key", "fred": "your-key", "eia": "your-key"}, add it to your .gitignore before your first commit, and load it into the same variable names:
Because both approaches end with the same three variables, every downstream code block in this chapter works unchanged either way.
For a comprehensive guide to API keys, environment variables, .env files, and secrets management, see the Missing Manual’s Chapter 34: Environment Variables and Secrets.
11.3 A Tour: From an Agency’s Website to Its API
Every number this chapter’s code retrieves is also on a web page, built for people to read. Start there. The page tells you what the agency calls the thing you want, which table or series it belongs to, and what place or period it covers, and those are the words the API wants. Two of the three sites go further, and show you the request itself.
11.3.1 A Census Table
data.census.gov is the U.S. Census Bureau’s site for browsing its tables; the same tables come from its API, documented at census.gov/data/developers. Figure 11.1 is table B19013, median household income, for Boulder County. The table’s ID ① is the start of every variable in it: the estimate is B19013_001E. The product ② is the survey and its years, the American Community Survey (ACS) 5-year estimates for 2020–2024, which is 2024/acs/acs5 in the API’s address. The column ③ is the geography, and the page’s own address names it with the code 050XX00US08013, whose last five digits are the county’s FIPS code (Federal Information Processing Standards code), 08013: state 08, county 013. The estimate ④ comes with a margin of error, and the API button ⑤ opens the request that returns the table.
11.3.2 A FRED Series
Every series in FRED (Federal Reserve Economic Data) has a page (Figure 11.2), and the same series comes from FRED’s API, documented at fred.stlouisfed.org/docs/api/fred. Its ID ① is what the API asks for: MHICO08013A052NCEN, which embeds Colorado’s postal code and Boulder County’s FIPS code (Federal Information Processing Standards code), 08013. The line under Observations ② gives the latest value, then the units and the frequency, which are what the API returns unless you ask for something else. Edit Graph ③ opens the site’s controls for changing both, to percent change or to a lower frequency, and those controls are the API’s units and frequency parameters.
11.3.3 The EIA’s API Dashboard
The U.S. Energy Information Administration (EIA) builds its requests in the open. Its API is documented at eia.gov/opendata/documentation.php, and its API Dashboard is a form: choose a route, a frequency, the data you want, and filters, and the page writes out the request it will send (Figure 11.3). Here the data type ① is the average price of electricity, and the filters ② keep one state of 62 and one sector of 6. Under them, the API URL ③ is the request, with each choice as a parameter: data[0]=price, facets[stateid][]=CO, facets[sectorid][]=RES. Add your key, and it returns the table under the form.
11.3.4 From the Website to the API
Each page in the tour is built for people to read, and each has a request behind it that returns the same thing to a program. The table pairs them, one API to a row:
| API | The page | What it shows | The request that returns it |
|---|---|---|---|
| Census Bureau | a table on data.census.gov (Figure 11.1) | Boulder County’s median household income | api.census.gov/data/2024/acs/acs5?get=B19013_001E&for=county:013&in=state:08 |
| FRED | a series’ page (Figure 11.2) | Boulder County’s median household income, year by year | api.stlouisfed.org/fred/series/observations?series_id=MHICO08013A052NCEN |
| EIA | the API Dashboard (Figure 11.3) | the price of electricity in Colorado’s homes | api.eia.gov/v2/electricity/retail-sales/data/?data[]=price&facets[stateid][]=CO&facets[sectorid][]=RES |
Every request also needs your key, which the table leaves out. The words in each request are the page’s words: a table’s ID, a series’ ID, a state’s code. That is why the tour comes first. The rest of the chapter takes the three APIs in the table’s order, starting with the question every API raises before any data arrives: what can I ask for?
11.4 U.S. Census Bureau API
The U.S. Census Bureau provides access to an enormous range of demographic, economic, and housing data. Its home page is census.gov, and its API is documented at census.gov/data/developers, with a user guide and a page for each dataset. The American Community Survey (ACS), the Bureau’s yearly survey of a sample of households, alone holds about 1,200 tables. The challenge is not access but navigation: knowing what you can ask for. This section answers that question the way you would by hand, starting from the table on the website in Figure 11.1 and ending with the same numbers from the API.
11.4.1 From the Website’s Table to the API’s Group
Each Census dataset has an address. This chapter uses the ACS 5-year estimates for 2020–2024, documented at census.gov/data/developers/data-sets/acs-5year.html, whose address in the API is https://api.census.gov/data/2024/acs/acs5. That is the product ② in Figure 11.1.
The website calls B19013 a table; the API calls it a group. Every group the dataset holds is listed, with its title, at groups.json, and as a web page at api.census.gov/data/2024/acs/acs5/groups.html, where your browser’s Find works as well as code does. Search the titles for the words on the website’s table:
import pandas as pd
census_base = "https://api.census.gov/data/2024/acs/acs5" # ACS 5-year estimates, 2020-2024
# Every group (table) in the dataset, with its title
response = requests.get(f"{census_base}/groups.json", headers=HEADERS, timeout=60)
if response.status_code != 200:
raise RuntimeError(f"Got {response.status_code}, not 200: {response.text[:200]}")
groups = response.json()["groups"]
print(f"{len(groups):,} groups")
# Search the titles for the words on the website's table
for group in sorted(groups, key=lambda g: g["name"]):
if "median household income" in group["description"].lower():
print(group["name"], "|", group["description"])
# 1,199 groups
# B19013 | Median Household Income in the Past 12 Months (in 2024 Inflation-Adjusted Dollars)
# B19013A | Median Household Income in the Past 12 Months (in 2024 Inflation-Adjusted Dollars) (White Alone Householder)
# B19013B | Median Household Income in the Past 12 Months (in 2024 Inflation-Adjusted Dollars) (Black or African American Alone Householder)
# B19013C | Median Household Income in the Past 12 Months (in 2024 Inflation-Adjusted Dollars) (American Indian and Alaska Native Alone Householder)
# B19013D | Median Household Income in the Past 12 Months (in 2024 Inflation-Adjusted Dollars) (Asian Alone Householder)
# B19013E | Median Household Income in the Past 12 Months (in 2024 Inflation-Adjusted Dollars) (Native Hawaiian and Other Pacific Islander Alone Householder)
# B19013F | Median Household Income in the Past 12 Months (in 2024 Inflation-Adjusted Dollars) (Some Other Race Alone Householder)
# B19013G | Median Household Income in the Past 12 Months (in 2024 Inflation-Adjusted Dollars) (Two or More Races Householder)
# B19013H | Median Household Income in the Past 12 Months (in 2024 Inflation-Adjusted Dollars) (White Alone, Not Hispanic or Latino Householder)
# B19013I | Median Household Income in the Past 12 Months (in 2024 Inflation-Adjusted Dollars) (Hispanic or Latino Householder)
# B19019 | Median Household Income in the Past 12 Months (in 2024 Inflation-Adjusted Dollars) by Household Size
# B19049 | Median Household Income in the Past 12 Months (in 2024 Inflation-Adjusted Dollars) by Age of Householder
# B22008 | Median Household Income in the Past 12 Months (in 2024 Inflation-Adjusted Dollars) by Receipt of Food Stamps/SNAP in the Past 12 Months
# B25099 | Mortgage Status by Median Household Income in the Past 12 Months (in 2024 Inflation-Adjusted Dollars)
# B25119 | Median Household Income in the Past 12 Months (in 2024 Inflation-Adjusted Dollars) by Tenure
# B29004 | Median Household Income for Households With a Citizen, Voting-Age Householder (in 2024 Inflation-Adjusted Dollars)B19013 is the group for all households, the table in Figure 11.1. The groups after it with a letter, B19013A to B19013I, are the same measure for households of one race or ethnicity, and the rest break it down by household size, the householder’s age, receipt of SNAP benefits, mortgage status, whether the household owns or rents, and citizenship. Had you started from a topic instead of a table, the same search, with your own words, is how you would find one.
11.4.2 From the Group to Its Variables
A group’s own address, groups/B19013.json, lists its variables: every column the table has, each with a label. Its web page is groups/B19013.html:
response = requests.get(f"{census_base}/groups/B19013.json", headers=HEADERS, timeout=30)
if response.status_code != 200:
raise RuntimeError(f"Got {response.status_code}, not 200: {response.text[:200]}")
group_vars = response.json()["variables"]
for var_id, info in sorted(group_vars.items()):
print(f"{var_id:13} {info['label']}")
# B19013_001E Estimate!!Median household income in the past 12 months (in 2024 inflation-adjusted dollars)
# B19013_001EA Annotation of Estimate!!Median household income in the past 12 months (in 2024 inflation-adjusted dollars)
# B19013_001M Margin of Error!!Median household income in the past 12 months (in 2024 inflation-adjusted dollars)
# B19013_001MA Annotation of Margin of Error!!Median household income in the past 12 months (in 2024 inflation-adjusted dollars)
# GEO_ID Geography
# NAME Geographic Area NameEach variable’s name follows a pattern. B19013 is the group, _001 the line in the table, and the last letter what the line holds: E the estimate, M its margin of error, and EA and MA their annotations, which say why an estimate or a margin is missing; when one is, the estimate itself holds a code, as “Every Place in a State”, below, shows. The !! in a label separates its levels, the way the website’s table indents its rows. NAME and GEO_ID describe the place. B19013 has one line, so it has one estimate; a bigger group, such as B25034, Year Structure Built, has one estimate for each of its eleven lines, which “Comparing Places” uses.
The ACS is a survey of a sample, so every estimate comes with a margin of error, and a difference between two places smaller than their margins may be no difference at all. Ask for M whenever you ask for E.
11.4.3 The Same Numbers from the API
With a group and its variables, a request to the API is a few parameters, which its user guide lists: get names the variables, for the place, in what that place sits inside, and key your key. Here is the figure from Figure 11.1, with its margin of error:
params = {
"get": "NAME,B19013_001E,B19013_001M", # the place's name, the estimate, and its margin of error
"for": "county:013", # Boulder County...
"in": "state:08", # ...in Colorado
"key": census_key,
}
response = requests.get(census_base, params=params, headers=HEADERS, timeout=30)
if response.status_code != 200:
raise RuntimeError(f"Got {response.status_code}, not 200: {response.text[:200]}")
rows = response.json()
print(rows)
# [['NAME', 'B19013_001E', 'B19013_001M', 'state', 'county'], ['Boulder County, Colorado', '103994', '2268', '08', '013']]The estimate matches the website’s ④, $103,994, and the margin of error is its “±2,268”. The response is a list of lists: the first row is the column names, and each row after it is one place. Every value is a string, the numbers included, and the place’s codes come back as columns of their own.
11.4.4 The Same Variable for a State, a County, and a City
Places are named by FIPS codes (Federal Information Processing Standards codes), numbers the federal government assigns: Colorado is state 08; Boulder County is county 013 in Colorado; the city of Boulder is place 07850 in Colorado. You already have one of them. The website’s address in Figure 11.1 ends g=050XX00US08013: 050 means a county, and 08013 is the state’s code followed by the county’s. Change only for and in, and the same request asks about a different kind of place:
# The same two variables for three places, each named by its FIPS codes
places_to_ask = [
{"for": "state:08"}, # Colorado
{"for": "county:013", "in": "state:08"}, # Boulder County, in Colorado
{"for": "place:07850", "in": "state:08"}, # the city of Boulder, in Colorado
]
for geography in places_to_ask:
params = {"get": "NAME,B19013_001E,B19013_001M", "key": census_key, **geography}
response = requests.get(census_base, params=params, headers=HEADERS, timeout=30)
if response.status_code != 200:
raise RuntimeError(f"Got {response.status_code}, not 200: {response.text[:200]}")
name, estimate, margin = response.json()[1][:3]
print(f"{name:26} {int(estimate):>8,} ± {int(margin):,}")
# Colorado 95,470 ± 578
# Boulder County, Colorado 103,994 ± 2,268
# Boulder city, Colorado 87,493 ± 6,221A state needs only for; a county or a city also needs in, the state it sits in, because county and place codes are numbered within each state: county 013 is a different county in every state that has one. FIPS codes are strings: 08 without its zero is a different code. To ask about another kind of place, such as a census tract or a ZIP code area, two pages of the dataset’s documentation show the way. geography.html lists each kind of place and what it has to sit inside; examples.html gives a working request for each, ready to copy. The Census Bureau lists the codes themselves at census.gov/library/reference/code-lists.
The city’s median household income, $87,493, is lower than both the county’s and the state’s. Its margin of error, ±6,221, is almost three times the county’s and more than ten times the state’s: the smaller the place, the fewer of its households are in the survey’s sample. Before you say that two places differ, compare the difference with their margins.
11.4.5 Comparing Places
Ask the Census Bureau’s API for several places at once by listing their FIPS codes (Federal Information Processing Standards codes), as its user guide shows. This request gets the age of the housing stock from the American Community Survey (ACS), group B25034, Year Structure Built, for the cities of Boulder and Longmont, and labels each column with the words from the group’s variables:
# Lines 002 to 011: built 2020 or later, 2010 to 2019, ..., 1939 or earlier
housing_vars = [f"B25034_{line:03d}E" for line in range(2, 12)]
params = {
"get": "NAME," + ",".join(housing_vars),
"for": "place:07850,45970", # Boulder and Longmont
"in": "state:08",
"key": census_key,
}
response = requests.get(census_base, params=params, headers=HEADERS, timeout=30)
if response.status_code != 200:
raise RuntimeError(f"Got {response.status_code}, not 200: {response.text[:200]}")
rows = response.json()
# First row is column names, the rest are data; every value arrives as a string
df = pd.DataFrame(rows[1:], columns=rows[0])
df[housing_vars] = df[housing_vars].apply(pd.to_numeric)
# The group's labels; the last part of each is the decade, such as "Built 2010 to 2019"
response = requests.get(f"{census_base}/groups/B25034.json", headers=HEADERS, timeout=30)
if response.status_code != 200:
raise RuntimeError(f"Got {response.status_code}, not 200: {response.text[:200]}")
b25034 = response.json()["variables"]
labels = {var: b25034[var]["label"].split("!!")[-1] for var in housing_vars}
housing = df.set_index("NAME")[housing_vars].rename(columns=labels).T
print(housing)
# NAME Boulder city, Colorado Longmont city, Colorado
# Built 2020 or later 646 761
# Built 2010 to 2019 3836 6631
# Built 2000 to 2009 3968 7597
# Built 1990 to 1999 5561 7781
# Built 1980 to 1989 7141 4616
# Built 1970 to 1979 9739 8402
# Built 1960 to 1969 7904 3099
# Built 1950 to 1959 4453 1899
# Built 1940 to 1949 641 671
# Built 1939 or earlier 3576 2071The table holds the answer, but it takes reading: ten rows of two numbers each, newest first. A chart shows its shape at a glance. Draw one pair of bars for each decade, one bar per city, so that the two cities sit side by side wherever they differ. The labels came from the group’s variables, so the chart can use them as they are. Turn the table upside down first, so that time runs left to right, from the oldest decade to the newest:
import matplotlib.pyplot as plt
# Oldest decade at the left, newest at the right
ax = housing.iloc[::-1].plot(kind="bar", figsize=(8, 4.5))
ax.set_title("Housing units by year built: Boulder and Longmont, ACS 2020-2024")
ax.set_ylabel("Housing units")
ax.set_xlabel("")
ax.legend(title="")
plt.xticks(rotation=45, ha="right")
plt.tight_layout()
plt.show()Boulder’s housing is older than Longmont’s (Figure 11.4). Its biggest decade was the 1970s, with 9,739 of the units standing today, and each decade since has added fewer. Longmont has more units than Boulder from every decade since the 1990s. Boulder’s limits on growth, beginning with the Danish Plan’s cap on residential building permits in 1976, are one likely reason, though these numbers alone can’t show it. Read the table for what it is, too: it counts the units standing in 2020–2024 by the year they were built, so a decade’s count leaves out whatever has since been torn down.
11.4.6 Every Place in a State, and a Number That Isn’t
A wildcard asks the Census Bureau’s API for every place of a kind, as its user guide describes: for=place:* with in=state:08 returns all of Colorado’s cities, towns, and census-designated places. The variable is again the American Community Survey’s (ACS) median household income. Here is median household income for each of them:
params = {"get": "NAME,B19013_001E", "for": "place:*", "in": "state:08", "key": census_key}
response = requests.get(census_base, params=params, headers=HEADERS, timeout=30)
if response.status_code != 200:
raise RuntimeError(f"Got {response.status_code}, not 200: {response.text[:200]}")
rows = response.json()
places = pd.DataFrame(rows[1:], columns=rows[0])
places["income"] = pd.to_numeric(places["B19013_001E"])
print(f"{len(places)} places")
print(places["income"].describe().round())
# 482 places
# count 482.0
# mean -114723934.0
# std 251998296.0
# min -666666666.0
# 25% 43678.0
# 50% 72168.0
# 75% 106214.0
# max 250001.0
# Name: income, dtype: float64A median household income of minus 666 million dollars is not a number: it is a sentinel, a code that stands for “no estimate”. The Census Bureau’s notes on ACS estimate values list several, and -666666666 means that the estimate could not be computed, because the survey had too few sample observations there. In a small town, that is common. Left in, the sentinels drag every average far below zero. Replace them with a missing value before you compute anything:
no_estimate = places["income"] == -666666666
print(f"{no_estimate.sum()} of {len(places)} places have no estimate")
places.loc[no_estimate, "income"] = float("nan") # pandas skips NaN in medians and means
print(f"Median of the rest: ${places['income'].median():,.0f}")
# 83 of 482 places have no estimate
# Median of the rest: $81,250Eighty-three of Colorado’s 482 places have no estimate in the 2020–2024 survey; in the 2018–2022 survey, 72 did. The count changes with every release, so count the sentinels in the data you have rather than assuming a number. Left in, they put the mean income of Colorado’s places at minus $114,723,934. The top of the range is coded too: 250,001 means “$250,000 or more”, the highest value the ACS reports for a median. Look at describe()’s minimum and maximum before you trust any Census column.
11.5 FRED API
The Federal Reserve Bank of St. Louis maintains FRED (Federal Reserve Economic Data), one of the world’s largest free collections of economic time series, with an API documented at fred.stlouisfed.org/docs/api/fred: more than 800,000 of them, covering macroeconomics, banking, labor markets, prices, and more. A series in FRED is a list of dates and values, and FRED will transform that list for you before it sends it: into percent changes, into annual averages, into logarithms. Asking the server to do that work is this section’s idea. It saves code, and it gives everyone who asks the same way the same answer.
11.5.1 Finding Series IDs
FRED (Federal Reserve Economic Data) organizes data by “series”, each with a unique ID. The easiest way to find one is to search the FRED website and read the ID off the series’ page, as in Figure 11.2. The API’s series endpoint then describes a series before you download it:
fred_base = "https://api.stlouisfed.org/fred"
def fred_get(endpoint, **params):
"""Call one FRED endpoint, such as "series", with its own parameters, and return the JSON."""
params.update(api_key=fred_key, file_type="json")
response = requests.get(f"{fred_base}/{endpoint}", params=params, headers=HEADERS, timeout=30)
if response.status_code != 200:
raise RuntimeError(f"Got {response.status_code}, not 200: {response.text[:200]}")
return response.json()
info = fred_get("series", series_id="MHICO08013A052NCEN")["seriess"][0]
for field in ["title", "frequency", "units", "seasonal_adjustment", "observation_start", "observation_end"]:
print(f"{field}: {info[field]}")
# title: Estimate of Median Household Income for Boulder County, CO
# frequency: Annual
# units: Dollars
# seasonal_adjustment: Not Seasonally Adjusted
# observation_start: 1989-01-01
# observation_end: 2024-01-01The series is an annual estimate from the Census Bureau’s Small Area Income and Poverty Estimates (SAIPE) program, from 1989 to 2024. Its observations come from the series/observations endpoint. This function asks for them and returns them as a DataFrame with real dates and numbers; FRED writes a missing value as ".", which errors="coerce" turns into NaN:
def fred_observations(series_id, **params):
"""Return a FRED series' observations as a DataFrame of dates and values."""
params.update(series_id=series_id, api_key=fred_key, file_type="json")
response = requests.get(f"{fred_base}/series/observations", params=params, headers=HEADERS, timeout=30)
if response.status_code != 200:
raise RuntimeError(f"Got {response.status_code}, not 200: {response.text[:200]}")
df = pd.DataFrame(response.json()["observations"])[["date", "value"]]
df["date"] = pd.to_datetime(df["date"])
df["value"] = pd.to_numeric(df["value"], errors="coerce")
return df
# A fixed end date, so the answer doesn't change when FRED adds next year's estimate
income = fred_observations("MHICO08013A052NCEN", observation_end="2024-12-31")
print(len(income), "years")
print(income.tail(3).to_string(index=False))
# 36 years
# date value
# 2022-01-01 96584.0
# 2023-01-01 97170.0
# 2024-01-01 103293.0FRED’s 2024 figure for Boulder County, $103,293, isn’t the Census API’s $103,994. Both come from the Census Bureau, but from different programs: SAIPE models a single year’s income from the ACS together with tax and benefit records, while the American Community Survey (ACS) 5-year estimate pools five years of survey responses. Name the program and the years whenever you cite one of them.
11.5.2 Let the Server Compute: units
The units parameter of the series/observations endpoint asks FRED (Federal Reserve Economic Data) to transform a series’ values before it sends them. Ask for the same series, Boulder County’s median household income, twice more: with units="chg", the change in dollars from the previous observation, and with units="pch", the percent change. One series, three answers:
change = fred_observations("MHICO08013A052NCEN", units="chg", observation_end="2024-12-31")
growth = fred_observations("MHICO08013A052NCEN", units="pch", observation_end="2024-12-31")
views = pd.DataFrame({"date": income["date"], "dollars": income["value"],
"change": change["value"], "percent change": growth["value"]})
print(views.tail(3).to_string(index=False, float_format="%.1f"))
# date dollars change percent change
# 2022-01-01 96584.0 6257.0 6.9
# 2023-01-01 97170.0 586.0 0.6
# 2024-01-01 103293.0 6123.0 6.3The values FRED can compute for any series:
units= |
Returns |
|---|---|
lin |
the values as published (the default) |
chg |
change from the previous observation |
ch1 |
change from a year before |
pch |
percent change from the previous observation |
pc1 |
percent change from a year before |
pca |
compounded annual rate of change |
log |
natural logarithm |
11.5.3 Let the Server Compute: frequency and aggregation_method
A series’ frequency is how often it is measured. FRED (Federal Reserve Economic Data) can lower it before it sends the data, from monthly to quarterly or annual, and the series/observations endpoint documents how. Take one series through three requests: the Consumer Price Index (CPI) for all urban consumers in the United States, which the Bureau of Labor Statistics (BLS) publishes every month and FRED carries as CPIAUCNS. Ask FRED what it is first:
info = fred_get("series", series_id="CPIAUCNS")["seriess"][0]
for field in ["title", "frequency", "units", "seasonal_adjustment"]:
print(f"{field}: {info[field]}")
# title: Consumer Price Index for All Urban Consumers: All Items in U.S. City Average
# frequency: Monthly
# units: Index 1982-1984=100
# seasonal_adjustment: Not Seasonally AdjustedIt is a monthly index. Ask for it three ways, changing one parameter at a time:
- as published, one value a month;
- with
frequency="a"andaggregation_method="avg", which turns the months FRED has for each year into their mean (sumandeop, the end of the period, are the other methods); - with
units="pc1"added, the percent change of each year’s mean from the year before’s, which is the year’s inflation. FRED applies the frequency first, then the units.
years = {"observation_start": "2015-01-01", "observation_end": "2025-12-31"} # fixed, so the answer doesn't change
monthly = fred_observations("CPIAUCNS", **years)
annual = fred_observations("CPIAUCNS", frequency="a", aggregation_method="avg", **years)
inflation = fred_observations("CPIAUCNS", frequency="a", aggregation_method="avg", units="pc1", **years)
print(len(monthly), "months, and", len(annual), "years")
table = pd.DataFrame({"year": annual["date"].dt.year, "mean index": annual["value"],
"inflation (%)": inflation["value"]})
print(table.to_string(index=False, float_format="%.1f"))
# 132 months, and 11 years
# year mean index inflation (%)
# 2015 237.0 0.1
# 2016 240.0 1.3
# 2017 245.1 2.1
# 2018 251.1 2.4
# 2019 255.7 1.8
# 2020 258.8 1.2
# 2021 271.0 4.7
# 2022 292.7 8.0
# 2023 304.7 4.1
# 2024 313.7 2.9
# 2025 321.9 2.6Trust, but check once. Compute the same yearly means and percent changes in pandas, from the monthly values of the first request, and they should match FRED’s:
They match. So frequency="a" with aggregation_method="avg" is the mean of the months FRED has for each year, and units="pc1" on top of it is the percent change in that mean, and you can describe the numbers that way when you write them up. For 2025, that is eleven months, not twelve. The Bureau of Labor Statistics collected no prices during the lapse in federal appropriations from October 1 to November 12, 2025, and published no October index for most of its series (BLS, 2025). So monthly holds NaN for October 2025, monthly["value"].isna() finds it, and both means, FRED’s and pandas’, leave it out. A 2025 figure from this series needs that footnote, and so does any year you average: count the months before you trust the mean. The index itself, 321.9 in 2025, means that prices were 3.2 times what they were in 1982–1984, the period the index sets at 100. (Ask pandas for 2015’s percent change, and it has none: the monthly request starts in January 2015. FRED reaches back to 2014’s months itself.)
With one series understood, comparing two is a matter of asking each the same question. The BLS also publishes a CPI for the Denver area, which FRED carries as CUUSA433SA0. It is annual already, so it needs only units="pc1" to give the same year-over-year inflation:
denver = fred_observations("CUUSA433SA0", units="pc1", **years)
cpi = denver.merge(inflation, on="date", suffixes=("_denver", "_national"))
cpi["year"] = cpi["date"].dt.year
print(cpi[["year", "value_denver", "value_national"]].to_string(index=False, float_format="%.1f"))
# year value_denver value_national
# 2015 1.2 0.1
# 2016 2.8 1.3
# 2017 3.4 2.1
# 2018 2.7 2.4
# 2019 1.9 1.8
# 2020 2.0 1.2
# 2021 3.5 4.7
# 2022 8.0 8.0
# 2023 5.2 4.1
# 2024 2.3 2.9
# 2025 2.3 2.6Eleven years of two numbers each are easier to compare as pairs of bars, one pair a year, with a line across them at 2 percent, the Federal Reserve’s target for inflation:
pairs = cpi.set_index("year")[["value_denver", "value_national"]]
pairs.columns = ["Denver-Aurora-Lakewood", "United States"]
ax = pairs.plot.bar(figsize=(8, 4), rot=0, width=0.8)
ax.axhline(y=2, color="gray", linestyle="--", linewidth=1, label="2% target")
ax.set_title("Annual inflation (CPI-U, percent change from the year before)")
ax.set_ylabel("Percent")
ax.set_xlabel("")
ax.legend()
plt.tight_layout()
plt.show()Prices in the Denver area rose faster than the nation’s from 2015 to 2020 (Figure 11.5): 3.4 percent in 2017 against 2.1. Both reached 8.0 percent in 2022, and since 2024 Denver’s inflation has run below the nation’s, 2.3 percent in 2025 against 2.6. Housing is the largest part of the CPI, so a natural next question is whether rent explains the gap; FRED’s Denver series for rent of primary residence, CUUSA433SEHA, is a place to start, and the same parameters work on it unchanged.
11.6 EIA API v2
The U.S. Energy Information Administration’s (EIA) API, version 2, documented at eia.gov/opendata/documentation.php, holds a great deal: every state’s electricity prices and sales, every power plant’s monthly generation, coal, oil, gas, and the agency’s forecasts. You will never want all of it. Its design assumes that, and lets you name exactly the slice you want before the server sends anything: one state, one sector, one column, one span of years, in the order you choose. Narrowing a request on the server, instead of downloading everything and filtering in pandas, is this section’s idea.
11.6.1 Routes That Describe Themselves
The EIA’s (U.S. Energy Information Administration’s) API is a tree of routes, paths such as electricity/retail-sales/, which its documentation describes. Ask for a route without asking for its data, and it describes itself. At the top, it lists the routes under it:
eia_base = "https://api.eia.gov/v2"
def eia_get(route, params=None):
"""GET one EIA route, such as "electricity/", and return the "response" part of its JSON."""
params = dict(params or {}, api_key=eia_key)
response = requests.get(f"{eia_base}/{route}", params=params, headers=HEADERS, timeout=60)
if response.status_code != 200:
raise RuntimeError(f"Got {response.status_code}, not 200: {response.text[:200]}")
return response.json()["response"]
electricity = eia_get("electricity/")
for child in electricity["routes"]:
print(f"{child['id']:32} {child['name']}")
# retail-sales Electricity Sales to Ultimate Customers
# electric-power-operational-data Electric Power Operations (Annual and Monthly)
# rto Electric Power Operations (Daily and Hourly)
# state-electricity-profiles State Specific Data
# operating-generator-capacity Inventory of Operable Generators
# facility-fuel Electric Power Operations for Individual Power Plants (Annual and Monthly)A route with data under it describes that data instead: how often it is measured, the facets it can be filtered by, the data columns it holds, with their units, and the span it covers:
meta = eia_get("electricity/retail-sales/")
print("Frequencies:", [f["id"] for f in meta["frequency"]])
print("Facets:", [f["id"] for f in meta["facets"]])
for column, about in meta["data"].items():
print(f" {column:10} {about['units']}")
print("From", meta["startPeriod"], "to", meta["endPeriod"])
# Frequencies: ['monthly', 'quarterly', 'annual']
# Facets: ['stateid', 'sectorid']
# revenue million dollars
# sales million kilowatt hours
# price cents per kilowatt-hour
# customers number of customers
# From 2001-01 to 2026-08Each facet lists its own values, at facet/ and the facet’s name:
These are the same lists the API Dashboard’s menus show in Figure 11.3: the dashboard reads them from these routes.
11.6.2 Let the Server Filter
Add data/ to an EIA (U.S. Energy Information Administration) route, and it returns rows; the API’s documentation lists the parameters. Each parameter narrows them: data[] names the columns, facets[stateid][] and facets[sectorid][] keep only the values you list, start and end fix the span, and sort orders the rows. The square brackets are part of the parameters’ names, and requests encodes them for you:
params = {
"frequency": "annual",
"data[]": "price", # one column: the average price
"facets[stateid][]": "CO", # only Colorado...
"facets[sectorid][]": "RES", # ...and only homes
"start": "2001",
"end": "2025", # fixed years, so the answer doesn't change next year
"sort[0][column]": "period",
"sort[0][direction]": "asc",
}
prices = eia_get("electricity/retail-sales/data/", params)
print("Rows:", prices["total"])
co_price = pd.DataFrame(prices["data"])
print(co_price[["period", "stateid", "sectorName", "price", "price-units"]].tail(3).to_string(index=False))
# Rows: 25
# period stateid sectorName price price-units
# 2023 CO residential 14.3 cents per kilowatt-hour
# 2024 CO residential 14.92 cents per kilowatt-hour
# 2025 CO residential 15.69 cents per kilowatt-hourColorado’s households paid 15.69 cents a kilowatt-hour on average in 2025. The request returned 25 rows, one a year, from a route that holds every state and sector by month, quarter, and year, and nothing else crossed the network. The prices arrive as strings, as the Census Bureau’s numbers do, so convert them with pd.to_numeric() before computing with them; total is a string too.
A facet can take several values: give requests a list, and it repeats the parameter once for each. This request asks the route for power plants’ operations for Colorado’s generation from five sources, plus all sources together:
params = {
"frequency": "annual",
"data[]": "generation",
"facets[location][]": "CO",
"facets[sectorid][]": "99", # all sectors
"facets[fueltypeid][]": ["ALL", "COW", "NG", "WND", "SUN", "HYC"], # all, coal, gas, wind, solar, hydro
"start": "2001",
"end": "2025",
}
gen = pd.DataFrame(eia_get("electricity/electric-power-operational-data/data/", params)["data"])
gen["generation"] = pd.to_numeric(gen["generation"])
# One row per year, one column per source, each source as a share of all generation
mix = gen.pivot(index="period", columns="fueltypeid", values="generation")
mix = mix.rename(columns={"COW": "coal", "NG": "gas", "WND": "wind", "SUN": "solar", "HYC": "hydro"})
shares = mix[["coal", "gas", "wind", "solar", "hydro"]].div(mix["ALL"], axis=0) * 100
print(shares.loc[["2001", "2015", "2025"]].round(1))
# fueltypeid coal gas wind solar hydro
# period
# 2001 76.7 20.0 0.1 NaN 3.2
# 2015 60.2 22.2 14.3 0.5 3.1
# 2025 24.7 32.0 30.0 9.9 3.0Three years in a table hide the path between them. The shares DataFrame already holds every year from 2001 to 2025, one column per source, which is the shape a line chart wants: one line per column, with the years along the bottom. The data are annual, so give the axis a tick for every year, in small type so that 25 labels fit:
shares.index = shares.index.astype(int) # the years arrive as strings
ax = shares.plot(figsize=(8, 4.5), marker=".", xticks=shares.index)
ax.tick_params(axis="x", labelsize=7, labelrotation=90)
ax.set_title("Colorado's electricity generation by source, 2001-2025")
ax.set_ylabel("Share of all generation (%)")
ax.set_xlabel("")
ax.legend(title="")
plt.tight_layout()
plt.show()Coal made 76.7 percent of Colorado’s electricity in 2001 and 24.7 percent in 2025 (Figure 11.6). Wind grew from almost nothing to 30.0 percent, and 2024 was the first year in which coal wasn’t the state’s largest source: gas made 30.5 percent, wind 29.9, and coal 28.0. SUN counts power plants only, and its line starts in 2007, the first year with any; rooftop panels are in a separate estimate, TSN, estimated total solar, which puts solar at 13.9 percent of 2025’s generation.
11.6.3 Paging with offset and length
The EIA’s (U.S. Energy Information Administration’s) API returns at most 5,000 rows a request, as its documentation says. Ask for more, and you get the first 5,000 and a warning, "incomplete return". Colorado’s monthly generation from every source, 2001 to 2025, is 9,289 rows. The response says how many rows match in total, and you ask for the next page with offset, the number of rows to skip, and length, the number to return:
def eia_get_all(route, params, page_size=5000):
"""Page through every row of an EIA data route, page_size rows at a time."""
rows = []
while True:
page_params = dict(params, api_key=eia_key, offset=len(rows), length=page_size)
response = requests.get(f"{eia_base}/{route}", params=page_params, headers=HEADERS, timeout=60)
if response.status_code != 200:
raise RuntimeError(f"Got {response.status_code}, not 200: {response.text[:200]}")
page = response.json()["response"]
print(f"offset {len(rows):>5}: {len(page['data'])} rows of {page['total']}")
rows.extend(page["data"])
if len(rows) >= int(page["total"]) or not page["data"]:
break
return pd.DataFrame(rows)
params = {
"frequency": "monthly",
"data[]": "generation",
"facets[location][]": "CO",
"facets[sectorid][]": "99",
"start": "2001-01",
"end": "2025-12",
"sort[0][column]": "period", # a fixed order, so no row moves between pages
"sort[0][direction]": "asc",
"sort[1][column]": "fueltypeid",
"sort[1][direction]": "asc",
}
monthly_gen = eia_get_all("electricity/electric-power-operational-data/data/", params)
print(len(monthly_gen), "rows;", monthly_gen["fueltypeid"].nunique(), "energy sources")
# offset 0: 5000 rows of 9289
# offset 5000: 4289 rows of 9289
# 9289 rows; 36 energy sourcesCompare this loop with Chapter 10’s. Wikipedia’s API hands you a continue token, and you send it back without knowing what it means; the server keeps track of where you are. The EIA tells you the total, and you keep track: the next offset is the number of rows you already have. Three details follow from that:
- Stop on the count, not the warning. The
"incomplete return"warning comes with every page that isn’t the whole result, the last page included, so it can’t tell you when to stop.totalcan; it arrives as a string, henceint(). - Sort when you page. Without a fixed order, nothing promises that the rows come back in the same order on the second request as on the first, and a row could appear on both pages or on neither.
- Filter first. Paging is for results that are large after you have narrowed them. Before writing a loop, ask whether a facet, a shorter span, or a lower frequency would fit the request in one page.
11.7 Combining Census and EIA Data
Each API in this chapter answers a question on its own. Some questions need two. What does electricity cost a household, against what households earn? The EIA (U.S. Energy Information Administration) knows what homes paid for electricity in each state; the Census Bureau’s American Community Survey (ACS) knows the state’s median household income. Joining them is a matter of putting each state’s two numbers in one row, and the real work of a join is finding the identifier that says two rows are the same state.
Ask each agency for every state. The Census Bureau’s API takes for=state:*; the EIA’s retail-sales route returns every state when you leave out the stateid facet. Ask the EIA for three of its data columns at once, the homes’ revenue, customers, and price in 2024:
params = {"get": "NAME,B19013_001E", "for": "state:*", "key": census_key}
response = requests.get(census_base, params=params, headers=HEADERS, timeout=30)
if response.status_code != 200:
raise RuntimeError(f"Got {response.status_code}, not 200: {response.text[:200]}")
rows = response.json()
states = pd.DataFrame(rows[1:], columns=rows[0])
states["income"] = pd.to_numeric(states["B19013_001E"])
params = {
"frequency": "annual",
"data[]": ["revenue", "customers", "price"], # three columns in one request
"facets[sectorid][]": "RES", # homes only
"start": "2024",
"end": "2024",
}
power = pd.DataFrame(eia_get("electricity/retail-sales/data/", params)["data"])
print(len(states), "rows from the Census Bureau;", len(power), "from the EIA")
print(states[["NAME", "state"]].head(3).to_string(index=False))
print(power[["stateDescription", "stateid"]].head(3).to_string(index=False))
# 52 rows from the Census Bureau; 62 from the EIA
# NAME state
# Alabama 01
# Alaska 02
# Arizona 04
# stateDescription stateid
# Alaska AK
# Alabama AL
# Arkansas ARThe two agencies name Colorado differently. The Census Bureau uses its FIPS code (Federal Information Processing Standards code), 08; the EIA uses its postal abbreviation, CO. The state’s name is in both, but a name is a poor key: a spelling, an abbreviation, or a “The” can keep two names for one place from matching. A crosswalk is a table that pairs one set of codes with the other, and the Census Bureau publishes one for states, a text file whose columns are separated by |, listed on its page of FIPS codes under “States”:
import io
response = requests.get("https://www2.census.gov/geo/docs/reference/codes2020/national_state2020.txt", headers=HEADERS, timeout=30)
if response.status_code != 200:
raise RuntimeError(f"Got {response.status_code}, not 200: {response.text[:200]}")
codes = pd.read_csv(io.StringIO(response.text), sep="|", dtype=str) # dtype=str keeps "08" as "08"
print(codes.head(3).to_string(index=False))
# STATE STATEFP STATENS STATE_NAME
# AL 01 01779775 Alabama
# AK 02 01785533 Alaska
# AZ 04 01779777 ArizonaJoin in two steps: the Census rows to the crosswalk on the FIPS code, then the result to the EIA’s rows on the postal code. An outer join keeps every row from both sides, and pandas’ merge() with indicator=True adds a column, _merge, that says where each row came from. Look at the rows that didn’t match before you trust the ones that did:
# In the crosswalk, STATEFP is the FIPS code and STATE the postal code; the Census API's "state" column is a FIPS code
states = states.merge(codes[["STATEFP", "STATE"]], left_on="state", right_on="STATEFP", how="left")
joined = states.merge(power, left_on="STATE", right_on="stateid", how="outer", indicator=True)
print(joined["_merge"].value_counts().to_string())
print("Only in the Census Bureau's data:", sorted(joined.loc[joined["_merge"] == "left_only", "NAME"]))
print("Only in the EIA's data:", sorted(joined.loc[joined["_merge"] == "right_only", "stateDescription"]))
# _merge
# both 51
# right_only 11
# left_only 1
# Only in the Census Bureau's data: ['Puerto Rico']
# Only in the EIA's data: ['East North Central', 'East South Central', 'Middle Atlantic', 'Mountain', 'New England', 'Pacific Contiguous', 'Pacific Noncontiguous', 'South Atlantic', 'U.S. Total', 'West North Central', 'West South Central']Fifty-one rows matched: the fifty states and the District of Columbia. The one Census row without a partner is Puerto Rico, which the American Community Survey covers and the EIA’s retail-sales route doesn’t. The eleven EIA rows without a partner aren’t states at all. They are regions (the Census Bureau’s divisions, with the Pacific division split into its contiguous and noncontiguous states) and the U.S. total, which the EIA puts in the same column as the states, stateid. An inner join would have dropped all twelve without a word, and a sum of the EIA’s column would have counted every state three times: as itself, in its region, and in the total.
Keep the 51 rows that matched, and compute two things from them: a home’s average annual electricity bill, the residential revenue divided by the number of residential customers, and that bill as a share of the state’s median household income:
both = joined[joined["_merge"] == "both"].copy()
for column in ["revenue", "customers", "price"]:
both[column] = pd.to_numeric(both[column]) # the EIA's numbers arrive as strings
both["annual_bill"] = both["revenue"] * 1_000_000 / both["customers"] # revenue is in millions of dollars
both["share"] = both["annual_bill"] / both["income"] * 100
columns = ["NAME", "annual_bill", "income", "share"]
print(both.sort_values("share", ascending=False)[columns].head(5).round(1).to_string(index=False))
print(both.loc[both["STATE"] == "CO", columns].round(1).to_string(index=False))
# NAME annual_bill income share
# Mississippi 1857.9 56447.0 3.3
# Alabama 2082.0 63999.0 3.3
# West Virginia 1857.1 59608.0 3.1
# Louisiana 1691.5 60756.0 2.8
# South Carolina 1794.1 69324.0 2.6
# NAME annual_bill income share
# Colorado 1206.9 95470.0 1.3In Mississippi and Alabama, a home’s electricity bill averaged 3.3 percent of the median household’s income; in Colorado, 1.3 percent, $1,207 a year against $95,470. Two cautions come with the join. The years differ: the EIA’s figures are for 2024, while the ACS estimate pools 2020 to 2024 and states it in 2024 dollars. And the units differ: an EIA customer is not the same thing as an ACS household, so the share is an approximation, worth saying so whenever you report it. Matching identifiers is the first step of a join; matching what the numbers mean is the second. A scatter plot puts every state on one page:
ax = both.plot.scatter(x="income", y="annual_bill", figsize=(8, 4.5))
for _, row in both[both["STATE"].isin(["CO", "HI", "CA", "MS", "UT"])].iterrows():
ax.annotate(row["STATE"], (row["income"], row["annual_bill"]), xytext=(4, 4), textcoords="offset points")
ax.set_title("Homes' electricity bills against household income, by state")
ax.set_xlabel("Median household income, ACS 2020-2024 (dollars)")
ax.set_ylabel("Average annual electricity bill, 2024 (dollars)")
plt.tight_layout()
plt.show()Electricity bills don’t rise with income in any simple way (Figure 11.7). Hawaii’s homes paid the most, more than $2,500 a year, and Colorado’s and Utah’s, in high-income states, paid among the least. The burden falls hardest where incomes are lowest, which is why Mississippi, Alabama, and West Virginia top the list of shares. Each of those findings rests on the join: on a crosswalk from one agency’s codes to the other’s, and on knowing which rows of each table were never states.
11.8 More Government APIs for Colorado
The three APIs in this chapter are a small part of what governments publish. Each of these is free, documented, and has data about Colorado; most answer the same three questions you asked of this chapter’s: what can I ask for, how do I narrow it, and how do I page through it. Where an API wants a key, the list says so.
Federal
- Bureau of Labor Statistics (BLS) Public Data API. Employment, unemployment, wages, and prices as time series, including Colorado’s and each county’s unemployment rate from the Local Area Unemployment Statistics. Version 1.0 needs no registration; version 2.0 needs a free key and allows more series and requests.
- Bureau of Economic Analysis (BEA) API. GDP and personal income for the nation, the states, counties, and metropolitan areas, such as personal income per capita in Boulder County. Requires a free key.
- U.S. Geological Survey (USGS) Water Data APIs. Streamflow and water levels from monitoring stations, such as the gauges on Boulder Creek and the South Platte. Its site offers a free key.
- National Weather Service API. Forecasts, observations, and alerts for any point, such as
api.weather.gov/points/40.015,-105.2705for Boulder. No key: instead, it asks every request for a User-Agent with your contact information, as this book’sHEADERSdo. - EPA AirNow API. Current and forecast air quality from more than 2,500 monitoring stations, including Colorado’s. Requires a free account and key.
- USAspending API. Federal contracts, grants, and loans, by recipient, agency, and place, under the DATA Act, such as every federal award to recipients in Colorado. No key.
- OpenFEMA. The Federal Emergency Management Agency’s disaster declarations, assistance, and flood-insurance records, filtered with
$filter, as instate eq 'CO'. Boulder County’s records include the Marshall Fire of December 2021. No key. - Congress.gov API. The Library of Congress’s records of bills, members, committees, and votes, such as every bill Colorado’s delegation has sponsored. A bill’s record links to its actions, cosponsors, and text, each a request of its own, and lists page with a
nextlink. Requires a free api.data.gov key.
State
- Colorado Information Marketplace. The State of Colorado’s open-data portal: the Secretary of State’s records of business entities, and many other datasets. Each dataset has an endpoint in the Socrata Open Data API (SODA), queried with a SQL-like language, SoQL. No key, but a free application token raises the limit on how fast you can ask.
- Colorado Division of Water Resources’ CDSS REST API. The Colorado Decision Support System’s stream gauges, wells, diversions, and water rights. Answers anonymous and registered users; a free key raises the daily limits.
- Regional Transportation District (RTD) real-time feeds. Where the Denver area’s buses and trains are, and their delays and alerts, in GTFS Realtime, a binary format (protocol buffers) rather than JSON. Used under RTD’s license agreement.
Local
- City of Boulder Open Data. Construction permits, the police department’s crime blotter and stops, parcels, and Open Space trails. Each dataset has an ArcGIS REST endpoint, which pages with
resultOffsetand filters with awhereclause. - City and County of Denver Open Data Catalog. Crime, 311 service requests, permits, and parcels for Denver, on the same ArcGIS platform as Boulder’s.
Before you build on any of them, read its terms, its limits, and its robots.txt where it has one (Chapter 2), and note the date you used it: local portals rename and retire datasets more often than federal APIs do.
11.9 Recommended Exercises
This guided exercise is the chapter’s take-home assignment. Work through it in the companion notebook, filling in each empty code cell, and submit the completed notebook. The steps build on one another, so do them in order — everything you need appears in this chapter or an earlier one. You will need your Census and FRED keys from the start of this chapter.
You will answer one comparative question about Colorado with two federal data sources: how does a Census measure vary across the state’s counties, and what has a related economic indicator done over time?
Before you start. Run this cell first. It imports what the steps use and sets the two base addresses; it reads no keys, which is Step 1’s job. These exercises need only the Census and FRED keys, so if the chapter’s getpass() cell asks for EIA_KEY, press Enter. For Step 5, the chapter’s fred_observations() does the request: run its cell, in “Finding Series IDs”, or copy it into your notebook.
# Run this first: the imports and addresses every step below uses
import os
import requests
import pandas as pd
import matplotlib.pyplot as plt
# Every request says who is asking; put your own address here
HEADERS = {"User-Agent": "WebDataScience/1.0 (your-email@colorado.edu)"}
census_base = "https://api.census.gov/data/2024/acs/acs5" # ACS 5-year estimates, 2020-2024
fred_base = "https://api.stlouisfed.org/fred"Step 1 — Load your keys safely. Load your Census and FRED API keys from environment variables or your api_keys.json, exactly as the chapter shows. Confirm both loaded by printing, for each key, set or MISSING and its length, never the key itself, since the notebook is what you submit. A Census key has 40 characters and a FRED key 32; a key of another length was cut off, or picked up a space, when you pasted it.
Step 2 — Query every Colorado county. Choose one ACS variable you care about (browse the groups catalog to pick it; median household income is B19013_001E). A median or a share compares counties fairly; a count, such as the number of households with an internet subscription, mostly ranks counties by their size. Query the Census API with for=county:* and in=state:08 to get all Colorado counties in one call, and print how many rows came back: Colorado has 64 counties, and without in, the same request returns every county in the country.
Step 3 — Build and clean the DataFrame. First row is headers, the rest is data — the same shape you handled in Chapter 7. Convert your variable to numeric, sort by it, and print the top and bottom five counties.
Step 4 — Visualize the geography. Make a horizontal bar chart of the top 20 counties by your variable, labeled with county names.
Step 5 — Add the time dimension with FRED. Find one FRED series related to your Census variable for Colorado (unemployment rate, home price index, per-capita income — the chapter shows how to search for series IDs). Ask the series endpoint for its title, units, and frequency, as “Finding Series IDs” does. Retrieve it, build a DataFrame with real dates, and plot the series over the last two decades, with its units on the axis.
Step 6 — Interpret. In four to six sentences: What geographic pattern did the county ranking reveal, and does it match what you know about Colorado? How does the FRED trend contextualize the Census snapshot — is the cross-sectional picture stable or a moment in a moving series? What would you need to be careful about before combining these two sources in one analysis (different geographies, different definitions, different vintages)?
11.10 Additional Exercises
These are open-ended extensions — no scaffold, no fixed path. Use them for further practice or deeper exploration.
Census exploration. Using the Census API, retrieve a variable group of your choice (browse at
api.census.gov/data/2024/acs/acs5/groups.html) for at least five geographic areas. Create a comparative visualization and write a brief analytical narrative explaining what the data reveals.FRED time series. Retrieve two related economic time series for your local area or state using the FRED API. Plot them on the same or side-by-side axes. What story does the data tell? Common pairings include housing prices and mortgage rates, unemployment and job creation, or income and cost of living.
Where the power comes from, state by state. Using the EIA’s
electric-power-operational-dataroute, retrieve annual generation by source for Colorado and two neighboring states of your choice, filtering on the server with facets as “Let the Server Filter” does. Chart each state’s coal, gas, wind, and solar shares since 2001. Which state changed fastest, and in which years? Check one of your numbers against the EIA’s API Dashboard (Figure 11.3).Two agencies, one identifier. Join two of this chapter’s APIs on a shared identifier, through a crosswalk if their codes differ, as “Combining Census and EIA Data” does. For example, join the EIA’s residential electricity price with the share of each state’s homes heated by electricity (ACS table
B25040, House Heating Fuel). Report every row that didn’t match, and say why it didn’t.Graduate extension (INFO 5617). Read Lazer et al. (2020) on the obstacles and opportunities facing computational social science. Then design and execute a small study that combines data from at least two of this chapter’s government APIs to examine one obstacle or opportunity the paper raises — for example, the promise and difficulty of linking administrative data across agencies and geographic units. Write a formal limitations section that addresses measurement (what your variables actually capture) and coverage (which people, places, or time periods your linked data misses). The goal is not a definitive finding but a defensible design that takes the paper’s warnings seriously.
11.12 Common Issues to Debug
- Census variable codes: The naming convention is opaque. Bookmark the variable catalog and use it as a reference. Variables ending in
Eare estimates; those ending inMare margins of error. - FIPS codes: Geographic identifiers like
08(Colorado) and07850(Boulder) are strings, not integers. Do not strip leading zeros. - FRED series IDs: These are alphanumeric strings; some families follow a pattern (like the SAIPE income series earlier in this chapter), but many do not. Use the FRED website search to find them, then copy the ID into your code exactly.
KeyErrororMISSINGfor a key: Jupyter never received the environment variable. After setting it, quit Jupyter, open a new terminal, and start Jupyter from it; restarting the kernel isn’t enough. See “When a Key SaysMISSING”, above, for the other causes and a stopgap.- A key in a traceback:
response.raise_for_status()raises an error whose message holds the request’s whole URL, and these three APIs put your key in the URL. That is why this chapter checksresponse.status_codeinstead. If an output or a traceback shows your key, clear that cell’s output before you submit or commit the notebook, and if it was published, ask the agency for a new key. - API key exposure: The most common mistake. Environment variables never enter your repository; if you use the JSON-file alternative, add
api_keys.jsonto.gitignorebefore your first commit, or the key will persist in your git history even after deletion. - Rate limiting: Limits vary by agency. As of mid-2026, the Census API publishes no hard limit for keyed users (but expects polite use), and FRED allows roughly 120 requests per minute. Check each API’s documentation for current figures, and stay well within them, especially during automated collection.
- The EIA’s 5,000-row cap: A request to the EIA’s API returns at most 5,000 rows, with an
"incomplete return"warning if more match. Filter with facets, a shorter span, or a lower frequency first; page withoffsetandlengthonly for what is still too large (“Paging withoffsetandlength”, above).
11.13 Key Takeaways
Government APIs provide access to some of the most valuable, reliable, and stable data sources available. The Census Bureau, the Federal Reserve Bank of St. Louis, and the EIA each serve a public mandate, and each API in this chapter carries an idea you will meet again: ask the API what you can ask for (the Census Bureau’s groups and variables); let the server compute (FRED’s units and frequency); and let the server filter (the EIA’s facets). Keep keys out of your notebooks, and when you combine two agencies’ data, spend your effort on the identifiers that join them. These APIs exist because of public interest mandates, and using them effectively is itself a form of civic engagement.
11.14 Further Reading
- U.S. Census Bureau API: https://www.census.gov/data/developers.html
- FRED API documentation: https://fred.stlouisfed.org/docs/api/fred/
- EIA API documentation: https://www.eia.gov/opendata/documentation.php
- Salganik (2018) — Chapter 2: Observing Behavior
- Munzert et al. (2014) — Chapter on working with web APIs


![Screenshot of the EIA API Dashboard. Marker 1: the Data Type section, with Average Price of Electricity to Ultimate Customers checked among four choices. Marker 2: Filter by Facet, with STATEID 1 of 62 selected and SECTORID 1 of 6 selected. Marker 3: the API URL, https://api.eia.gov/v2/electricity/retail-sales/data/?frequency=annual&data[0]=price&facets[stateid][]=CO&facets[sectorid][]=RES with sort, offset, and length parameters.](images/ch-11/eia-browser_annotated.png)




11.11 Social History and Public Interest
Government data APIs embody the value of openness from Chapter 3: they exist because of democratic commitments to transparency. The Census Bureau has been counting the American population every ten years since 1790 (Census Bureau). The American Community Survey, in full operation since 2005, replaced the census long form, last used in 2000, with a survey taken every year, so that communities get current estimates of demographic, social, economic, and housing characteristics every year instead of once a decade (Census Bureau). The Bureau opened its first public API in July 2012 (Census Bureau, 2012). The decision to make this data freely accessible through APIs reflects a commitment to the idea that public data should be accessible to all, not just to researchers with institutional subscriptions or specialized software.
FRED, from the Federal Reserve Bank of St. Louis, grew from a similar philosophy. It descends from the paper data publications of Homer Jones, the bank’s research director from 1958 to 1971, who wanted policymakers and members of the public alike to be able to judge the state of the economy for themselves; the data were printed and sent out by mail. FRED began in 1991 as a free electronic bulletin board that 620 users reached by modem, with 30 data series, and moved to the web in 1995 with 865 (Federal Reserve Bank of St. Louis, 2016). It now serves more than 800,000 series, to anyone, for free (FRED).
The EIA was established on October 1, 1977, under the Department of Energy Organization Act, as the federal government’s independent authority for energy statistics and analysis (EIA), on the same day the Department of Energy itself began work (Department of Energy). Its independence is written into the law: its Administrator “shall not be required to obtain the approval of any other officer or employee of the Department” to collect or analyze information, nor, before publishing, anyone else’s approval of “the substance of any statistical or forecasting technical reports” (42 U.S.C. § 7135(d)). The numbers in “EIA API v2”, above, come from an agency built so that its energy statistics would not have to answer to its own department’s policy.
But government data infrastructure is not immune to erosion. Datasets are withdrawn, APIs deprecated, and political pressure on statistical agencies can affect what data is collected and how it is presented. In 2019 the Supreme Court refused to let the Commerce Department add a citizenship question to the 2020 census on the reason it had given, which “seems to have been contrived” (Department of Commerce v. New York, 2019). In 2017, the first year of the first Trump administration, the Environmental Data & Governance Initiative documented agencies removing or overhauling webpages, documents, and whole websites about climate change, although it found no climate data removed (Environmental Data & Governance Initiative 2018). In early 2025, after an Office of Personnel Management memo applying an executive order on “gender ideology,” the CDC, the FDA, and their parent department took down webpages and datasets, until a federal judge ordered them restored to their versions of January 30 (Alder, 2025). That August President Trump fired the commissioner of the Bureau of Labor Statistics after a weak jobs report, calling the data “rigged” (PBS NewsHour, 2025); that fall, the lapse in appropriations from October 1 to November 12 stopped the Bureau from collecting prices, so the Consumer Price Index has no October 2025 for most series (BLS, 2025); and in December the American Statistical Association reported that most of the 13 federal statistical agencies had lost 20 to 30% of their staff (ASA, 2025). The fragility of government data infrastructure is itself a public interest concern, and a reason to record the date, version, and URL of every government dataset you use.