# 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 a software tools running on the Apify platform, for all kinds of web data extraction and automation use cases.
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.

In JavaScript/TypeScript projects, use official [JavaScript/TypeScript client](https://docs.apify.com/api/client/js.md):

```bash
npm install apify-client
```

In Python projects, use official [Python client library](https://docs.apify.com/api/client/python.md):

```bash
pip install apify-client
```

In shell scripts, use [Apify CLI](https://docs.apify.com/cli/docs.md):

````bash
# MacOS / Linux
curl -fsSL https://apify.com/install-cli.sh | bash
# Windows
irm https://apify.com/install-cli.ps1 | iex
```bash

In AI frameworks, you might use the [Apify MCP server](https://docs.apify.com/platform/integrations/mcp.md).

If your project is in a different language, use 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

```json
{
    "openapi": "3.0.1",
    "info": {
        "title": "Census Trade Scraper",
        "description": "",
        "version": "1.0",
        "x-build-id": "5sLiC54pjVbnSGv8I"
    },
    "servers": [
        {
            "url": "https://api.apify.com/v2"
        }
    ],
    "paths": {
        "/acts/quarterly_jingo~census-trade-scraper/run-sync-get-dataset-items": {
            "post": {
                "operationId": "run-sync-get-dataset-items-quarterly_jingo-census-trade-scraper",
                "x-openai-isConsequential": false,
                "summary": "Executes an Actor, waits for its completion, and returns Actor's dataset items in response.",
                "tags": [
                    "Run Actor"
                ],
                "requestBody": {
                    "required": true,
                    "content": {
                        "application/json": {
                            "schema": {
                                "$ref": "#/components/schemas/inputSchema"
                            }
                        }
                    }
                },
                "parameters": [
                    {
                        "name": "token",
                        "in": "query",
                        "required": true,
                        "schema": {
                            "type": "string"
                        },
                        "description": "Enter your Apify token here"
                    }
                ],
                "responses": {
                    "200": {
                        "description": "OK"
                    }
                }
            }
        },
        "/acts/quarterly_jingo~census-trade-scraper/runs": {
            "post": {
                "operationId": "runs-sync-quarterly_jingo-census-trade-scraper",
                "x-openai-isConsequential": false,
                "summary": "Executes an Actor and returns information about the initiated run in response.",
                "tags": [
                    "Run Actor"
                ],
                "requestBody": {
                    "required": true,
                    "content": {
                        "application/json": {
                            "schema": {
                                "$ref": "#/components/schemas/inputSchema"
                            }
                        }
                    }
                },
                "parameters": [
                    {
                        "name": "token",
                        "in": "query",
                        "required": true,
                        "schema": {
                            "type": "string"
                        },
                        "description": "Enter your Apify token here"
                    }
                ],
                "responses": {
                    "200": {
                        "description": "OK",
                        "content": {
                            "application/json": {
                                "schema": {
                                    "$ref": "#/components/schemas/runsResponseSchema"
                                }
                            }
                        }
                    }
                }
            }
        },
        "/acts/quarterly_jingo~census-trade-scraper/run-sync": {
            "post": {
                "operationId": "run-sync-quarterly_jingo-census-trade-scraper",
                "x-openai-isConsequential": false,
                "summary": "Executes an Actor, waits for completion, and returns the OUTPUT from Key-value store in response.",
                "tags": [
                    "Run Actor"
                ],
                "requestBody": {
                    "required": true,
                    "content": {
                        "application/json": {
                            "schema": {
                                "$ref": "#/components/schemas/inputSchema"
                            }
                        }
                    }
                },
                "parameters": [
                    {
                        "name": "token",
                        "in": "query",
                        "required": true,
                        "schema": {
                            "type": "string"
                        },
                        "description": "Enter your Apify token here"
                    }
                ],
                "responses": {
                    "200": {
                        "description": "OK"
                    }
                }
            }
        }
    },
    "components": {
        "schemas": {
            "inputSchema": {
                "type": "object",
                "required": [
                    "startMonth"
                ],
                "properties": {
                    "tradeType": {
                        "title": "Trade Type",
                        "enum": [
                            "imports",
                            "exports",
                            "both"
                        ],
                        "type": "string",
                        "description": "Type of trade data to retrieve",
                        "default": "both"
                    },
                    "dataLevel": {
                        "title": "Data Level",
                        "enum": [
                            "hs",
                            "porths",
                            "naics",
                            "enduse"
                        ],
                        "type": "string",
                        "description": "Level of detail for trade data",
                        "default": "hs"
                    },
                    "hsCode": {
                        "title": "HS Code",
                        "type": "string",
                        "description": "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)",
                        "default": "8703"
                    },
                    "countryCode": {
                        "title": "Country Code",
                        "type": "string",
                        "description": "Census country code (e.g., 5700=China, 2010=Mexico, 1220=Canada). Leave empty for all countries or 'TOTAL'.",
                        "default": "5700"
                    },
                    "portCode": {
                        "title": "Port Code",
                        "type": "string",
                        "description": "2-digit port district code. Only used with 'By Port & HS Code' level. Leave empty for all ports."
                    },
                    "startMonth": {
                        "title": "Start Month",
                        "type": "string",
                        "description": "Start of date range (YYYY-MM format, e.g., 2023-01). Data available from 2013-01.",
                        "default": "2024-01"
                    },
                    "endMonth": {
                        "title": "End Month",
                        "type": "string",
                        "description": "End of date range (YYYY-MM format). Leave empty for single month."
                    },
                    "aggregationLevel": {
                        "title": "HS Aggregation Level",
                        "enum": [
                            "",
                            "HS2",
                            "HS4",
                            "HS6",
                            "HS10"
                        ],
                        "type": "string",
                        "description": "Level of commodity detail (HS2=broad categories, HS10=most detailed)",
                        "default": "HS4"
                    },
                    "includeQuantity": {
                        "title": "Include Quantity Data",
                        "type": "boolean",
                        "description": "Include quantity and unit of measure in output",
                        "default": true
                    },
                    "includeYearToDate": {
                        "title": "Include Year-to-Date",
                        "type": "boolean",
                        "description": "Include cumulative year-to-date values",
                        "default": false
                    },
                    "maxRecords": {
                        "title": "Max Records",
                        "type": "integer",
                        "description": "Maximum records to return (0 = unlimited). API may limit large queries.",
                        "default": 10
                    },
                    "apiKey": {
                        "title": "Census API Key",
                        "type": "string",
                        "description": "Optional Census API key for higher rate limits (get free at api.census.gov/data/key_signup.html)"
                    }
                }
            },
            "runsResponseSchema": {
                "type": "object",
                "properties": {
                    "data": {
                        "type": "object",
                        "properties": {
                            "id": {
                                "type": "string"
                            },
                            "actId": {
                                "type": "string"
                            },
                            "userId": {
                                "type": "string"
                            },
                            "startedAt": {
                                "type": "string",
                                "format": "date-time",
                                "example": "2025-01-08T00:00:00.000Z"
                            },
                            "finishedAt": {
                                "type": "string",
                                "format": "date-time",
                                "example": "2025-01-08T00:00:00.000Z"
                            },
                            "status": {
                                "type": "string",
                                "example": "READY"
                            },
                            "meta": {
                                "type": "object",
                                "properties": {
                                    "origin": {
                                        "type": "string",
                                        "example": "API"
                                    },
                                    "userAgent": {
                                        "type": "string"
                                    }
                                }
                            },
                            "stats": {
                                "type": "object",
                                "properties": {
                                    "inputBodyLen": {
                                        "type": "integer",
                                        "example": 2000
                                    },
                                    "rebootCount": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "restartCount": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "resurrectCount": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "computeUnits": {
                                        "type": "integer",
                                        "example": 0
                                    }
                                }
                            },
                            "options": {
                                "type": "object",
                                "properties": {
                                    "build": {
                                        "type": "string",
                                        "example": "latest"
                                    },
                                    "timeoutSecs": {
                                        "type": "integer",
                                        "example": 300
                                    },
                                    "memoryMbytes": {
                                        "type": "integer",
                                        "example": 1024
                                    },
                                    "diskMbytes": {
                                        "type": "integer",
                                        "example": 2048
                                    }
                                }
                            },
                            "buildId": {
                                "type": "string"
                            },
                            "defaultKeyValueStoreId": {
                                "type": "string"
                            },
                            "defaultDatasetId": {
                                "type": "string"
                            },
                            "defaultRequestQueueId": {
                                "type": "string"
                            },
                            "buildNumber": {
                                "type": "string",
                                "example": "1.0.0"
                            },
                            "containerUrl": {
                                "type": "string"
                            },
                            "usage": {
                                "type": "object",
                                "properties": {
                                    "ACTOR_COMPUTE_UNITS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATASET_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATASET_WRITES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "KEY_VALUE_STORE_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "KEY_VALUE_STORE_WRITES": {
                                        "type": "integer",
                                        "example": 1
                                    },
                                    "KEY_VALUE_STORE_LISTS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "REQUEST_QUEUE_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "REQUEST_QUEUE_WRITES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATA_TRANSFER_INTERNAL_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATA_TRANSFER_EXTERNAL_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "PROXY_RESIDENTIAL_TRANSFER_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "PROXY_SERPS": {
                                        "type": "integer",
                                        "example": 0
                                    }
                                }
                            },
                            "usageTotalUsd": {
                                "type": "number",
                                "example": 0.00005
                            },
                            "usageUsd": {
                                "type": "object",
                                "properties": {
                                    "ACTOR_COMPUTE_UNITS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATASET_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATASET_WRITES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "KEY_VALUE_STORE_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "KEY_VALUE_STORE_WRITES": {
                                        "type": "number",
                                        "example": 0.00005
                                    },
                                    "KEY_VALUE_STORE_LISTS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "REQUEST_QUEUE_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "REQUEST_QUEUE_WRITES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATA_TRANSFER_INTERNAL_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATA_TRANSFER_EXTERNAL_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "PROXY_RESIDENTIAL_TRANSFER_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "PROXY_SERPS": {
                                        "type": "integer",
                                        "example": 0
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
```
