# New York State Open Data Scraper (`automation-lab/new-york-open-data-catalog-export`) Actor

Search data.ny.gov datasets, export catalog metadata and column schemas, and fetch bounded rows from selected public dataset IDs.

- **URL**: https://apify.com/automation-lab/new-york-open-data-catalog-export.md
- **Developed by:** [Stas Persiianenko](https://apify.com/automation-lab) (community)
- **Categories:** Other
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $4.25 / 1,000 item extracteds

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.
Since this Actor supports Apify Store discounts, the price gets lower the higher subscription plan you have.

Learn more: https://docs.apify.com/actors/running/actors-in-store.md#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

## New York State Open Data Scraper

Search **New York State open data** on data.ny.gov, export dataset catalog metadata and column schemas, and fetch bounded rows from public dataset IDs.

Use the Actor to inventory government datasets, inspect stable Socrata field names before building a pipeline, or refresh selected public rows on an Apify schedule. It uses official anonymous JSON endpoints and does not need a data.ny.gov account or API token.

### What does this Actor do?

The Actor supports two complementary jobs in one run:

1. Search the data.ny.gov catalog by words such as `public health`, `transportation`, or `unemployment`.
2. Fetch a bounded number of rows from explicit Socrata resource IDs such as `5xaw-6ayf`.

Catalog records include:

- stable dataset ID;
- title and description;
- publishing agency or attribution;
- category and tags;
- source and API links;
- available update timestamps and usage counts;
- column names, API field names, source types, and descriptions.

Selected dataset rows preserve their original public fields inside `data`, together with dataset identity and provenance.

### Who is it for?

#### Civic-data teams

Create a searchable inventory of New York State datasets and inspect when metadata or source data changed.

#### Data engineers

Resolve Socrata field names and types, then feed bounded row exports into recurring ETL jobs.

#### Researchers and journalists

Find official datasets on a topic, retain source links, and collect a reproducible sample for analysis.

#### Public-sector analysts

Review schemas across related datasets without opening each portal page manually.

### Why use it?

- **Official structured routes:** requests go to Socrata's public catalog, metadata, and SODA row APIs.
- **Catalog plus rows:** discover datasets and sample selected resources with one input.
- **Bounded output:** explicit catalog and per-dataset limits prevent accidental unlimited exports.
- **Pipeline-friendly:** stable provenance fields wrap arbitrary source rows without renaming their original keys.
- **Visible failures:** invalid IDs and upstream errors fail the run instead of producing a misleading empty success.
- **No paid proxy fallback:** direct official APIs keep runtime and transfer costs predictable.

### Getting started

1. Open the Actor input tab.
2. Enter a catalog `query`, one or more `datasetIds`, or both.
3. Set `maxCatalogItems` for search results.
4. Set `rowsPerDataset` above zero only when you want source rows.
5. Leave `includeCatalog` enabled to receive metadata and column schemas.
6. Click **Start**.
7. Open the default dataset to download JSON, CSV, Excel, XML, or RSS through Apify.

A small catalog search:

```json
{
  "query": "public health",
  "maxCatalogItems": 10,
  "rowsPerDataset": 0,
  "includeCatalog": true
}
```

A selected dataset export:

```json
{
  "datasetIds": ["5xaw-6ayf"],
  "rowsPerDataset": 25,
  "includeCatalog": true
}
```

### Input parameters

| Field | Type | Default | Description |
| --- | --- | --- | --- |
| `query` | string | — | Search words for the data.ny.gov catalog. Maximum 200 characters. |
| `datasetIds` | string\[] | `[]` | Up to 50 data.ny.gov IDs in `xxxx-xxxx` form. |
| `maxCatalogItems` | integer | `20` | Maximum catalog matches, from 1 to 1,000. |
| `rowsPerDataset` | integer | `0` | Maximum rows per selected ID, from 0 to 5,000. |
| `includeCatalog` | boolean | `true` | Include metadata and schema records. |

Provide `query`, `datasetIds`, or both.

When `includeCatalog` is false, at least one dataset ID is required because a query alone would otherwise have no output.

Duplicate IDs are fetched once.

### Search catalog metadata

Set `query` and keep `includeCatalog` enabled.

The Actor pages the official Socrata Discovery API, restricts results to `data.ny.gov`, validates the returned source domain, and deduplicates by resource ID.

Search is full-text relevance search supplied by Socrata. It is not an exact phrase filter and may match titles, descriptions, categories, publishers, or tags.

Use a narrow term when you need a focused inventory:

```json
{
  "query": "electric vehicle charging",
  "maxCatalogItems": 50
}
```

### Export dataset schemas

Every `catalog` item contains a `columns` array.

Each column can include:

| Field | Meaning |
| --- | --- |
| `name` | Human-readable portal column label. |
| `fieldName` | Field name used in Socrata API rows and SoQL. |
| `dataType` | Socrata source type such as Text, Number, or Calendar date. |
| `description` | Publisher-provided explanation when available. |

Schema fields are nullable because publishers do not populate every metadata property consistently.

### Fetch selected public dataset rows

Supply one or more IDs and set `rowsPerDataset` above zero.

Example using New York's Mega Millions winning-number dataset:

```json
{
  "datasetIds": ["5xaw-6ayf"],
  "rowsPerDataset": 10,
  "includeCatalog": true
}
```

The Actor first resolves public metadata, then requests rows in bounded pages. It does not fetch private datasets and does not accept credentials.

The original row is stored under `data`. Source column names therefore differ by selected dataset.

### Output fields

The default dataset can contain two `recordType` values.

#### `catalog`

| Field | Description |
| --- | --- |
| `datasetId` | Stable Socrata resource ID. |
| `name` | Dataset title. |
| `description` | Publisher's dataset description. |
| `attribution` | Publishing agency or organization. |
| `category`, `tags` | Discovery labels from data.ny.gov. |
| `createdAt`, `updatedAt` | Available lifecycle timestamps. |
| `dataUpdatedAt`, `metadataUpdatedAt`, `rowsUpdatedAt` | More specific update evidence when exposed. |
| `columns` | Column schema array. |
| `sourceUrl` | Human-readable portal page. |
| `apiUrl` | Public JSON row endpoint. |
| `fetchedAt` | Actor collection timestamp. |

#### `datasetRow`

| Field | Description |
| --- | --- |
| `datasetId` | Source resource ID. |
| `datasetName` | Resolved dataset title. |
| `rowIndex` | Zero-based offset in this export. |
| `data` | Original public row object. |
| `sourceUrl` | Human-readable dataset page. |
| `apiUrl` | Public endpoint for the row offset. |
| `fetchedAt` | Actor collection timestamp. |

### Output example

A catalog result has this shape:

```json
{
  "recordType": "catalog",
  "datasetId": "5xaw-6ayf",
  "name": "Lottery Mega Millions Winning Numbers: Beginning 2002",
  "attribution": "New York State Gaming Commission",
  "tags": ["mega millions", "winning numbers"],
  "columns": [
    {
      "name": "Draw Date",
      "fieldName": "draw_date",
      "dataType": "Calendar date",
      "description": null
    }
  ],
  "sourceUrl": "https://data.ny.gov/d/5xaw-6ayf",
  "apiUrl": "https://data.ny.gov/resource/5xaw-6ayf.json",
  "fetchedAt": "2025-02-15T12:00:00.000Z"
}
```

A row result has this shape:

```json
{
  "recordType": "datasetRow",
  "datasetId": "5xaw-6ayf",
  "datasetName": "Lottery Mega Millions Winning Numbers: Beginning 2002",
  "rowIndex": 0,
  "data": {
    "draw_date": "2025-01-15T00:00:00.000",
    "winning_numbers": "01 02 03 04 05",
    "mega_ball": "06"
  },
  "sourceUrl": "https://data.ny.gov/d/5xaw-6ayf"
}
```

Values shown are representative and may differ from current source rows.

### How much does it cost to export New York State open data?

Pricing uses one start event plus one `item` event for every useful catalog record or selected dataset row saved.

At the BRONZE tier:

- run start: $0.005;
- item: $0.007076 per saved record.

For example, 25 catalog records cost about $0.182 including the start event. A run producing one metadata record and 100 source rows costs about $0.720.

Apify plan tiers can change the per-item price. Check the Actor pricing panel for the applicable live tier before a large run.

Failed, duplicate, or rejected records are not item-charged.

### Recurring civic-data ETL

Create an Apify schedule with stable `datasetIds` and `rowsPerDataset`.

Typical flow:

1. Search once to identify relevant datasets.
2. Save stable IDs and column field names.
3. Create a Task containing the selected IDs.
4. Schedule the Task daily, weekly, or monthly.
5. Send dataset output to a webhook, cloud storage, database, or automation platform.
6. Compare `fetchedAt` runs or source update timestamps in your downstream system.

The Actor exports current snapshots. It does not itself store historical diffs or send change alerts.

### Spreadsheet workflow

After a run:

1. Open **Dataset**.
2. Select the overview view for normalized provenance fields.
3. Download JSON for complete nested `data` and `columns` objects.
4. Use CSV or Excel when your chosen output contains only fields suitable for tabular flattening.

Arbitrary dataset row columns remain nested under `data`; downstream code should select the source fields it needs.

### API usage with cURL

Start a run and wait for its dataset:

```bash
curl -X POST \
  "https://api.apify.com/v2/acts/automation-lab~new-york-open-data-catalog-export/run-sync-get-dataset-items?token=$APIFY_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"query":"unemployment","maxCatalogItems":10}'
```

Keep the token in an environment variable or secret manager.

### API usage with JavaScript

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

const client = new ApifyClient({ token: process.env.APIFY_TOKEN });
const run = await client.actor('automation-lab/new-york-open-data-catalog-export').call({
  datasetIds: ['5xaw-6ayf'],
  rowsPerDataset: 20,
  includeCatalog: true,
});
const { items } = await client.dataset(run.defaultDatasetId).listItems();
console.log(items);
```

### API usage with Python

```python
from apify_client import ApifyClient
import os

client = ApifyClient(os.environ['APIFY_TOKEN'])
run = client.actor('automation-lab/new-york-open-data-catalog-export').call(
    run_input={
        'query': 'public health',
        'maxCatalogItems': 20,
    }
)
items = client.dataset(run['defaultDatasetId']).list_items().items
print(items)
```

### Use with Apify MCP

Add the Actor to Claude Code:

```bash
claude mcp add --transport http apify \
  "https://mcp.apify.com?tools=automation-lab/new-york-open-data-catalog-export"
```

#### Claude Desktop, Cursor, and VS Code setup

Claude Desktop, Cursor, and VS Code clients can use this MCP server configuration:

```json
{
  "mcpServers": {
    "apify": {
      "url": "https://mcp.apify.com?tools=automation-lab/new-york-open-data-catalog-export"
    }
  }
}
```

Example prompts:

- "Search New York State open data for public health and return five datasets with their API field names."
- "Fetch ten rows from data.ny.gov dataset 5xaw-6ayf and summarize its schema."
- "Prepare an inventory of unemployment datasets with source links and update timestamps."

### Limits and responsible scaling

- Catalog output is capped at 1,000 records per run.
- Up to 50 explicit dataset IDs are accepted.
- Row output is capped at 5,000 rows per selected dataset.
- Requests time out after 20 seconds and retry transient failures at most three times.
- Deterministic 4xx responses, including invalid or unavailable IDs, are not retried blindly.
- No proxy, browser, login, private app token, or CAPTCHA service is used.

Start small before increasing limits on a schedule.

### Data freshness and completeness

The Actor reports what Socrata returns at run time.

Publishers control metadata quality, schemas, row ordering, update timing, and dataset availability. Some timestamps, descriptions, tags, usage counts, or column descriptions can be absent.

Rows use the source's default API order. If a stable business ordering matters, sort or key them downstream using fields from that dataset's schema.

Catalog search relevance and result totals can change as data.ny.gov content changes.

### Error behavior

The run fails visibly when:

- neither a query nor a dataset ID is provided;
- a query is blank or too long;
- an ID does not match `xxxx-xxxx`;
- a requested dataset is missing, private, or unavailable;
- the source repeatedly times out or returns a transient server error;
- the source returns a non-JSON response.

A valid search with no matches succeeds with an empty dataset.

### Troubleshooting

#### Why did my selected ID fail with HTTP 404?

Confirm the ID on the data.ny.gov dataset page. IDs from other Socrata portals are outside this Actor's scope, and deleted or private views are unavailable.

#### Why are row fields inside `data`?

Every Socrata dataset defines its own columns. Nesting the unchanged source row preserves field names while keeping common identity and provenance fields stable.

#### Why did search return fewer records than requested?

The source may have fewer relevant data.ny.gov records, or some catalog entries may not be tabular dataset IDs suitable for this product.

#### Can I use SoQL filters?

Not in this initial version. The Actor deliberately offers bounded first rows rather than arbitrary SQL. Use the emitted `apiUrl` and schema field names to build a specialized downstream request if needed.

#### Does it include NYC Open Data?

No. Search and selected IDs are restricted to the New York State `data.ny.gov` portal. NYC's `data.cityofnewyork.us` is a separate source.

### Legal and responsible use

This Actor accesses public government open-data endpoints without authentication.

Users remain responsible for:

- following dataset-specific licenses and attribution requirements;
- reviewing publisher disclaimers and data-quality notes;
- avoiding harmful re-identification or misuse of sensitive public records;
- applying privacy, retention, and security rules in downstream systems;
- respecting Socrata and data.ny.gov usage policies and practical rate limits.

Public availability does not guarantee that every downstream use is appropriate.

### Related Automation Lab Actors

- [USGS LiDAR Downloads Scraper](https://apify.com/automation-lab/public-lidar-dataset-catalog-exporter) for specialized USGS point-cloud catalog and download-link acquisition.
- [Schema-Guided Web Data to Excel](https://apify.com/automation-lab/schema-guided-web-data-to-excel) for turning supported web data into a controlled spreadsheet schema.
- [New York State Contract Reporter Scraper](https://apify.com/automation-lab/new-york-state-contract-reporter-scraper) for procurement opportunity monitoring rather than general open-data catalog inventory.

Choose this Actor when you need data.ny.gov catalog discovery, schemas, or selected public Socrata rows.

### FAQ

#### Do I need a data.ny.gov application token?

No. The Actor uses anonymous public endpoints for bounded requests.

#### Can I search and fetch rows in the same run?

Yes. Supply both `query` and `datasetIds`. Search matches do not automatically trigger row downloads; only explicit IDs do.

#### Are catalog records and rows separate datasets?

No. Both are in the default dataset and distinguished by `recordType`, which keeps standard Apify integrations simple.

#### Are duplicate dataset IDs charged twice?

No. Duplicate explicit IDs are deduplicated. Catalog metadata already emitted by search is not emitted again for the same selected ID.

#### Can the Actor export all rows from a very large dataset?

It intentionally caps each selected dataset at 5,000 rows. This protects schedules from unexpectedly large output and cost. For bulk archival, use the source's dedicated export facilities.

#### Does the Actor detect changes between runs?

It emits current metadata, timestamps, schemas, and rows. Schedule it and compare outputs in your own database or automation workflow; the Actor does not maintain a private change history.

# Actor input Schema

## `query` (type: `string`):

Words to search across data.ny.gov dataset titles, descriptions, agencies, categories, and tags.

## `datasetIds` (type: `array`):

Optional data.ny.gov Socrata resource IDs in xxxx-xxxx form. The Actor exports metadata and up to rowsPerDataset rows for each ID.

## `maxCatalogItems` (type: `integer`):

Maximum matching catalog records to export when query is supplied.

## `rowsPerDataset` (type: `integer`):

Maximum public data rows to export for each dataset ID. Keep 0 to export metadata and schemas only.

## `includeCatalog` (type: `boolean`):

Emit catalog metadata and column schemas. Disable only when datasetIds are supplied and you need data rows alone.

## Actor input object example

```json
{
  "query": "transportation",
  "datasetIds": [],
  "maxCatalogItems": 20,
  "rowsPerDataset": 0,
  "includeCatalog": true
}
```

# Actor output Schema

## `overview` (type: `string`):

Open the default dataset overview containing all saved New York State open data records.

# 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 = {
    "query": "transportation"
};

// Run the Actor and wait for it to finish
const run = await client.actor("automation-lab/new-york-open-data-catalog-export").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 = { "query": "transportation" }

# Run the Actor and wait for it to finish
run = client.actor("automation-lab/new-york-open-data-catalog-export").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 '{
  "query": "transportation"
}' |
apify call automation-lab/new-york-open-data-catalog-export --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,automation-lab/new-york-open-data-catalog-export"
        }
    }
}
```

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/y7evXOxlfcJUKabPB/builds/nA3YjCFzWCqRSLTDX/openapi.json
