# Census Trade Scraper (`quarterly_jingo/census-trade-scraper`) Actor

- **URL**: https://apify.com/quarterly\_jingo/census-trade-scraper.md
- **Developed by:** [Petey Boy](https://apify.com/quarterly_jingo) (community)
- **Categories:** Lead generation, Automation, Developer tools
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

Pay per usage

This Actor is paid per platform usage. The Actor is free to use, and you only pay for the Apify platform usage, which gets cheaper the higher subscription plan you have.

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

## 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 International Trade Data Scraper

Extract US import and export trade data from the official Census Bureau International Trade API. Get trade values, quantities, and commodity descriptions by HS code, country, and port.

### Features

- **Import & Export Data**: Query US imports, exports, or both
- **Multiple Data Levels**: By HS code, port, NAICS industry, or end-use category
- **Flexible Filtering**: Filter by commodity (HS code), country, port, date range
- **Quantity Data**: Includes quantities and units of measure
- **Date Ranges**: Query single months or multi-month ranges (2013-present)
- **No API Key Required**: Works without authentication (key optional for higher limits)

### Data Available

| Field | Description |
|-------|-------------|
| `tradeType` | "import" or "export" |
| `time` | Month (YYYY-MM format) |
| `commodityCode` | HS code (2, 4, 6, or 10 digits) |
| `commodityDescription` | Human-readable commodity name |
| `countryName` | Trading partner country |
| `countryCode` | Census country code |
| `tradeValueMonthly` | Trade value in USD for the month |
| `tradeValueYTD` | Year-to-date trade value (optional) |
| `quantity` | Quantity traded |
| `unit` | Unit of measure (e.g., NO, KG, LTR) |
| `portCode` | Port district code (if port-level) |
| `portName` | Port name (if port-level) |

### Input Examples

#### All US-China trade in vehicles (HS 87) for 2024

```json
{
  "tradeType": "both",
  "hsCode": "87",
  "countryCode": "5700",
  "startMonth": "2024-01",
  "endMonth": "2024-12",
  "aggregationLevel": "HS4"
}
```

#### Semiconductor imports by port

```json
{
  "tradeType": "imports",
  "dataLevel": "porths",
  "hsCode": "8542",
  "startMonth": "2024-06"
}
```

#### All exports to Mexico, broad categories

```json
{
  "tradeType": "exports",
  "countryCode": "2010",
  "startMonth": "2024-01",
  "aggregationLevel": "HS2"
}
```

### Common Country Codes

| Code | Country |
|------|---------|
| 5700 | China |
| 2010 | Mexico |
| 1220 | Canada |
| 5880 | Japan |
| 4280 | Germany |
| 4120 | United Kingdom |
| 5830 | South Korea |
| 5330 | India |

### Common HS Codes

| Code | Category |
|------|----------|
| 84 | Machinery, mechanical appliances |
| 85 | Electrical machinery, equipment |
| 87 | Vehicles |
| 27 | Mineral fuels, oils |
| 90 | Optical, medical instruments |
| 8471 | Computers |
| 8542 | Integrated circuits |
| 8703 | Motor cars |
| 2709 | Crude petroleum |

### API Information

- **Source**: US Census Bureau International Trade API
- **Data Range**: Monthly from 2013-present
- **Update Frequency**: Monthly (approximately 6-week lag)
- **Documentation**: https://www.census.gov/data/developers/data-sets/international-trade.html

### Output

Results are saved to the default dataset. Each record includes:

- Trade type (import/export)
- Time period
- Commodity code and description
- Country information
- Trade value in USD
- Quantity and unit (if available)
- Port information (if port-level query)

### Notes

- Large queries may be limited by the API. Use filters to narrow results.
- API key is optional but recommended for heavy usage.
- Get a free API key at: https://api.census.gov/data/key\_signup.html

# Actor input Schema

## `tradeType` (type: `string`):

Type of trade data to retrieve

## `dataLevel` (type: `string`):

Level of detail for trade data

## `hsCode` (type: `string`):

Harmonized System code to filter by (2, 4, 6, or 10 digits). Leave empty for all commodities. Examples: 87 (vehicles), 8703 (motor cars), 870310 (snow vehicles)

## `countryCode` (type: `string`):

Census country code (e.g., 5700=China, 2010=Mexico, 1220=Canada). Leave empty for all countries or 'TOTAL'.

## `portCode` (type: `string`):

2-digit port district code. Only used with 'By Port & HS Code' level. Leave empty for all ports.

## `startMonth` (type: `string`):

Start of date range (YYYY-MM format, e.g., 2023-01). Data available from 2013-01.

## `endMonth` (type: `string`):

End of date range (YYYY-MM format). Leave empty for single month.

## `aggregationLevel` (type: `string`):

Level of commodity detail (HS2=broad categories, HS10=most detailed)

## `includeQuantity` (type: `boolean`):

Include quantity and unit of measure in output

## `includeYearToDate` (type: `boolean`):

Include cumulative year-to-date values

## `maxRecords` (type: `integer`):

Maximum records to return (0 = unlimited). API may limit large queries.

## `apiKey` (type: `string`):

Optional Census API key for higher rate limits (get free at api.census.gov/data/key\_signup.html)

## Actor input object example

```json
{
  "tradeType": "both",
  "dataLevel": "hs",
  "hsCode": "8703",
  "countryCode": "5700",
  "startMonth": "2024-01",
  "aggregationLevel": "HS4",
  "includeQuantity": true,
  "includeYearToDate": false,
  "maxRecords": 10
}
```

# 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 = {};

// Run the Actor and wait for it to finish
const run = await client.actor("quarterly_jingo/census-trade-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 = {}

# Run the Actor and wait for it to finish
run = client.actor("quarterly_jingo/census-trade-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 '{}' |
apify call quarterly_jingo/census-trade-scraper --silent --output-dataset

```

## MCP server setup

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

```

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/C0wiVZq8ZJrKbanpU/builds/5sLiC54pjVbnSGv8I/openapi.json
