# US Census Bureau Data API Scraper (`muhammadafzal/us-census-bureau-scraper`) Actor

Query official US Census Bureau API datasets for ACS, Decennial Census, and public data research. Returns structured rows with variables, geography identifiers, source URL, and retrieval time. Charged $0.00005 per valid query plus $0.0005 per row.

- **URL**: https://apify.com/muhammadafzal/us-census-bureau-scraper.md
- **Developed by:** [Muhammad Afzal](https://apify.com/muhammadafzal) (community)
- **Categories:** Automation, MCP servers
- **Stats:** 1 total users, 0 monthly users, 0.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $0.50 / 1,000 census row returneds

This Actor is paid per event and usage. You are charged both the fixed price for specific events and for Apify platform usage.

Learn more: https://docs.apify.com/platform/actors/running/actors-in-store#pay-per-event

## What's an Apify Actor?

Actors are web data automations that power AI and operations. They run on the Apify platform to scrape websites, process data, connect APIs, and automate workflows.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.
Actors are written with capital "A".

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.
The best way to integrate Actors is as follows.

- **AI agents and MCP clients** — the [Apify MCP server](https://docs.apify.com/integrations/mcp.md) at `https://mcp.apify.com` (remote, streamable HTTP, OAuth on first use).
- **Agentic workflows and local Actor development** — [Agent Skills](https://apify.com/.well-known/agent-skills/index.json) with the [Apify CLI](https://docs.apify.com/cli/docs.md): `npm install -g apify-cli`, then `apify login`.
- **JavaScript/TypeScript projects** — the official [JS/TS client](https://docs.apify.com/api/client/js/docs.md): `npm install apify-client`.
- **Python projects** — the official [Python client](https://docs.apify.com/api/client/python/docs.md): `pip install apify-client`.
- **Any other language** — the [REST API](https://docs.apify.com/api/v2.md).

For usage examples, see the [API](#api) section below.

For more details, see Apify documentation as [Markdown index](https://docs.apify.com/llms.txt) and [Markdown full-text](https://docs.apify.com/llms-full.txt).

# README

## US Census Bureau Data Scraper

Query official US Census Bureau Data API datasets and return one structured dataset item per Census API row. It is designed for analysts, researchers, public-sector teams, geospatial workflows, demographic analysis, and AI agents that need current Census variables by geography.

### What it returns

Each item contains:

| Field | Description |
| --- | --- |
| `dataset` | Relative Census API dataset path, such as `acs/acs5`. |
| `year` | Census vintage year. |
| `values` | Requested variable codes mapped to their returned string or `null` values. |
| `geography` | Geography identifiers returned by the API, such as `state`, `county`, `place`, or `tract`. |
| `queryUrl` | The official Census API URL used for the row. |
| `retrievedAt` | UTC retrieval timestamp. |

The actor preserves Census values as strings because the Census API returns tabular data as text and variable codes can represent counts, percentages, annotations, dates, or other dataset-specific values. Use the dataset's variable metadata to interpret units and margins of error.

### When to use it

Use it for ACS, Decennial Census, Population Estimates, Economic Census, PUMS, and other public datasets exposed through the Census Data API. The actor passes through standard `get`, `for`, `in`, predicate, and `ucgid` parameters, and adds the required secret API key at runtime.

Do not use it to scrape the interactive `data.census.gov` website, download bulk files that are not available through the Data API, or infer a variable's meaning from its code alone. Choose the dataset and variable codes from the official Census dataset documentation first.

### Inputs

```json
{
  "dataset": "acs/acs5",
  "year": 2023,
  "variables": ["NAME", "B01001_001E"],
  "for": "county:*",
  "in": ["state:06"],
  "maxResults": 100
}
```

This returns 2023 ACS 5-year county rows inside California with each county name and total-population estimate. A state-level default query is prefilled so the actor has a small, valid health-test request.

For a mixed-geography query supported by a dataset, use `ucgid` instead of `for`/`in`:

```json
{
  "dataset": "acs/acs5",
  "year": 2023,
  "variables": ["NAME", "B01001_001E"],
  "ucgid": "0400000US24"
}
```

Additional dataset-specific predicates can be supplied as key-value pairs:

```json
{
  "predicates": { "NAME": "California" }
}
```

The required `CENSUS_API_KEY` environment variable must be configured as a secret in Apify before a run. The current Census API requires a valid key on data requests. Do not put API keys in public input; the actor never includes the key in dataset provenance URLs or logs.

### Output and limits

The run summary is stored in the `OUTPUT` key-value record. It includes the number of API rows available, rows returned, the query URL, warnings, and whether `maxResults` or the Apify charge limit stopped output. Census does not expose a generic page cursor; if the result is capped, narrow the geography or predicates for the next query.

Valid queries with no rows complete successfully with an empty dataset and a truthful summary. Invalid input and Census HTTP/API failures are reported in `OUTPUT` with `INVALID_INPUT` or `WARNING` status; error objects are not mixed into the dataset.

### Pricing

| Event | Price |
| --- | ---: |
| Actor start | $0.00005 per valid run |
| Census row returned | $0.0005 per dataset item |

Example: a 52-row state query costs approximately **$0.02605** in actor events, excluding Apify platform usage. The start event is charged only for valid requests; row events are charged only for rows actually returned.

### Data source and compliance

The source is the public [US Census Bureau Data API](https://api.census.gov/data.html). Review the selected dataset's official documentation for coverage, vintage, variable definitions, margins of error, suppression, and any geographic limitations. This actor does not bypass access controls or collect private information.

# Actor input Schema

## `dataset` (type: `string`):

Use this to select the Census dataset path after the year, for example 'acs/acs5' or 'dec/pl'. Defaults to 'acs/acs5'. This is not a data.census.gov URL.

## `year` (type: `integer`):

Use this to choose the Census vintage year, for example 2023. Defaults to 2023; choose a year published by the selected dataset.

## `variables` (type: `array`):

Use this to choose Census variable codes returned in each row, for example 'NAME' and 'B01001\_001E'. Defaults to NAME and total population. This is not a free-text search across Census websites.

## `for` (type: `string`):

Use this to set the Census API 'for' geography selector, for example 'state:*' or 'county:*'. Defaults to state:\*; use ucgid instead when selecting mixed geographies.

## `in` (type: `array`):

Use this to restrict results inside parent geographies, for example 'state:06' when querying counties in California. Defaults to no parent filter; this is not the same as the 'for' geography.

## `predicates` (type: `object`):

Use this for additional Census API predicate parameters such as NAME or DATE\_CODE, for example {"NAME": "California"}. Defaults to none; do not place get, for, in, key, or ucgid here.

## `ucgid` (type: `string`):

Use this for UCGID geography selection supported by newer Census datasets, for example '0400000US24'. Leave blank when using the standard for/in selectors.

## `maxResults` (type: `integer`):

Use this to cap rows returned and billed from the Census API response. Defaults to 1000, with a maximum of 50000. This is a client-side cap, not Census server pagination.

## Actor input object example

```json
{
  "dataset": "acs/acs5",
  "year": 2023,
  "variables": [
    "NAME",
    "B01001_001E"
  ],
  "for": "state:*",
  "in": [
    "state:06"
  ],
  "predicates": {
    "NAME": "California"
  },
  "ucgid": "0400000US24",
  "maxResults": 100
}
```

# Actor output Schema

## `dataset` (type: `string`):

Structured rows returned by the official Census API.

## `datasetCsv` (type: `string`):

The same Census rows as CSV.

## `summary` (type: `string`):

Status, row counts, query URL, truncation flags, and warnings.

## `consoleRun` (type: `string`):

Live run status, logs, and dataset preview.

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {
    "dataset": "acs/acs5",
    "year": 2023,
    "variables": [
        "NAME",
        "B01001_001E"
    ],
    "for": "state:*"
};

// Run the Actor and wait for it to finish
const run = await client.actor("muhammadafzal/us-census-bureau-scraper").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = {
    "dataset": "acs/acs5",
    "year": 2023,
    "variables": [
        "NAME",
        "B01001_001E",
    ],
    "for": "state:*",
}

# Run the Actor and wait for it to finish
run = client.actor("muhammadafzal/us-census-bureau-scraper").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print("💾 Check your data here: https://console.apify.com/storage/datasets/" + run["defaultDatasetId"])
for item in client.dataset(run["defaultDatasetId"]).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{
  "dataset": "acs/acs5",
  "year": 2023,
  "variables": [
    "NAME",
    "B01001_001E"
  ],
  "for": "state:*"
}' |
apify call muhammadafzal/us-census-bureau-scraper --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "command": "npx",
            "args": [
                "mcp-remote",
                "https://mcp.apify.com/?tools=muhammadafzal/us-census-bureau-scraper",
                "--header",
                "Authorization: Bearer <YOUR_API_TOKEN>"
            ]
        }
    }
}

```

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/ioYWqIg7cISamcmb0/builds/v6Pcv5asmxnIcl8XL/openapi.json
