3 skills · 34 min
Skills
Skill 2 of 3
Query the OpenData API for data research and analysis.
8 minutes · 1,741 words · 22 sections
Install
npx skills add tryopendata/skills --skill opendata-apinpx skills add tryopendata/skills/plugin marketplace add tryopendata/skillsThe first command installs just this skill, by the name in its SKILL.md; the second installs the whole repository.
Query datasets stored as Parquet files through a REST API backed by DuckDB. The API returns JSON by default, with support for CSV, TSV, and XLSX exports.
Base URL: https://api.tryopendata.ai (production) or http://localhost:8000 (local dev). Default to use production
All endpoints require authentication in production. Before making API calls, resolve a Bearer token using this sequence:
OPENDATA_API_KEY is set, use it.~/.config/opendata/auth.json. If it exists, extract the token:
method: "api_key" -> use the api_key fieldmethod: "clerk" -> use the access_token field (check expires_at hasn’t passed)method field, just api_key) -> use the api_key fieldopendata CLI is installed (which opendata)opendata auth login and let the user authenticatebrew install tryopendata/opendata/opendata or curl -fsSL https://raw.githubusercontent.com/tryopendata/opendata/main/scripts/install-cli.sh | bash), then run opendata auth loginOPENDATA_API_KEY manually with a key from https://tryopendata.ai/settings/api-keys (opens in a new tab)Once resolved, pass the token via Authorization: Bearer header:
curl -H "Authorization: Bearer $TOKEN" \
"https://api.tryopendata.ai/v1/datasets/fred/cpi?limit=5"If you get a 401 during a session, re-run the resolution sequence (the token may have expired).
Local dev (localhost:8000) does not require auth when running the standalone opendata server (make quickstart). The backend server (make dev-all) requires auth for write endpoints but allows unauthenticated reads.
For analysis (aggregations, joins, window functions), use SQL:
# Average CPI by year, most recent first
curl -X POST "https://api.tryopendata.ai/v1/datasets/fred/cpi/query" \
-H "Authorization: Bearer ${OPENDATA_API_KEY}" \
-H "Content-Type: application/json" \
-d '{"sql": "SELECT EXTRACT(YEAR FROM date) as year, AVG(value) as avg_cpi FROM data GROUP BY 1 ORDER BY 1 DESC LIMIT 10"}'Parameterized queries (avoids escaping issues):
curl -X POST "https://api.tryopendata.ai/v1/datasets/owid/gdp/query" \
-H "Authorization: Bearer ${OPENDATA_API_KEY}" \
-H "Content-Type: application/json" \
-d '{"sql": "SELECT * FROM data WHERE country_name = ? AND year >= ? ORDER BY year", "params": ["United States", 2020]}'For simple row fetches (no aggregation), use the REST endpoint:
# Get the 5 most recent CPI values
curl -H "Authorization: Bearer ${OPENDATA_API_KEY}" \
"https://api.tryopendata.ai/v1/datasets/fred/cpi?limit=5&sort=-date"Do NOT append /query to GET requests. GET /v1/datasets/fred/cpi/query will fail with a SUBDATASET_NOT_FOUND error because the API interprets query as a subdataset name. The POST /query endpoint is a separate SQL interface (see sql-query.md (opens in a new tab)).
All data endpoints live under /v1/datasets/.
If you have access to OpenData MCP tools (search_datasets, query_dataset, query_sql), prefer them over direct API calls. The MCP tools handle auth, pagination, and response formatting automatically. Use query_sql for analytical queries (aggregations, joins, window functions) and query_dataset for simple row fetches. Fall back to the REST API below only when:
| Method | Path | Description |
|---|---|---|
| GET | /v1/datasets/{provider}/{dataset} | Query dataset rows (flat) or list subdatasets (hierarchical) |
| GET | /v1/datasets/{provider}/{dataset}/{subdataset} | Query subdataset rows |
| GET | /v1/datasets/{provider}/{dataset}/columns | Column metadata and statistics |
| GET | /v1/datasets/{provider}/{dataset}/columns/{name} | Single column detail with full value list |
| GET | /v1/datasets/{provider}/{dataset}/meta | Dataset metadata (schema, views, graph scores, merged enrichment) |
| GET | /v1/datasets/{provider}/{dataset}/views | List available views |
| POST | /v1/datasets/{provider}/{dataset}/query | Execute SQL query (authenticated) |
| POST | /v1/query | Cross-dataset SQL query (join multiple datasets) |
| Method | Path | Description |
|---|---|---|
| GET | /v1/datasets/{provider}/{dataset}/meta/enriched | AI-enriched metadata (descriptions, tags, methodology, coverage) |
| GET | /v1/datasets/{provider}/{dataset}/meta/view-suggestions | AI-suggested views (timeseries, lookup, wide_to_long, pivot) |
| POST | /v1/datasets/{provider}/{dataset}/meta/view-suggestions/{id}/apply | Apply a view suggestion (admin) |
| GET | /v1/datasets/{provider}/{dataset}/chart | Dataset chart data with auto-downsampling |
| GET | /v1/datasets/{provider}/{dataset}/activity | Recent activity events (ingestion, enrichment, schema changes) |
| GET | /v1/datasets/{provider}/{dataset}/related | Related datasets (semantic + join + graph signals) |
| Method | Path | Description |
|---|---|---|
| GET | /v1/datasets/{provider}/{dataset}/joinable | List joinable datasets for composition |
| POST | /v1/datasets/{provider}/{dataset}/compose/preview | Preview a cross-dataset join (LEFT JOIN) |
| GET | /v1/datasets/{provider}/{dataset}/compose/download.csv | Download a composed join as CSV (auth required) |
| Method | Path | Description |
|---|---|---|
| GET | /v1/search | Search datasets (keyword/semantic/hybrid, graph-boosted) |
| GET | /v1/search/suggest | Autocomplete suggestions for search typeahead |
| GET | /v1/discover | Search datasets with enriched metadata for LLM agents |
| POST | /v1/discover/batch | Batch discover across multiple queries with deduplication |
| GET | /v1/categories/{slug} | Browse datasets by category (supports graph sorting) |
| Method | Path | Description |
|---|---|---|
| GET | /v1/graph/datasets/{provider}/{dataset}/stats | Graph statistics for a dataset (importance, bridge, community) |
| GET | /v1/graph/datasets/{provider}/{dataset}/join-paths | Multi-hop join paths from a dataset |
| GET | /v1/graph/datasets/{provider}/{dataset}/related | Graph-powered related datasets (structural + semantic) |
| GET | /v1/graph/datasets/{provider}/{dataset}/neighbors | Direct 1-hop connections (filterable by edge type) |
| GET | /v1/graph/datasets/{provider}/{dataset}/schema-graph | Schema-level subgraph for D3 visualization |
| GET | /v1/graph/communities | List communities with top datasets and dominant topics |
| GET | /v1/graph/communities/{community_id}/datasets | List datasets in a community by importance |
| GET | /v1/graph/bridges | Top bridge datasets by betweenness centrality |
| GET | /v1/graph/subgraph | Seeded subgraph for graph explorer |
| GET | /v1/graph/entities/{type}/{id}/datasets | Datasets referencing a specific entity |
| GET | /v1/graph/health | Graph health and sync status |
Some datasets contain multiple tables (e.g., multi-sheet Excel workbooks, BLS series groups). For these:
GET /v1/datasets/{provider}/{dataset} returns data for the default subdataset, or lists available subdatasetsGET /v1/datasets/{provider}/{dataset}/{subdataset} queries a specific subdatasetIf you get a SUBDATASET_NOT_FOUND error, the dataset likely has subdatasets. Check the error response’s suggestions field - it includes a link to browse available subdatasets. Any unrecognized path segment after the dataset slug is interpreted as a subdataset name, which is why paths like /query or /search appended to a dataset path produce this error.
| Parameter | Example | Description | Reference |
|---|---|---|---|
filter[col] | filter[year]=2024 | Filter rows by column value | filtering.md (opens in a new tab) |
filter[col][op] | filter[year][gte]=2020 | Filter with operator | filtering.md (opens in a new tab) |
sort | sort=-year | Sort by column (prefix - for desc) | pagination-and-sort.md (opens in a new tab) |
limit | limit=50 | Max rows to return (1-1000, default 100) |
Use filter[col]=val, not ?col=val. Bare column names as query params are silently ignored. The API returns a structured warning, but you still get unfiltered data back.
# Wrong - returns ALL rows, with a warning
curl '.../nces/naep?year=2024'
# Right
curl '.../nces/naep?filter[year]=2024'URL-encode brackets in curl. Some shells interpret [ and ]. Use %5B / %5D or quote the URL.
curl 'https://api.tryopendata.ai/v1/datasets/nces/naep?filter%5Byear%5D=2024'Check warnings in the response. Unknown parameters produce structured QueryWarning objects with code, message, and param. The X-OpenData-Warnings HTTP header also carries these for piped workflows.
Use ?debug=true to see generated SQL. Returns a debug object with debug.query (echo of your parameters) and debug.sql (the DuckDB SQL that ran). Useful for verifying filters and sorts are applied correctly.
aggregate and nest_fields are mutually exclusive. You get a 400 error if you combine them. Aggregation produces flat summary rows; nesting produces grouped hierarchical data.
If a SQL query returns an error, check the error response body for details. Common causes: invalid column names (verify with GET .../columns), syntax issues, or timeout on very large datasets. For simple aggregations that don’t need SQL features (window functions, CTEs, joins), the REST aggregate + group_by params are an alternative.
Sorting on computed aggregation columns works. When using aggregate + group_by, you can sort on the computed column names (e.g., sort=-count_event_id for aggregate=count(event_id)). Invalid sort fields return a 400 with valid_values showing available options.
Always use api.tryopendata.ai for POST endpoints. The frontend at tryopendata.ai/api/ proxies GET requests only. POST requests to tryopendata.ai/api/v1/query return 405. Use api.tryopendata.ai/v1/query directly for SQL and cross-dataset queries.
Set a User-Agent header in API requests. Some CDN/WAF configurations may block requests with missing or generic user agents. Include a descriptive identifier:
curl -H "User-Agent: claude-code/opendata-skill" \
-H "Authorization: Bearer ${OPENDATA_API_KEY}" \
"https://api.tryopendata.ai/v1/datasets/fred/cpi?limit=5"The POST /v1/datasets/{provider}/{dataset}/query endpoint accepts raw SQL and executes it against the dataset. Requires authentication (API key or session). The dataset table is available as data or "provider/dataset". SQL is validated against an allowlist (SELECT only, no DDL/DML/IO) and runs with resource limits (5s timeout, 10k rows, 512MB memory).
Parameterized queries: Use ? placeholders with a params array to avoid string quoting issues:
{
"sql": "SELECT * FROM data WHERE country IN (?, ?) AND year >= ?",
"params": ["United States", "Japan", 2020]
}This eliminates the triple-nested escaping problem (SQL quotes inside JSON inside shell). See sql-query.md (opens in a new tab) for details.
The compose endpoints let you join two datasets and preview or download the result without writing SQL. Useful for enriching a dataset with columns from a related one (e.g., joining county-level education data with census demographics).
Workflow: Call /joinable to discover what can be joined, /compose/preview to check the result, then /compose/download.csv to export. See composition.md (opens in a new tab) for full details.
Composite keys: source_column and join_column accept arrays for multi-column joins. Both arrays must have the same length.
# 1. What can this dataset join with?
curl 'https://api.tryopendata.ai/v1/datasets/nces/naep/joinable'
# 2. Preview the join (anonymous: 100 rows, authenticated: 5000 rows)
curl -X POST 'https://api.tryopendata.ai/v1/datasets/nces/naep/compose/preview' \
-H 'Content-Type: application/json' \
-d '{"joins": [{"target": "census/saipe", "source_column": "jurisdiction_name", "join_column": "name"}]}'
# 2b. Composite key join (match on multiple columns)
curl -X POST 'https://api.tryopendata.ai/v1/datasets/nces/naep/compose/preview'
The GET /v1/search endpoint supports three modes:
keyword: Traditional full-text search with tsvector matching. Supports Google-style query syntax: quotes for phrases, - to exclude, OR for alternatives.semantic: Embedding-based similarity search for conceptual matching (e.g., “inflation data” finds CPI datasets).hybrid (default): Combines both using Reciprocal Rank Fusion (RRF). Best for most queries.Sort options: relevance (default), recency, name, popularity (stars), trending (time-decayed activity), queries, downloads.
Filters: provider, format, category, status (defaults to “ready”).
Time ranges (for trending/queries/downloads sort): today, week, month, year, all_time.
Autocomplete: GET /v1/search/suggest?q=con returns dataset names matching the prefix for typeahead.
All search results include graph intelligence fields (importance, bridge_score, community_id, community_label, graph_available). Graph scores contribute to search ranking via a multiplicative boost.
View results: Search may return dataset views alongside regular datasets. View results have result_type: "view", a view_name field, and a parent_ref linking to the parent dataset. Query views using colon syntax: FROM "provider/dataset:view_name".
The GET /v1/datasets/{provider}/{dataset}/meta/enriched endpoint returns AI-enriched metadata including:
The GET /v1/datasets/{provider}/{dataset}/chart endpoint returns pre-aggregated chart data optimized for each dataset shape:
| Shape | Response key | Payload |
|---|---|---|
timeseries | series | {date, value}[] with auto-downsampling when >500 points |
panel | panel | Top-5 entities, each with {date, value}[] series |
categorical | buckets | Top-20 {label, count}[] |
geo | regions | {region: value} map using latest time period |
Downsampling (timeseries only): When raw data exceeds 500 points, the endpoint auto-buckets via date_trunc at the finest granularity that fits (week/month/quarter/year). Response includes downsampled: true, granularity, aggregation (“avg” or “count”), and raw_count. Returns 404 for tabular/text shapes.
The GET /v1/datasets/{provider}/{dataset}/activity endpoint returns recent system events (enrichment, ingestion, schema changes) in reverse chronological order. Accepts ?limit= (1-50, default 20).
Datasets are connected in a knowledge graph (Neo4j). Graph algorithms (PageRank, betweenness centrality, Leiden community detection) produce scores that surface in search rankings, dataset metadata, and related datasets.
On dataset metadata: Pass ?include_graph=true to /meta to get a graph block with importance, bridge_score, and community info.
Dataset-specific graph endpoints live under /v1/graph/datasets/{provider}/{dataset}/:
stats - Graph-computed statistics (importance, bridge score, community, connection count)join-paths - Multi-hop join paths with configurable max_hops (1-3), min_confidence, and limitrelated - Blended structural + semantic related datasetsneighbors - Direct 1-hop connections, filterable by edge_types (comma-separated, e.g., SIMILAR_TO,BELONGS_TO)schema-graph - Schema-level subgraph for D3 visualization with configurable depth (1-3)Global graph endpoints live under /v1/graph/:
communities - List communities with top datasets and dominant topicscommunities/{id}/datasets - Datasets in a community, sorted by importancebridges - Top bridge datasets by betweenness centralitysubgraph - Seeded subgraph for graph explorer (accepts seed_type, seed_id, depth, limit). Dataset seeds use provider/slug format.entities/{type}/{id}/datasets - Datasets referencing a specific entityhealth - Graph connection status and sync infoAll graph endpoints return 503 when Neo4j is unavailable. See graph.md (opens in a new tab) for details.
The GET /v1/discover endpoint returns datasets matching a natural language query, enriched with metadata tailored for LLM agents and programmatic integrations. Results include column schemas (with units, value ranges, display names), available views, canonical questions, methodology summaries, sample rows, and relevance scores. Unlike /v1/search, discover is authenticated and optimized for machine consumption rather than human browsing.
Batch discover: POST /v1/discover/batch accepts multiple queries in one call, deduplicates results, and returns per-query dataset references alongside the full metadata. See discover.md (opens in a new tab) for details.
| File | When to load |
|---|---|
| references/filtering.md (opens in a new tab) | Writing filter expressions, checking operator syntax |
| references/aggregation.md (opens in a new tab) | Using group_by, aggregate functions, summary queries |
| references/pagination-and-sort.md (opens in a new tab) | Paginating large results, sorting, cursor-based pagination |
| references/column-introspection.md |
Query the OpenData API for data research and analysis. Use when fetching dataset rows, filtering, sorting, aggregating, inspecting columns, composing cross-dataset joins, exploring graph intelligence, or building data pipelines against OpenData endpoints.
The verbatim description from this skill’s front matter — the string an agent matches on to decide whether to load it.
main, last pushed 25 July 2026.SKILL.md, not by matching a directory convention. 3 distinct layouts observed: plugins/openchart/skills/*/SKILL.md, plugins/opendata/skills/*/SKILL.md, plugins/opendesign/skills/*/SKILL.md.h1 and no skipped levels:.claude-plugin/marketplace.json by OpenData, declaring 3 plugins. It is read for editorial metadata only — never as the skill index, which is always the repository tree.| pagination-and-sort.md (opens in a new tab) |
offset | offset=100 | Skip N rows | pagination-and-sort.md (opens in a new tab) |
cursor | cursor=... | Keyset pagination token | pagination-and-sort.md (opens in a new tab) |
fields | fields=year,score | Column projection | output-formats.md (opens in a new tab) |
format | format=csv | Output format (json, csv, tsv, xlsx) | output-formats.md (opens in a new tab) |
aggregate | aggregate=avg(score) | Aggregate functions | aggregation.md (opens in a new tab) |
group_by | group_by=year | Group rows by column | aggregation.md (opens in a new tab) |
view | view=enriched | Apply a named view (for SQL, prefer colon syntax: FROM "bls/cpi-u:enriched") | sql-query.md (opens in a new tab) |
expand | expand=area | Expand joined dimensions inline |
include_sources | include_sources=true | Show _source_url, _source_page columns |
response_format | response_format=columnar | Response shape: objects (default) or columnar (compact) | output-formats.md (opens in a new tab) |
include_graph | include_graph=true | Attach graph scores to /meta response | graph.md (opens in a new tab) |
debug | debug=true | Include generated SQL and query echo |
| Discovering schema, column types, value distributions |
| references/output-formats.md (opens in a new tab) | Exporting CSV/TSV/XLSX, field projection, system columns |
| references/common-patterns.md (opens in a new tab) | Recipes for exploratory analysis and data research |
| references/sql-query.md (opens in a new tab) | Raw SQL query endpoint, allowed functions, security model |
| references/discover.md (opens in a new tab) | Using the discover endpoint, LLM agent integration, dataset discovery |
| references/composition.md (opens in a new tab) | Cross-dataset joins: joinable, preview, CSV download |
| references/graph.md (opens in a new tab) | Graph intelligence: communities, importance, bridge scores |
/tryopendata/skills.md.md10 files · 64 KB
Everything this skill ships beside its prose. All of it is set here, as subchapters of skill 2.
Documentation the agent loads on demand, rather than up front.