# UN Comtrade International Trade Statistics Scraper (`parseforge/un-comtrade-scraper`) Actor

Scrape the United Nations Comtrade free preview API for international trade flows. Pull imports, exports, re-imports and re-exports between reporters and partners by HS commodity code and year, including value, quantity, net weight, gross weight and customs procedure.

- **URL**: https://apify.com/parseforge/un-comtrade-scraper.md
- **Developed by:** [ParseForge](https://apify.com/parseforge) (community)
- **Categories:** Business, Education, Automation
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, NaN bookmarks
- **User rating**: No ratings yet

## Pricing

from $28.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.
Since this Actor supports Apify Store discounts, the price gets lower the higher subscription plan you have.

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

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

![ParseForge Banner](https://github.com/ParseForge/apify-assets/blob/main/banners/banner-default.jpg?raw=true)

## 🌐 UN Comtrade International Trade Statistics Scraper

> 🚀 **Export bilateral trade flows in seconds.** Pull imports, exports, re-imports and re-exports between **200+ reporting countries and partners**, by HS commodity code and year. Includes CIF and FOB values, quantities, net and gross weights. No sign-up needed.

> 🕒 **Last updated:** 2026-05-15 · **📊 47 fields** per record · **🌐 200+ countries** · **🧾 5,000+ HS commodity codes** · **📅 1962-present**

The **UN Comtrade Scraper** pulls from the official United Nations Comtrade source, the world's most comprehensive bilateral merchandise trade database. Every record carries **47 fields**, including reporter and partner identifiers (UN M49 codes plus ISO 3166-1 alpha-3), commodity codes across every HS revision (HS 1988 through HS 2022), customs procedure, mode of transport, and a complete suite of value and quantity measures (CIF, FOB, primary value, net weight, gross weight, alternate quantity).

Coverage spans **200+ reporter countries**, every UN partner economy, **all four flow directions** (Imports, Exports, Re-imports, Re-exports), and **8 HS classification revisions**. Annual data goes back to 1962 for many reporters. Choose any commodity (TOTAL aggregate or specific 2- or 6-digit HS code), specify the year, optionally restrict to a single partner, and download the result as CSV, Excel, JSON, or XML in under three minutes.

| 🎯 Target Audience | 💡 Primary Use Cases |
|---|---|
| Trade economists, supply chain analysts, customs and policy researchers, ESG teams, journalists, market researchers, academic institutions | Bilateral trade balances, import/export volume tracking, commodity sourcing analysis, sanctions monitoring, tariff impact studies, trade-flow visualisations |

---

### 📋 What the UN Comtrade Scraper does

Eleven filtering inputs combine in a single run:

- 🏳️ **Reporter filter.** Pick any UN M49 country code (842 = USA, 156 = China, 276 = Germany, 392 = Japan, 826 = United Kingdom, 250 = France) or pull a multi-reporter comparison.
- 🤝 **Partner filter.** Restrict to a single trading partner, leave empty for every partner row, or chain a second partner code for 3-way trade analysis.
- 📦 **Commodity filter.** TOTAL aggregate, broad chapters (27 = mineral fuels, 84 = machinery, 85 = electrical machinery, 87 = vehicles), or specific 6-digit HS codes.
- 🔄 **Flow direction.** Imports, Exports, Re-imports, Re-exports.
- 📅 **Period.** Single year or comma-separated list across multiple years.
- 🧾 **Classification revision.** HS current, plus HS 2022, 2017, 2012, 2007, 2002, 1996, 1988 for time-series consistency.
- 🚚 **Customs procedure and mode of transport.** Drill down to specific clearance regimes or transport modes.
- 📐 **Aggregation control.** Roll up rows by named dimensions or keep the raw breakdown.

Each record returns reporter and partner ISO codes, descriptive labels, commodity description, CIF and FOB values, primary value, net and gross weights, quantities with their unit of measure, estimation flags, and a deep link back to the official Comtrade trade-flow viewer.

> 💡 **Why it matters:** bilateral trade data underpins every supply-chain risk model, sanctions impact study, and country-level export competitiveness analysis. Building this pipeline yourself means handling complex paging, M49-to-ISO joins, dimension labelling, and multi-classification reconciliation. This Actor handles it all and keeps your dataset fresh on every run.

---

### 🎬 Full Demo

_🚧 Coming soon: a 3-minute walkthrough showing how to go from sign-up to a downloaded bilateral trade dataset._

---

### ⚙️ Input

<table>
<thead>
<tr><th>Input</th><th>Type</th><th>Default</th><th>Behavior</th></tr>
</thead>
<tbody>
<tr><td><code>maxItems</code></td><td>integer</td><td><code>10</code></td><td>Records to return. Free plan caps at 10, paid plan at 1,000,000.</td></tr>
<tr><td><code>reporterCode</code></td><td>string</td><td><code>"842"</code></td><td>UN M49 reporter code. Comma-separate for multiple reporters.</td></tr>
<tr><td><code>partnerCode</code></td><td>string</td><td><code>""</code></td><td>UN M49 partner code. Empty = every partner row, "0" = World aggregate.</td></tr>
<tr><td><code>partner2Code</code></td><td>string</td><td><code>""</code></td><td>Second partner code for 3-way trade analysis.</td></tr>
<tr><td><code>period</code></td><td>string</td><td><code>"2023"</code></td><td>Year or comma-separated years.</td></tr>
<tr><td><code>cmdCode</code></td><td>string</td><td><code>"TOTAL"</code></td><td>HS commodity code. TOTAL = all commodities, or any 2- or 6-digit HS code.</td></tr>
<tr><td><code>clCode</code></td><td>string</td><td><code>"HS"</code></td><td>HS classification revision (HS, H6, H5, H4, H3, H2, H1, H0).</td></tr>
<tr><td><code>flowCode</code></td><td>string</td><td><code>"M"</code></td><td>M = imports, X = exports, RM = re-imports, RX = re-exports.</td></tr>
<tr><td><code>customsCode</code></td><td>string</td><td><code>"C00"</code></td><td>Customs procedure. C00 = all procedures.</td></tr>
<tr><td><code>motCode</code></td><td>string</td><td><code>"0"</code></td><td>Mode of transport. 0 = all modes.</td></tr>
<tr><td><code>aggregateBy</code></td><td>string</td><td><code>""</code></td><td>Comma-separated dimension names to aggregate by, or empty for raw rows.</td></tr>
</tbody>
</table>

**Example: Germany imports from every partner in 2023, all commodities.**

```json
{
    "maxItems": 200,
    "reporterCode": "276",
    "partnerCode": "",
    "period": "2023",
    "cmdCode": "TOTAL",
    "flowCode": "M"
}
````

**Example: USA vehicle exports (HS chapter 87) to Mexico across three years.**

```json
{
    "maxItems": 100,
    "reporterCode": "842",
    "partnerCode": "484",
    "period": "2021,2022,2023",
    "cmdCode": "87",
    "flowCode": "X"
}
```

> ⚠️ **Good to Know:** UN Comtrade's preview tier returns up to 500 rows per query. For very large multi-country, multi-year pulls, split your request into smaller, well-scoped runs. Some smaller reporting economies have data lags of 6 to 12 months. Re-export and re-import flows are not reported by every country.

***

### 📊 Output

Each trade-flow record contains **47 fields**. Download the dataset as CSV, Excel, JSON, or XML.

#### 🧾 Schema

| Field | Type | Example |
|---|---|---|
| 🆔 `period` | number | `2023` |
| 📅 `refYear` | number | `2023` |
| 🏳️ `reporterCode` | number | `842` |
| 🏳️ `reporterISO` | string | `"USA"` |
| 🏷️ `reporterDesc` | string | `"USA"` |
| 🔄 `flowCode` | string | `"M"` |
| 🔄 `flowDesc` | string | `"Import"` |
| 🤝 `partnerCode` | number | `156` |
| 🤝 `partnerISO` | string | `"CHN"` |
| 🏷️ `partnerDesc` | string | `"China"` |
| 📦 `cmdCode` | string | `"TOTAL"` |
| 📦 `cmdDesc` | string | null | `"All Commodities"` |
| 🚚 `customsCode` | string | `"C00"` |
| 🚛 `motCode` | string | `"0"` |
| 💰 `cifvalue` | number | null | `426885050000` |
| 💵 `fobvalue` | number | null | `null` |
| 💲 `primaryValue` | number | null | `426885050000` |
| ⚖️ `netWgt` | number | null | `12345678` |
| ⚖️ `grossWgt` | number | null | `null` |
| 🧮 `qty` | number | null | `null` |
| 🔗 `url` | string | `"https://comtradeplus.un.org/TradeFlow?..."` |
| 🕒 `scrapedAt` | ISO 8601 | `"2026-05-15T00:00:00.000Z"` |

(Plus 25 more fields covering classification metadata, alternate quantities, weight estimation flags, and second-partner data.)

#### 📦 Sample record

<details>
<summary><strong>📥 USA imports from China, all commodities, 2023</strong></summary>

```json
{
    "period": 2023,
    "refYear": 2023,
    "reporterCode": 842,
    "reporterISO": "USA",
    "reporterDesc": "USA",
    "flowCode": "M",
    "flowDesc": "Import",
    "partnerCode": 156,
    "partnerISO": "CHN",
    "partnerDesc": "China",
    "cmdCode": "TOTAL",
    "cmdDesc": "All Commodities",
    "customsCode": "C00",
    "motCode": "0",
    "cifvalue": 426885050000,
    "fobvalue": null,
    "primaryValue": 426885050000,
    "netWgt": null,
    "grossWgt": null,
    "qty": null,
    "url": "https://comtradeplus.un.org/TradeFlow?Reporter=842&Partner=156&Commodity=TOTAL&Period=2023&Flow=M",
    "scrapedAt": "2026-05-15T00:00:00.000Z"
}
```

</details>

***

### ✨ Why choose this Actor

| | Capability |
|---|---|
| 🌐 | **Global coverage.** 200+ reporting countries with data going back to 1962 for many reporters. |
| 🔄 | **All flow directions.** Imports, Exports, Re-imports, Re-exports in a single schema. |
| 🧾 | **8 classification revisions.** HS current plus every back-revision (HS 2022, 2017, 2012, 2007, 2002, 1996, 1988) for time-series consistency. |
| 🤝 | **3-way trade support.** Optional second partner code unlocks transit and triangular trade analysis. |
| 🏷️ | **Pre-joined ISO codes.** UN M49 numeric codes are mapped to ISO 3166-1 alpha-3 (USA, CHN, DEU, JPN) so joins to other datasets just work. |
| ⚡ | **Fast.** Hundreds of rows in seconds, multi-year pulls in under a minute. |
| 🚫 | **No authentication.** Pulls from a public preview tier. No login or registration needed. |

> 📊 Bilateral trade data is the foundation of every customs intelligence platform, supply-chain risk model, and country-level export competitiveness benchmark.

***

### 📈 How it compares to alternatives

| Approach | Cost | Coverage | Refresh | Filters | Setup |
|---|---|---|---|---|---|
| **⭐ UN Comtrade Scraper** *(this Actor)* | $5 free credit, then pay-per-use | **200+ reporters, 1962-present** | **Live per run** | reporter, partner, commodity, flow, year, classification | ⚡ 2 min |
| Official trade-data portals | Free | Country-by-country | Quarterly | Web form only | 🐢 Hours per query |
| Commercial trade-intelligence platforms | $5,000+/year | Global | Weekly | Many | ⏳ Setup + license |
| Manual CSV downloads | Free | Limited per query | Manual | Few | 🕒 Hours of cleanup |

Pick this Actor when you need clean, structured bilateral trade data with full HS classification support and no licensing overhead.

***

### 🚀 How to use

1. 📝 **Sign up.** [Create a free account with $5 credit](https://console.apify.com/sign-up?fpr=vmoqkp) (takes 2 minutes).
2. 🌐 **Open the Actor.** Go to the UN Comtrade Scraper page on the Apify Store.
3. 🎯 **Set input.** Pick a reporter (842 = USA), commodity (TOTAL or a specific HS code), flow (M for imports), and year.
4. 🚀 **Run it.** Click **Start** and let the Actor collect your trade data.
5. 📥 **Download.** Grab your results in the **Dataset** tab as CSV, Excel, JSON, or XML.

> ⏱️ Total time from sign-up to downloaded dataset: **3-5 minutes.** No coding required.

***

### 💼 Business use cases

<table>
<tr>
<td width="50%" valign="top">

#### 📦 Supply Chain & Sourcing

- Track import volumes for a critical commodity over 5 years
- Identify alternate sourcing countries when a primary supplier is disrupted
- Benchmark unit costs across competing supplier countries
- Map dependency on single-country imports of strategic goods

</td>
<td width="50%" valign="top">

#### 📊 Trade Intelligence & Consulting

- Build bilateral trade balance dashboards for client briefings
- Detect tariff-driven trade diversion across HS chapters
- Track sanctions impact on commodity flows year-over-year
- Power export-opportunity scorecards for trade-promotion agencies

</td>
</tr>
<tr>
<td width="50%" valign="top">

#### 🏛️ Policy & Public Sector

- Monitor compliance with bilateral trade agreements
- Quantify export performance after tariff adjustments
- Track strategic-goods flows for export-control programs
- Inform trade negotiation positions with bilateral data

</td>
<td width="50%" valign="top">

#### 💼 Finance & ESG

- Macro-trade overlays for sovereign credit research
- Country-risk and supply-chain exposure scoring
- ESG due diligence on conflict-mineral and forced-labour sources
- Commodity-flow indicators feeding macro investment models

</td>
</tr>
</table>

***

### 🔌 Automating UN Comtrade Scraper

Control the scraper programmatically for scheduled runs and pipeline integrations:

- 🟢 **Node.js.** Install the `apify-client` NPM package.
- 🐍 **Python.** Use the `apify-client` PyPI package.
- 📚 See the [Apify documentation](https://docs.apify.com/api/v2) for full details.

The [Apify Schedules feature](https://docs.apify.com/platform/schedules) lets you trigger this Actor on any cron interval. Annual or quarterly refreshes keep downstream trade dashboards in sync automatically.

***

### 🌟 Beyond business use cases

Bilateral trade data powers more than commercial workflows. The same structured records support research, education, civic projects, and personal initiatives.

<table>
<tr>
<td width="50%">

#### 🎓 Research and academia

- Empirical trade economics papers and dissertations
- Cross-country panel datasets for econometrics courses
- Reproducible studies with cited, versioned dataset pulls
- Open-data exercises on globalisation and trade flows

</td>
<td width="50%">

#### 🎨 Personal and creative

- Data-journalism visualisations of import dependencies
- Personal portfolios with global trade-flow maps
- Sankey diagrams of bilateral commodity flows
- Hobbyist analyses of niche industries

</td>
</tr>
<tr>
<td width="50%">

#### 🤝 Non-profit and civic

- Investigative journalism on sanctions evasion and conflict commodities
- Civic transparency around national trade balances
- NGO research on resource-extraction supply chains
- OpenData community contributions

</td>
<td width="50%">

#### 🧪 Experimentation

- Train ML models on commodity-price-versus-flow relationships
- Validate trade-tech product hypotheses with real data
- Prototype agent pipelines that resolve HS commodity codes
- Test dashboard concepts with live bilateral trade feeds

</td>
</tr>
</table>

***

### 🤖 Ask an AI assistant about this scraper

Open a ready-to-send prompt about this ParseForge actor in the AI of your choice:

- 💬 [**ChatGPT**](https://chat.openai.com/?q=How%20do%20I%20use%20the%20UN%20Comtrade%20Scraper%20by%20ParseForge%20on%20Apify%3F%20Show%20me%20input%20examples%2C%20output%20fields%2C%20common%20use%20cases%2C%20and%20how%20to%20integrate%20it%20into%20a%20workflow.)
- 🧠 [**Claude**](https://claude.ai/new?q=How%20do%20I%20use%20the%20UN%20Comtrade%20Scraper%20by%20ParseForge%20on%20Apify%3F%20Show%20me%20input%20examples%2C%20output%20fields%2C%20common%20use%20cases%2C%20and%20how%20to%20integrate%20it%20into%20a%20workflow.)
- 🔍 [**Perplexity**](https://perplexity.ai/search?q=How%20do%20I%20use%20the%20UN%20Comtrade%20Scraper%20by%20ParseForge%20on%20Apify%3F%20Show%20me%20input%20examples%2C%20output%20fields%2C%20common%20use%20cases%2C%20and%20how%20to%20integrate%20it%20into%20a%20workflow.)
- 🅒 [**Copilot**](https://copilot.microsoft.com/?q=How%20do%20I%20use%20the%20UN%20Comtrade%20Scraper%20by%20ParseForge%20on%20Apify%3F%20Show%20me%20input%20examples%2C%20output%20fields%2C%20common%20use%20cases%2C%20and%20how%20to%20integrate%20it%20into%20a%20workflow.)

***

### ❓ Frequently Asked Questions

#### 🧩 How does it work?

Configure your reporter, partner, commodity, flow direction, and year filters in the input form, click Start, and the Actor pulls structured rows from the official UN Comtrade source. M49 numeric codes are mapped to ISO 3166-1 alpha-3 automatically so the rows are ready to join with any other country dataset.

#### 📏 How accurate is the data?

UN Comtrade is the global reference for bilateral merchandise trade. Records are reported by national customs authorities and may differ between reporter and partner (mirror discrepancy is a known characteristic of trade data). For very recent periods, expect reporting lags of 6 to 12 months for some economies.

#### 🔁 How often is the dataset refreshed?

The official Comtrade source updates as national authorities submit revisions. Every run of this Actor pulls live data, so your dataset reflects the current state at run time.

#### 📦 Which classification revisions are supported?

All 8: HS current, HS 2022 (H6), HS 2017 (H5), HS 2012 (H4), HS 2007 (H3), HS 2002 (H2), HS 1996 (H1), and HS 1988 (H0). Use back-revisions when building consistent long time series.

#### 🌍 Can I pull every partner row in one query?

Yes. Leave `partnerCode` empty and the Actor returns one row per partner, typically 100+ rows per reporter for a TOTAL commodity query.

#### 🔄 What's the difference between Imports, Exports, Re-imports, and Re-exports?

Imports (M) are foreign goods entering the reporter for domestic use. Exports (X) are domestic goods leaving the reporter. Re-imports (RM) are domestic goods returning unchanged after a temporary export. Re-exports (RX) are foreign goods leaving after entering the reporter. Not every country reports re-imports and re-exports.

#### ⏰ Can I schedule regular runs?

Yes. Use Apify Schedules to run this Actor on any cron interval (annual, quarterly, monthly) and keep downstream trade dashboards in sync.

#### ⚖️ Is this data legal to use?

UN Comtrade publishes under the United Nations data policy that permits public use, including commercial use, with attribution. Review the official terms for your specific use case.

#### 💳 Do I need a paid Apify plan to use this Actor?

No. The free Apify plan is enough for testing and small runs (10 records per run). A paid plan lifts the limit and gives you access to scheduling, higher concurrency, and larger datasets.

#### 🔁 What happens if a run fails or gets interrupted?

Apify automatically retries transient errors. If a run still fails, you can inspect the log in the Runs tab, fix the input, and re-run. Partial datasets from failed runs are preserved so you never lose progress.

#### 🆘 What if I need help?

Our support team is here to help. Contact us through the Apify platform or use the Tally form linked below.

***

### 🔌 Integrate with any app

UN Comtrade Scraper connects to any cloud service via [Apify integrations](https://apify.com/integrations):

- [**Make**](https://docs.apify.com/platform/integrations/make) - Automate multi-step workflows
- [**Zapier**](https://docs.apify.com/platform/integrations/zapier) - Connect with 5,000+ apps
- [**Slack**](https://docs.apify.com/platform/integrations/slack) - Get run notifications in your channels
- [**n8n**](https://docs.apify.com/platform/integrations/n8n) - Self-hosted automation pipelines
- [**Pipedream**](https://docs.apify.com/platform/integrations/pipedream) - Event-driven workflow automation
- [**Airbyte**](https://docs.apify.com/platform/integrations/airbyte) - Pipe trade data into your warehouse
- [**GitHub**](https://docs.apify.com/platform/integrations/github) - Trigger runs from commits and releases
- [**Google Drive**](https://docs.apify.com/platform/integrations/drive) - Export datasets straight to Sheets

You can also use webhooks to trigger downstream actions when a run finishes. Push fresh trade data into your product backend, or alert your team in Slack.

***

### 🔗 Recommended Actors

- [**📈 Indexmundi Scraper**](https://apify.com/parseforge/indexmundi-scraper) - Global demographic and economic indicators
- [**📊 World Bank Open Data Scraper**](https://apify.com/parseforge/world-bank-data-scraper) - Cross-country development indicators
- [**🌍 EIA Energy Scraper**](https://apify.com/parseforge/eia-energy-scraper) - U.S. and global energy statistics
- [**🛢️ OPEC Oil Data Scraper**](https://apify.com/parseforge/opec-oil-scraper) - Oil production and reserves data
- [**📜 USTR Tariff Scraper**](https://apify.com/parseforge/ustr-tariff-scraper) - U.S. trade representative tariff schedules

> 💡 **Pro Tip:** browse the complete [ParseForge collection](https://apify.com/parseforge) for more reference-data scrapers.

***

**🆘 Need Help?** [**Open our contact form**](https://tally.so/r/BzdKgA) to request a new scraper, propose a custom data project, or report an issue.

***

> **⚠️ Disclaimer:** this Actor is an independent tool and is not affiliated with, endorsed by, or sponsored by the United Nations or UN Comtrade. All trademarks mentioned are the property of their respective owners. Only publicly available open trade statistics are collected.

# Actor input Schema

## `reporterCode` (type: `string`):

UN M49 reporter code. 0 = World, 842 = USA, 156 = China, 276 = Germany, 392 = Japan, 826 = United Kingdom, 250 = France. Comma-separate to query multiple.

## `partnerCode` (type: `string`):

UN M49 partner code. Leave empty for all partners (returns one row per partner, ~100+ rows). Use 0 for the single World-aggregate row, 842 for USA, 156 for China, 276 for Germany. Comma-separate for multiple.

## `partner2Code` (type: `string`):

UN M49 code for second partner — used for 3-way trade analysis (e.g. Mexico exports to USA via Canada). Leave empty for none.

## `period` (type: `string`):

Year(s). Single year (2023) or comma-separated (2021,2022,2023).

## `cmdCode` (type: `string`):

HS commodity code. TOTAL = all commodities, 27 = Mineral fuels, 84 = Machinery, 85 = Electrical machinery, 87 = Vehicles. 2- or 6-digit. Comma-separate for multiple.

## `clCode` (type: `string`):

UN Comtrade commodity classification family. HS = current Harmonized System (default), H6/H5/H4/H3/H2/H1/H0 = HS revisions 2022/2017/2012/2007/2002/1996/1988.

## `flowCode` (type: `string`):

M = imports, X = exports, RM = re-imports, RX = re-exports.

## `customsCode` (type: `string`):

Customs code. C00 = TOTAL all customs procedures.

## `motCode` (type: `string`):

Mode of transport. 0 = TOTAL all modes.

## `aggregateBy` (type: `string`):

UN Comtrade aggregation setting (comma-separated dimension names, e.g. 'reporterCode,cmdCode'). Leave empty for raw rows.

## `maxItems` (type: `integer`):

Free users: Limited to 10 items (preview). Paid users: Optional, max 1,000,000

## Actor input object example

```json
{
  "reporterCode": "842",
  "partnerCode": "",
  "partner2Code": "",
  "period": "2023",
  "cmdCode": "TOTAL",
  "clCode": "HS",
  "flowCode": "M",
  "customsCode": "C00",
  "motCode": "0",
  "aggregateBy": "",
  "maxItems": 10
}
```

# Actor output Schema

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

Overview of scraped data

## `fullData` (type: `string`):

Complete dataset

# 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 = {
    "reporterCode": "842",
    "partnerCode": "",
    "partner2Code": "",
    "period": "2023",
    "cmdCode": "TOTAL",
    "clCode": "HS",
    "flowCode": "M",
    "customsCode": "C00",
    "motCode": "0",
    "aggregateBy": "",
    "maxItems": 10
};

// Run the Actor and wait for it to finish
const run = await client.actor("parseforge/un-comtrade-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 = {
    "reporterCode": "842",
    "partnerCode": "",
    "partner2Code": "",
    "period": "2023",
    "cmdCode": "TOTAL",
    "clCode": "HS",
    "flowCode": "M",
    "customsCode": "C00",
    "motCode": "0",
    "aggregateBy": "",
    "maxItems": 10,
}

# Run the Actor and wait for it to finish
run = client.actor("parseforge/un-comtrade-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 '{
  "reporterCode": "842",
  "partnerCode": "",
  "partner2Code": "",
  "period": "2023",
  "cmdCode": "TOTAL",
  "clCode": "HS",
  "flowCode": "M",
  "customsCode": "C00",
  "motCode": "0",
  "aggregateBy": "",
  "maxItems": 10
}' |
apify call parseforge/un-comtrade-scraper --silent --output-dataset

```

## MCP server setup

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

```

## OpenAPI specification

```json
{
    "openapi": "3.0.1",
    "info": {
        "title": "UN Comtrade International Trade Statistics Scraper",
        "description": "Scrape the United Nations Comtrade free preview API for international trade flows. Pull imports, exports, re-imports and re-exports between reporters and partners by HS commodity code and year, including value, quantity, net weight, gross weight and customs procedure.",
        "version": "0.0",
        "x-build-id": "fwMgW4mD9ul42HLG0"
    },
    "servers": [
        {
            "url": "https://api.apify.com/v2"
        }
    ],
    "paths": {
        "/acts/parseforge~un-comtrade-scraper/run-sync-get-dataset-items": {
            "post": {
                "operationId": "run-sync-get-dataset-items-parseforge-un-comtrade-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/parseforge~un-comtrade-scraper/runs": {
            "post": {
                "operationId": "runs-sync-parseforge-un-comtrade-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/parseforge~un-comtrade-scraper/run-sync": {
            "post": {
                "operationId": "run-sync-parseforge-un-comtrade-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",
                "properties": {
                    "reporterCode": {
                        "title": "Reporter code",
                        "type": "string",
                        "description": "UN M49 reporter code. 0 = World, 842 = USA, 156 = China, 276 = Germany, 392 = Japan, 826 = United Kingdom, 250 = France. Comma-separate to query multiple.",
                        "default": "842"
                    },
                    "partnerCode": {
                        "title": "Partner code",
                        "type": "string",
                        "description": "UN M49 partner code. Leave empty for all partners (returns one row per partner, ~100+ rows). Use 0 for the single World-aggregate row, 842 for USA, 156 for China, 276 for Germany. Comma-separate for multiple.",
                        "default": ""
                    },
                    "partner2Code": {
                        "title": "Second partner code (3-way trade)",
                        "type": "string",
                        "description": "UN M49 code for second partner — used for 3-way trade analysis (e.g. Mexico exports to USA via Canada). Leave empty for none.",
                        "default": ""
                    },
                    "period": {
                        "title": "Period",
                        "type": "string",
                        "description": "Year(s). Single year (2023) or comma-separated (2021,2022,2023).",
                        "default": "2023"
                    },
                    "cmdCode": {
                        "title": "Commodity code (HS)",
                        "type": "string",
                        "description": "HS commodity code. TOTAL = all commodities, 27 = Mineral fuels, 84 = Machinery, 85 = Electrical machinery, 87 = Vehicles. 2- or 6-digit. Comma-separate for multiple.",
                        "default": "TOTAL"
                    },
                    "clCode": {
                        "title": "Commodity classification",
                        "enum": [
                            "HS",
                            "H6",
                            "H5",
                            "H4",
                            "H3",
                            "H2",
                            "H1",
                            "H0"
                        ],
                        "type": "string",
                        "description": "UN Comtrade commodity classification family. HS = current Harmonized System (default), H6/H5/H4/H3/H2/H1/H0 = HS revisions 2022/2017/2012/2007/2002/1996/1988.",
                        "default": "HS"
                    },
                    "flowCode": {
                        "title": "Flow direction",
                        "enum": [
                            "M",
                            "X",
                            "RM",
                            "RX"
                        ],
                        "type": "string",
                        "description": "M = imports, X = exports, RM = re-imports, RX = re-exports.",
                        "default": "M"
                    },
                    "customsCode": {
                        "title": "Customs procedure code",
                        "type": "string",
                        "description": "Customs code. C00 = TOTAL all customs procedures.",
                        "default": "C00"
                    },
                    "motCode": {
                        "title": "Mode of transport",
                        "type": "string",
                        "description": "Mode of transport. 0 = TOTAL all modes.",
                        "default": "0"
                    },
                    "aggregateBy": {
                        "title": "Aggregate by",
                        "type": "string",
                        "description": "UN Comtrade aggregation setting (comma-separated dimension names, e.g. 'reporterCode,cmdCode'). Leave empty for raw rows.",
                        "default": ""
                    },
                    "maxItems": {
                        "title": "Max Items",
                        "minimum": 1,
                        "maximum": 1000000,
                        "type": "integer",
                        "description": "Free users: Limited to 10 items (preview). Paid users: Optional, max 1,000,000"
                    }
                }
            },
            "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
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
```
