# Socrata Scraper (`aurenic/socrata-scraper`) Actor

Extract raw rows from any Socrata Open Data (SODA) portal — NYC, Chicago, LA, Seattle, CDC, HHS, CMS, and hundreds more city, county, state, and federal portals. SoQL filters, automatic pagination, no API key required.

- **URL**: https://apify.com/aurenic/socrata-scraper.md
- **Developed by:** [Aurenic](https://apify.com/aurenic) (community)
- **Features:** Limited permissions
- **Stats:** 1 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $1.50 / 1,000 results

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.

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

## What's an Apify Actor?

An Actor is a serverless cloud program that runs on the Apify platform. It has two run modes.
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.

Apify vocabulary and the platform model are defined once, in the agent quickstart at https://apify.com/agents.md.

## 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.

Do not guess an integration path. Every one of them is in the agent quickstart at https://apify.com/agents.md: the Apify MCP server, Agent Skills with the Apify CLI, the JavaScript and Python clients, the REST API, and the account-free path for an agent with no human to sign in. It also carries the rule on stating cost before the first paid run.

For examples already wired to this Actor's own input schema, see the [API](#api) section below.

Each client library has reference documentation the quickstart does not restate: [JavaScript/TypeScript](https://docs.apify.com/api/client/js/docs.md) (`npm install apify-client`) and [Python](https://docs.apify.com/api/client/python/docs.md) (`pip install apify-client`).

# README

## Socrata Scraper

Extract raw rows from any Socrata Open Data (SODA) portal — NYC, Chicago, LA, Seattle, CDC, HHS, CMS, and hundreds more city, county, state, and federal portals. SoQL filters, automatic pagination, no API key required.

### What does Socrata Scraper do?

Socrata powers open data portals for **hundreds of U.S. city, county, state, and federal agencies**. Every dataset on every portal exposes the same REST API (SODA). This actor is the generic reader:

- **Any portal, any dataset** — pass `{ domain, datasetId }` pairs. `data.cityofnewyork.us` + `h9gi-nx95` returns NYC Motor Vehicle Collisions. `data.cdc.gov` + `uqq2-txqb` returns CDC COVID data. Hundreds of combinations.
- **SoQL queries** — filter with `$where`, project with `$select`, sort with `$order`, aggregate with `$group`.
- **Automatic pagination** — walks `$limit` / `$offset` until the dataset is exhausted or `maxRowsPerTarget` is hit.
- **Optional dataset metadata** — emit a separate record with dataset name, description, column schema, and timestamps.

**No API key required.** Anonymous access is allowed at throttled rates. Register a free app token on any portal to raise the limit to 1,000 requests/hour.

### Output fields

Each row is emitted **as-is** from the dataset, with two internal fields added:

| Field | Description |
|---|---|
| recordType | `row` (or `dataset-metadata` when `includeMetadata: true`) |
| \_source | `{ domain, datasetId }` — which dataset produced this row |
| scrapedAt | ISO 8601 timestamp |
| …all dataset columns | Whatever columns the dataset defines (e.g. `unique_key`, `created_date`, `complaint_type`, `borough`, `latitude`, `longitude`) |

#### Dataset metadata record (when enabled)

| Field | Description |
|---|---|
| name | Dataset title |
| description | Dataset description |
| category | Portal category |
| attribution | Attribution string |
| createdAt / rowsUpdatedAt | Dataset timestamps |
| columns | Array of `{ fieldName, name, dataType, description }` |

### Who is it for?

- **Civic tech and gov-tech builders** pulling permit, license, 311, and inspection data at scale
- **Real estate analysts** sourcing building permits, violations, and property records from city portals
- **Public health researchers** querying CDC, HHS, and state health department datasets
- **Journalists** aggregating data across multiple city portals in one run
- **Data scientists** building pipelines that combine datasets from many portals into one schema
- **Market researchers** pulling business licenses and permits as a commercial-activity signal

### Pricing

**$1.50 per 1,000 results.** No subscription.

| Results | Cost |
|---|---|
| 100 | $0.15 |
| 1,000 | $1.50 |
| 10,000 | $15.00 |

### How to use it

1. Add one or more **Targets**: `{ "domain": "...", "datasetId": "..." }` or paste a full resource URL.
2. Optionally add SoQL clauses: **Select**, **Where**, **Order**, **Group**.
3. Set **Limit per Page** (default 5,000) and **Max Rows per Target** (default 50,000).
4. Optionally paste a free **App Token** to raise rate limits.
5. Click **Start**.

### Output example

```json
{
  "recordType": "row",
  "_source": { "domain": "data.cityofnewyork.us", "datasetId": "h9gi-nx95" },
  "crash_date": "2024-03-15T08:30:00.000",
  "borough": "BROOKLYN",
  "zip_code": "11216",
  "latitude": "40.6806",
  "longitude": "-73.9493",
  "on_street_name": "BEDFORD AVE",
  "number_of_persons_injured": "1",
  "number_of_persons_killed": "0",
  "contributing_factor_vehicle_1": "Driver Inattention/Distraction",
  "vehicle_type_code1": "PASSENGER VEHICLE",
  "scrapedAt": "2026-09-24T12:00:00.000Z"
}
```

### Technical details

- **SODA (Socrata Open Data API)** — `https://{domain}/resource/{dataset_id}.json`. Public, unauthenticated.
- **No API key required.** Anonymous access is allowed at throttled rates. A free app token raises limits to 1,000 requests/hour.
- **Pagination** via `$limit` and `$offset`. SODA 2.0 endpoints cap at 50,000 rows per request; SODA 2.1 endpoints have no cap. Default actor page size is 5,000.
- **SoQL query support** — `$select`, `$where`, `$order`, `$group`.
- **No browser, no proxy** — pure JSON REST API.
- **Rate-limit handling** — 429 responses trigger exponential backoff (5s, 10s, 15s, …) up to 5 retries per page.

### Known limits

- **Anonymous rate limits are shared across all users of a portal.** For large or scheduled runs, register a free app token — limits become 1,000 requests/hour per app.
- **Some datasets are private or restricted.** Public datasets work; authenticated-only datasets return HTTP 403.
- **`$group` requires aggregate `$select` expressions.** `$select=borough, count(*)` with `$group=borough` — not a plain column list.
- **Row shape varies by dataset.** Every dataset has its own schema; downstream code must handle that.
- **Portal domains must be exact.** `data.cityofnewyork.us`, not `nyc.gov` or `opendata.cityofnewyork.us`.

### FAQ

**Do I need an API key?** No. Anonymous access works. A free app token raises the rate limit from shared-pool to 1,000 requests/hour per app.

**Do I need a proxy?** No. Datacenter IPs work.

**How do I find a dataset ID?** On any Socrata portal, open a dataset and click **API** — the ID is the `xxxx-xxxx` in the endpoint URL.

**What's the maximum rows I can pull?** Up to `maxRowsPerTarget` (default 50,000, max 1,000,000). For unlimited depth, raise the cap and pagination will continue until the dataset is exhausted.

**What portals are supported?** Any portal whose API endpoint is `{domain}/resource/{id}.json`. That covers NYC, Chicago, LA, SF, Seattle, Austin, Boston, Nashville, Philadelphia, DC, CDC, HHS, CMS, HUD, and hundreds more.

**How do I export data?** After a run, go to Storage → Export as JSON, CSV, Excel.

### Support

Open an issue on the Actor's page for bugs or feature requests.

# Actor input Schema

## `targets` (type: `array`):

Datasets to pull. Each entry: { "domain": "data.cityofnewyork.us", "datasetId": "h9gi-nx95" }. You can also paste full URLs like https://data.cityofnewyork.us/resource/h9gi-nx95.json.

## `select` (type: `string`):

Comma-separated column list (e.g. 'unique_key, created_date, complaint_type'). Leave empty for all columns.

## `where` (type: `string`):

Filter clause (e.g. "borough='BROOKLYN' AND created_date > '2024-01-01'"). Leave empty for no filter.

## `order` (type: `string`):

Sort clause (e.g. 'created_date DESC'). Leave empty for dataset default order.

## `group` (type: `string`):

Group-by clause (e.g. 'borough'). Only valid with aggregate $select expressions.

## `limitPerPage` (type: `integer`):

Rows per request. SODA caps at 50,000. Default 1,000 keeps runs fast — raise for bulk extraction.

## `maxRowsPerTarget` (type: `integer`):

Hard cap on rows per dataset. Default 5,000 (test-friendly). Raise to 1,000,000 for bulk dumps.

## `appToken` (type: `string`):

Optional Socrata app token. Not required — anonymous access works at throttled rates. Register free at any Socrata portal to raise limits to 1,000 requests/hour.

## `includeMetadata` (type: `boolean`):

Emit a separate record per dataset with name, description, column schema, and timestamps.

## `requestDelayMs` (type: `integer`):

Delay between requests. Anonymous rate limits are strict; 250ms is safe. Lower if you supply an app token.

## Actor input object example

```json
{
  "targets": [
    {
      "domain": "data.cityofnewyork.us",
      "datasetId": "h9gi-nx95"
    }
  ],
  "select": "",
  "where": "",
  "order": "",
  "group": "",
  "limitPerPage": 1000,
  "maxRowsPerTarget": 5000,
  "appToken": "",
  "includeMetadata": false,
  "requestDelayMs": 250
}
```

# Actor output Schema

## `results` (type: `string`):

No description

# 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 = {
    "targets": [
        {
            "domain": "data.cityofnewyork.us",
            "datasetId": "h9gi-nx95"
        }
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("aurenic/socrata-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 = { "targets": [{
            "domain": "data.cityofnewyork.us",
            "datasetId": "h9gi-nx95",
        }] }

# Run the Actor and wait for it to finish
run = client.actor("aurenic/socrata-scraper").call(run_input=run_input)

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

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

```

## CLI example

```bash
echo '{
  "targets": [
    {
      "domain": "data.cityofnewyork.us",
      "datasetId": "h9gi-nx95"
    }
  ]
}' |
apify call aurenic/socrata-scraper --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,aurenic/socrata-scraper"
        }
    }
}
```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/8aeDbADVm4nSSiO2I/builds/JruqgFPp7wRyJW6qr/openapi.json
