NewAnswers MCP: one question, one checked answer for your agent.See how it works

Guides

Census API: get a key, build an ACS query, fix common errors

By , founder of HyperresearchPublished

The Census Data API lives at https://api.census.gov/data/{year}/{dataset} and answers a GET request that names variables in get= and a geography in for=, with in= to narrow it. Every data query now needs a free API key in &key=: the Census Bureau made keys mandatory in May 2026, so the old allowance of 500 keyless queries a day no longer works. Most “key not working” problems are a missing or mistyped key parameter, and most empty or failed queries ask for a variable or geography that does not exist in that year’s dataset.

This guide uses the 2024 ACS 5-year Detailed Tables (/data/2024/acs/acs5), the newest 5-year vintage on the API. Everything below was read from the Census Data API User Guide and the API’s own metadata on 2026-11-14.

How to request and activate a Census API key

You request a key by filling in an organization name and an email address on the key signup form and agreeing to the terms of service. The API Key page of the User Guide says the key is free and lists the steps:

  1. Open the Developers site and click Request a KEY.
  2. Fill in the form. The guide says to use an email address that ends in .com, .net, .org, .gov or .edu, and the form rejects disposable addresses.
  3. Check your inbox. You “will receive an email with your key code in the message and a link to register it.”
  4. Click the link to activate the key, then add &key= followed by the key to the end of every data call.

If a new key fails, first confirm you clicked the registration link. Keep the key in an environment variable rather than in your code:

Terminal window
export CENSUS_API_KEY=YOUR_KEY_GOES_HERE

On Windows PowerShell, use $env:CENSUS_API_KEY = "YOUR_KEY_GOES_HERE".

The May 2026 key requirement

All data queries have needed a key since May 2026. The Census Bureau’s key video page, dated May 11, 2026, says it “now requires an API key for all queries”, and the User Guide’s Query Limits tab says a key “must be used with all data queries”. The Python census package gives May 12, 2026 as the start date in its own error message.

Before that, the Bureau’s 2020 ACS API handbook allowed up to 500 queries per IP address per day without a key. Tutorials and answers written before May 2026 still repeat that figure, which is why code that once worked keyless now fails.

Metadata is different. The June 2026 Data.census.gov newsletter says the key requirement for metadata queries was removed, so the Discovery Tool, variables.json, groups.json, geography.json and examples.json all answer without a key. Data queries still need one.

The Bureau publishes no per-key daily quota. The terms of service keep a “Right to Limit” clause: use may be limited, and an attempt to exceed or get around the limits can lead to a temporary or permanent block.

How to write an ACS 5-year query for every county in a state

A query for every county in one state puts county:* in for= and the state’s FIPS code in in=. This one asks for the name, median household income (B19013_001E) and its margin of error (B19013_001M) for every county in California (state FIPS 06):

https://api.census.gov/data/2024/acs/acs5?get=NAME,B19013_001E,B19013_001M&for=county:*&in=state:06&key=YOUR_KEY_GOES_HERE

The parts, as the Core Concepts tab defines them:

Part Example What it does
Host and vintage api.census.gov/data/2024 The reference year of the data
Dataset acs/acs5 ACS 5-year Detailed Tables; acs/acs5/subject, acs/acs5/profile and acs/acs5/cprofile are the Subject Tables, Data Profiles and Comparison Profiles
get= NAME,B19013_001E,B19013_001M Up to 50 variables, separated by commas
for= county:* The geography level; * means every value
in= state:06 The parent geography; county requires a state
key= your key Required on every data query

Other for= forms from the guide: state:01,13 returns two states, state:* every state, and county:001&in=state:01 one county. &outputFormat=csv returns CSV instead of JSON, and get=group(B19013) returns every variable in a table, even past the 50-variable limit. The API’s geography list for this dataset shows which levels need which parents; for county it lists "requires": ["state"].

The response is a JSON array of arrays. The first row holds the column names, and the geography codes come last, so this query’s rows read NAME, B19013_001E, B19013_001M, state, county. Numbers arrive as strings, and missing values as null.

ACS estimates can also come back as large negative numbers that are codes, not data. The Notes on ACS Estimate and Annotation Values list them: -666666666 (estimate could not be computed), -999999999 (too few sample cases), -888888888 (not applicable or not available), and -222222222, -333333333 and -555555555 for margins of error. Treat them as missing before you average or sum anything.

