Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 13 additions & 3 deletions census/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,11 @@ class Client(object):
groups_url = 'https://api.census.gov/data/%s/%s/groups.json'

def __init__(self, key, year=None, session=None, retries=3):
if key == "" or key is None:
raise ValueError(
"As of May 12, 2026, all requests to the US Census API require an API key. "
"You may acquire one at https://api.census.gov/data/key_signup.html"
)
self._key = key
self.session = session or new_session()
if year:
Expand All @@ -112,7 +117,7 @@ def tables(self, year=None):

# Query the table metadata as raw JSON
tables_url = self.groups_url % (year, self.dataset)
resp = self.session.get(tables_url)
resp = self.session.get(tables_url, params={"key": self._key})

# Pass it out
return resp.json()['groups']
Expand All @@ -126,7 +131,7 @@ def fields(self, year=None, flat=False):

fields_url = self.definitions_url % (year, self.dataset)

resp = self.session.get(fields_url)
resp = self.session.get(fields_url, params={"key": self._key})
obj = resp.json()

if flat:
Expand Down Expand Up @@ -216,7 +221,7 @@ def query(self, fields, geo, year=None, sort_by_geoid=False, **kwargs):
@lru_cache(maxsize=1024)
def _field_type(self, field, year):
url = self.definition_url % (year, self.dataset, field)
resp = self.session.get(url)
resp = self.session.get(url, params={"key": self._key})

types = {"fips-for": str,
"fips-in": str,
Expand Down Expand Up @@ -581,6 +586,11 @@ class Census(object):
ALL = ALL

def __init__(self, key, year=None, session=None):
if key == "" or key is None:
raise ValueError(
"As of May 12, 2026, all requests to the US Census API require an API key. "
"You may acquire one at https://api.census.gov/data/key_signup.html"
)

if not session:
session = new_session()
Expand Down
17 changes: 16 additions & 1 deletion census/tests/test_census.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import unittest

from census.core import (
Census, UnsupportedYearException)
Census, Client, UnsupportedYearException)

KEY = os.environ.get('CENSUS_KEY', '')

Expand Down Expand Up @@ -385,5 +385,20 @@ def test_older_sf1(self):
assert result_2010 != result_2000


class TestAPIKeyRequired(unittest.TestCase):

def test_census_raises_without_key(self):
with self.assertRaises(ValueError):
Census(None)
with self.assertRaises(ValueError):
Census("")

def test_client_raises_without_key(self):
with self.assertRaises(ValueError):
Client(None)
with self.assertRaises(ValueError):
Client("")


if __name__ == '__main__':
unittest.main()
Loading