# International Trade Statistics — UN Comtrade Imports & Exports (`dalbian/un-comtrade-trade-statistics`) Actor

Official import and export figures between any two countries, by commodity, by year: value in US dollars, quantity, net weight and the implied unit price. From UN Comtrade, the United Nations' trade database. Country and commodity names resolved for you.

- **URL**: https://apify.com/dalbian/un-comtrade-trade-statistics.md
- **Developed by:** [Benjamin Jerez](https://apify.com/dalbian) (community)
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $40.00 / 1,000 trade queries

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.

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

## What's an Apify Actor?

An Actor is a serverless cloud program that runs on the Apify platform. It has two run modes.
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.

Apify vocabulary and the platform model are defined once, in the agent quickstart at https://apify.com/agents.md.

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

Do not guess an integration path. Every one of them is in the agent quickstart at https://apify.com/agents.md: the Apify MCP server, Agent Skills with the Apify CLI, the JavaScript and Python clients, the REST API, and the account-free path for an agent with no human to sign in. It also carries the rule on stating cost before the first paid run.

For examples already wired to this Actor's own input schema, see the [API](#api) section below.

Each client library has reference documentation the quickstart does not restate: [JavaScript/TypeScript](https://docs.apify.com/api/client/js/docs.md) (`npm install apify-client`) and [Python](https://docs.apify.com/api/client/python/docs.md) (`pip install apify-client`).

# README

## International Trade Statistics — UN Comtrade Imports and Exports

Official customs figures for trade between any two countries, by commodity and by year: value in US dollars, quantity, net weight, and the unit price the two imply.

From **UN Comtrade**, the United Nations' trade database — the source national statistics offices, market researchers and trade economists all work from.

### What a query returns

US imports of passenger cars (HS 8703) from Germany and Japan:

| Year | Partner | Value | Units | Unit price |
| --- | --- | --- | --- | --- |
| 2021 | Japan | $33 390 640 672 | 1 353 572 | $24 669 |
| 2021 | Germany | $15 287 824 543 | 298 089 | $51 286 |
| 2022 | Japan | $33 524 672 675 | 1 309 665 | $25 598 |
| 2022 | Germany | $19 518 487 208 | 335 991 | $58 092 |
| 2023 | Japan | $40 876 679 872 | 1 465 999 | $27 883 |
| 2023 | Germany | $23 866 838 184 | 393 926 | $60 587 |

The unit price column is the point. Comtrade publishes value and quantity separately; dividing one by the other turns a trade figure into a market signal — a German car crossing into the US averaged $51 286 in 2021 and $60 587 two years later, while the Japanese average moved from $24 669 to $27 883.

Each row also carries CIF and FOB values where the reporter files both, net weight, price per kilogram, and flags marking any figure the UN estimated rather than received.

### Names instead of codes

Comtrade speaks in numbers. Its open endpoint returns `reporterDesc`, `partnerDesc` and `cmdDesc` as null on every single row, so a raw response is a wall of integers: country 842, partner 276, commodity 8703.

This Actor loads the UN's reference tables at the start of each run and joins the names back on. The same tables work in the other direction, so you can write what you mean:

- **Countries** — `United States`, `USA`, `US`, `Germany`, `DE`, `DEU` all resolve. The UN's own spelling is frequently not the obvious one: it calls the United States *USA*, South Korea *Rep. of Korea*, Russia *Russian Federation*, and Hong Kong *China, Hong Kong SAR*. Common names are mapped, and an unrecognised one is reported with an explanation rather than silently dropped.
- **Commodities** — an HS code (`8703`), or a word. `coffee` resolves to **0901**, *Coffee, whether or not roasted or decaffeinated*. A word search returns the four-digit heading rather than the two-digit chapter, because a chapter is usually far broader than intended — chapter 09 is "Coffee, tea, mate and spices", and would hand you tea.
- **`TOTAL`** gives all goods, and `World` as a partner gives the total across every partner at once.

Two digits is a chapter, four a heading, six a specific product. The resolved code and its full label are on the summary row, so you can always see what was actually queried.

### Years

The open Comtrade endpoint accepts exactly one year per request and answers a multi-year query with an error. Write `2019-2023` and the Actor issues one request per year and reassembles the series — which is why a long range takes proportionally longer.

### Who uses this

Importers and exporters sizing a market or checking what a corridor is worth. Market researchers and consultancies building country-by-product models. Supply-chain and procurement teams tracking where a component actually comes from. Commodity traders watching unit prices move. Economists, journalists and NGOs working on trade flows.

### What the numbers are, and are not

**They are the reporter's own customs figures.** Germany's exports to France and France's imports from Germany will not match. Both are correct: they are measured at different borders, on different valuations (exports FOB, imports CIF, so imports include freight and insurance), and recorded at different moments. Economists call the gap the mirror discrepancy, and it is expected rather than an error in the data.

**Recent years are incomplete.** Countries file months to years late, and some never file at all. An empty result for last year usually means nobody has reported yet, not that no trade occurred. The Actor says so on the summary row instead of returning a bare zero.

**Estimated figures are flagged.** `isNetWeightEstimated` and `isQuantityEstimated` mark values the UN derived rather than received. Net weight in particular is frequently estimated.

**The open endpoint returns at most 500 rows per query.** That is the UN's ceiling, not a setting here. Asking for one commodity across every partner will hit it on a large economy; naming the partners you care about, or using a four-digit code instead of a two-digit chapter, is how you stay under it. The summary row says plainly when a result was capped.

### Source and licence

**UN Comtrade**, through its public preview endpoint at `comtradeapi.un.org`. No key, no account. The service throttles, and the Actor waits and retries rather than dropping a year — a multi-year run will pause occasionally, which is normal and logged.

UN Comtrade data is made available by the United Nations Statistics Division for public use.

### Frequently asked

**Why did my country name not resolve?**
Because the UN spells it differently. Try the ISO code — `US`, `DE`, `JP` — which always works, or the numeric code. The error message names what went wrong rather than returning an empty run.

**Why do two rows have the same partner?**
Because they are different commodity codes. A chapter-level query returns each heading beneath it separately.

**Can I get monthly figures?**
Not from this endpoint. It serves annual data. Monthly series require a UN Comtrade subscription key.

**Why is quantity empty on some rows?**
Because the reporter filed a value but no quantity, which is common for aggregated codes and for commodities with no natural unit. `valueUsd` is still reliable; `unitValueUsd` is simply omitted rather than guessed.

**What is HS?**
The Harmonised System, the world's shared customs classification. Nearly every country codes its trade with it, which is what makes these figures comparable across borders at all.

# Actor input Schema

## `reporters` (type: `array`):

The countries whose customs figures you want, one per line. Names or ISO codes both work — United States, USA, Germany, DE. These are the countries doing the reporting, so the numbers are theirs.

## `partners` (type: `array`):

The countries traded with, one per line. Leave empty for every partner, or put World for the total across all of them.

## `commodities` (type: `array`):

HS codes or plain words, one per line. 8703 is passenger cars; writing coffee searches the commodity list and uses what it finds. TOTAL gives all goods. Two digits is a chapter, four a heading, six a specific product.

## `flows` (type: `array`):

Which direction to report. Imports and exports of the same pair rarely match exactly — see the README.

## `years` (type: `array`):

One per line, or a range such as 2019-2023. Each year is a separate request to Comtrade, so a long range takes proportionally longer.

## `maxRowsPerQuery` (type: `integer`):

The open Comtrade endpoint returns at most 500 rows per request. Narrow the commodity or the partner rather than raising this.

## Actor input object example

```json
{
  "reporters": [
    "United States"
  ],
  "commodities": [
    "8703"
  ],
  "flows": [
    "M"
  ],
  "years": [
    "2023"
  ],
  "maxRowsPerQuery": 500
}
```

# Actor output Schema

# 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 = {
    "reporters": [
        "United States"
    ],
    "commodities": [
        "8703"
    ],
    "years": [
        "2023"
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("dalbian/un-comtrade-trade-statistics").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 = {
    "reporters": ["United States"],
    "commodities": ["8703"],
    "years": ["2023"],
}

# Run the Actor and wait for it to finish
run = client.actor("dalbian/un-comtrade-trade-statistics").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print(f"💾 Check your data here: https://console.apify.com/storage/datasets/{run.default_dataset_id}")
for item in client.dataset(run.default_dataset_id).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{
  "reporters": [
    "United States"
  ],
  "commodities": [
    "8703"
  ],
  "years": [
    "2023"
  ]
}' |
apify call dalbian/un-comtrade-trade-statistics --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,dalbian/un-comtrade-trade-statistics"
        }
    }
}
```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/98enMcvCMdGtKAPXP/builds/bUoAKNLwetw87pBb6/openapi.json