Finding variable names like B01001_001E

Variable names are listed per dataset and per year in the API’s metadata, which needs no key. Three files cover most lookups:

  • https://api.census.gov/data/2024/acs/acs5/variables.html: every variable in the dataset, with label and concept. The JSON version, variables.json, is about 10 MB and holds 28,475 entries.
  • https://api.census.gov/data/2024/acs/acs5/groups/B01001.json: every variable in one table.
  • https://api.census.gov/data/2024/acs/acs5/variables/B01001_001E.json: one variable. It returns HTTP 404 if that name does not exist in that dataset and year.

The name follows a pattern. B01001 is the table (Sex by Age), _001 the line, and the last letter the type: per the Example API Queries tab, E is the estimate and M its margin of error, and PE and PM are the percent estimate and its margin of error in some tables. So B01001_001E is the estimate of total population (“Estimate!!Total:”) and B19013_001E median household income in 2024 inflation-adjusted dollars.

Names change between datasets and years. Total population is P001001 in the 2010 decennial Summary File 1 and P1_001N in the 2020 redistricting file, and asking the 2020 file for P001001 returns a 404. Check each variable against the vintage you query; the ACS 5-year page links a 2024 5YR API Changes file listing what changed from the prior year.

Fixing “Invalid Key” and “Missing Key”

A rejected key never returns JSON. The API answers with an HTTP 302 redirect and a header X-DataWebAPI-KeyError: 1, pointing to one of two HTML pages:

  • https://api.census.gov/data/missing_key.html, titled Missing Key, when the request has no key parameter, an empty one, or the key under another name such as api_key.
  • https://api.census.gov/data/invalid_key.html, titled Invalid Key, when a key is present but not accepted.

Both pages say “A valid key must be included with each data API request.” To fix Invalid Key, copy the key again from the email without spaces or quotes, check that the parameter is spelled key in lower case, and, for a new key, click the registration link in the email. The API checks the key before anything else, so a key error can hide a second problem, such as a bad variable name, that shows up once the key works.

In Python, requests follows the redirect, gets the HTML page with status 200, and resp.json() then fails with JSONDecodeError: Expecting value: line 1 column 1 (char 0). That message almost always means a key problem. The helper below turns redirects off so the real cause is visible.

Fixing “error: unknown variable”

An unknown-variable error means the name in get= does not exist in the dataset and year you queried. The Census docs do not print the message; an R package test quotes it as error: unknown variable 'NAME', from a 1990 dataset that has no NAME variable. The common causes are a typo, a name from a different vintage, a missing E or M suffix, or a variable from the Subject Tables or Data Profiles (S... or DP...) sent to the Detailed Tables endpoint. Look the name up in variables/{name}.json for that exact year and dataset; a 404 there confirms it.

Geography has an equivalent. The 2020 handbook warns that some predicates return “unknown/unsupported geography hierarchy” when the area is not in the dataset; areas with fewer than 20,000 people, for example, are only in the 5-year data. Check geography.json for the dataset, or start from its examples.html page. The User Guide’s general advice for an error with no data: check spelling, capitalization and spacing, because API calls are case sensitive.

Common Census API errors and fixes

Error or symptom Cause Fix
302 to missing_key.html, page “Missing Key” No key, an empty key, or api_key= instead of key= Add &key=YOUR_KEY_GOES_HERE
302 to invalid_key.html, page “Invalid Key” Key mistyped, padded with spaces or quotes, or not yours Copy it again; for a new key, click the registration link in the email
Python JSONDecodeError: Expecting value: line 1 column 1 (char 0) requests followed the key redirect to an HTML page Fix the key; use allow_redirects=False to see the redirect
census package ValueError “As of May 12, 2026, all requests to the US Census API require an API key.” Census("") or Census(None) Pass your key
census package APIKeyError The API returned the Invalid Key page Same fix as Invalid Key
error: unknown variable '...' The variable is not in that dataset and year Check variables/{name}.json for that vintage
“unknown/unsupported geography hierarchy” The geography level is not in the dataset, or a required parent is missing from in= Check geography.json; use 5-year data for small areas
-666666666, -999999999, -888888888 in a value ACS special value codes, not data Treat as missing; read the matching EA annotation
Signup form “Disposable emails are not supported.” A throwaway email address Use a permanent address ending in .com, .net, .org, .gov or .edu
More than 50 variables in get= Over the per-query limit Split the call or use group(TABLE)

Python with requests

This helper sends a query, raises a clear error on a key redirect, turns the array of arrays into a list of dicts, and converts numbers and ACS special values. It uses requests and nothing else.

import os
import requests
API_KEY = os.environ["CENSUS_API_KEY"] # set to YOUR_KEY_GOES_HERE
BASE_URL = "https://api.census.gov/data"
SPECIAL_VALUES = {-666666666, -999999999, -888888888, -222222222, -333333333, -555555555}
def census_get(year, dataset, variables, geo_for, geo_in=None):
"""Run one Census Data API query and return a list of dicts."""
params = {"get": ",".join(variables), "for": geo_for, "key": API_KEY}
if geo_in:
params["in"] = geo_in
resp = requests.get(
f"{BASE_URL}/{year}/{dataset}",
params=params,
timeout=60,
allow_redirects=False, # a key error is a 302 to an HTML page
)
if resp.headers.get("X-DataWebAPI-KeyError"):
raise RuntimeError(f"Census key rejected, see {resp.headers.get('Location')}")
if resp.status_code != 200:
raise RuntimeError(f"Census {resp.status_code}: {resp.text[:300]}")
header, *rows = resp.json()
return [dict(zip(header, row)) for row in rows]
def to_number(value):
"""Turn a Census string into a float; None for null and ACS special codes."""
if value is None:
return None
number = float(value)
return None if int(number) in SPECIAL_VALUES else number
def variable_exists(year, dataset, name):
"""True if the variable is in that dataset and year (metadata needs no key)."""
url = f"{BASE_URL}/{year}/{dataset}/variables/{name}.json"
return requests.get(url, timeout=30).status_code == 200
if __name__ == "__main__":
for name in ("B19013_001E", "B19013_001M"):
assert variable_exists(2024, "acs/acs5", name), name
counties = census_get(
2024, "acs/acs5", ["NAME", "B19013_001E", "B19013_001M"],
geo_for="county:*", geo_in="state:06",
)
for row in counties[:5]:
print(row["NAME"], to_number(row["B19013_001E"]), to_number(row["B19013_001M"]))

To get a pandas DataFrame, pass the rows straight in: pd.DataFrame(counties), then apply to_number to the value columns. Keep state and county as strings, because FIPS codes have leading zeros.

Python with the census package

The census package (version 0.8.27 on PyPI, May 2026) wraps the ACS and decennial endpoints and returns a list of dicts. It defaults to the 2024 ACS 5-year data.

import os
from census import Census
c = Census(os.environ["CENSUS_API_KEY"])
# Every county in California: same query as the URL above.
rows = c.acs5.state_county(("NAME", "B19013_001E", "B19013_001M"), "06", Census.ALL)
# The general form, for any geography.
rows = c.acs5.get(("NAME", "B19013_001E"), {"for": "county:*", "in": "state:06"})
# An earlier vintage.
rows_2019 = c.acs5.state_county(("NAME", "B19013_001E"), "06", Census.ALL, year=2019)
print(rows[:3])

The trade-offs, read from the package source on 2026-11-14:

  • Good: it splits calls of more than 49 variables into chunks and joins them on GEO_ID, so the 50-variable limit stops mattering. It looks up each variable’s type in the metadata and returns numbers as floats. It retries when the API returns one known transient error message.
  • Watch: numeric conversion keeps ACS special codes such as -666666666 as numbers, so filter them yourself. It raises APIKeyError (from census.core) for the Invalid Key page, but a Missing Key page surfaces as a JSON decode error. It covers ACS, decennial SF1 and redistricting data only; for other datasets, such as County Business Patterns or the time series, use the requests helper.

Attribution and terms

The terms of service require any service that uses the API to show this notice prominently: “This product uses the Census Bureau Data API but is not endorsed or certified by the Census Bureau.” They also forbid using the data to identify any person, household or business. Questions go to census.data@census.gov.

When you need Census data next to other sources

Hyperresearch queries the Census Bureau’s data as one of its 120+ data sources, for teams that want ACS figures cited in a report instead of raw arrays; AI market research shows how Census revenue anchors a market size. For other public data APIs, see the FRED API in Python and ClinicalTrials.gov API v2 guides.

Sources