UN COMTRADE International Trade Data avatar

UN COMTRADE International Trade Data

Pricing

from $2.00 / 1,000 trade fetcheds

Go to Apify Store
UN COMTRADE International Trade Data

UN COMTRADE International Trade Data

Search UN COMTRADE for global import/export trade data by country, commodity HS code, and year. Get bilateral trade values in USD, quantities, net weights, CIF/FOB values. Supports 200+ countries with free preview or authenticated API.

Pricing

from $2.00 / 1,000 trade fetcheds

Rating

0.0

(0)

Developer

ryan clinton

ryan clinton

Maintained by Community

Actor stats

0

Bookmarked

5

Total users

3

Monthly active users

3 hours ago

Last modified

Share

UN COMTRADE International Trade Data is an Apify actor that queries the United Nations COMTRADE database -- the world's largest repository of bilateral merchandise trade statistics -- to retrieve detailed import and export records between over 200 countries and territories. The actor connects directly to the official UN COMTRADE API and returns structured, machine-readable trade data including trade values in USD, CIF and FOB valuations, net and gross weights, physical quantities, commodity descriptions classified by Harmonized System (HS) codes, and full reporter/partner country details. It supports both the free public preview endpoint (up to 500 records) and the authenticated endpoint for subscription key holders (up to 250,000 records), with smart country name resolution that accepts common names like "USA" or "China", ISO2/ISO3 codes, or raw UN M49 numeric codes.


Why use UN COMTRADE International Trade Data?

Accessing the UN COMTRADE database programmatically requires writing custom API integration code, resolving country identifiers to M49 numeric codes, handling authentication headers, parsing complex response structures, and managing the gap between the preview and authenticated endpoints. This actor eliminates all of that overhead. You configure a simple input form or JSON payload, run the actor, and receive clean, normalized trade data in your Apify dataset within seconds.

Running on Apify gives you scheduled recurring data pulls on daily, weekly, or monthly cadences to track trade flows over time. You can chain the output into other Apify actors, push results to Google Sheets or Slack, or trigger downstream pipelines via webhooks. The serverless execution model means zero infrastructure to maintain and you pay only for the compute you use. The actor also adds significant value over raw API access by automatically resolving human-readable country names to M49 codes, providing sensible defaults (such as selecting the most recent available data year), and transforming the raw API response into a clean output schema with clearly labeled fields.


Key features

  • Smart country resolution -- enter common country names (e.g., "USA", "UK", "China", "South Korea"), ISO2 codes ("US", "CN"), ISO3 codes ("GBR", "DEU"), or raw UN M49 numeric codes ("842"). The actor resolves them automatically from a built-in lookup table covering 40+ countries.
  • HS commodity code search -- filter trade data by specific Harmonized System codes (e.g., "2701" for coal, "0101" for live horses, "2709" for crude petroleum, "8703" for motor vehicles) or retrieve aggregate totals with "TOTAL".
  • Trade flow filtering -- narrow results to imports, exports, re-imports, re-exports, or retrieve all flow directions at once.
  • Multi-year queries -- specify a single year or comma-separated list of years (e.g., "2021,2022,2023") to pull historical data in one run.
  • Free and authenticated modes -- works out of the box with the free preview API (up to 500 records per query). Supply your own UN COMTRADE subscription key for up to 250,000 records per query.
  • Comprehensive trade metrics -- every record includes trade value (USD), CIF value, FOB value, net weight, gross weight, physical quantity with units, and metadata flags for reported vs. estimated data.
  • Automatic year defaults -- if no year is specified, the actor defaults to two years before the current date, which is typically the most recent fully available data period in COMTRADE due to the 1-2 year reporting lag.
  • Clean JSON output -- structured data exportable to JSON, CSV, Excel, or Google Sheets, or consumable via the Apify API.

How to use UN COMTRADE International Trade Data

  1. Open the actor on the Apify Console or call it via the API.
  2. Set the reporter country. Enter a country name like "USA", "Germany", or "Japan" in the Reporter Country field. Leave it empty to query all reporters.
  3. Set the partner country (optional). Enter a trading partner to filter bilateral trade (e.g., "China"). Leave empty to include all partners.
  4. Set the commodity code (optional). Enter an HS code like "2709" for crude petroleum or "8703" for motor vehicles. Leave empty for aggregate totals across all commodities.
  5. Choose the trade flow. Select Import, Export, Re-Import, Re-Export, or All.
  6. Set the year (optional). Enter a year like "2023" or comma-separated years like "2021,2022,2023". Leave empty for the most recent available data.
  7. Set max results. Control how many records are returned (default 100, up to 500 for free, up to 250,000 with a subscription key).
  8. Run the actor and download results from the Dataset tab in JSON, CSV, XML, or Excel format.

Input parameters

ParameterTypeRequiredDefaultDescription
reporterStringNoAll reportersReporting country name, ISO2/ISO3 code, or UN M49 numeric code (e.g., "USA", "DE", "GBR", "156").
partnerStringNoAll partnersPartner country name or code. Leave empty to include all trading partners.
commodityStringNoTOTALHS commodity code (e.g., "0101" for live horses, "2701" for coal, "2709" for crude petroleum). Leave empty for aggregate totals.
tradeFlowEnumNoAllTrade flow direction: Import, Export, Re-Import, Re-Export, or All.
yearStringNo2 years agoTrade year (e.g., "2023"). Comma-separated for multiple years (e.g., "2022,2023").
subscriptionKeyStringNo--UN COMTRADE API subscription key for higher limits (up to 250K records). Without a key, the free preview endpoint allows up to 500 records.
maxResultsIntegerNo100Maximum number of records to return (1--250,000). Limited to 500 without a subscription key.
{
"reporter": "USA",
"partner": "China",
"tradeFlow": "Import",
"year": "2023",
"maxResults": 100
}

Input example (specific commodity with multi-year)

{
"reporter": "Germany",
"commodity": "8703",
"tradeFlow": "Export",
"year": "2021,2022,2023",
"maxResults": 500
}

Input example (authenticated with subscription key)

{
"reporter": "Japan",
"partner": "USA",
"commodity": "8542",
"tradeFlow": "All",
"year": "2023",
"subscriptionKey": "your_comtrade_subscription_key_here",
"maxResults": 10000
}

Tips for best results

  • Start broad, then narrow. If you are unsure what data is available, start with a single reporter country and no partner or commodity filter. Review the results, then add filters in subsequent runs.
  • Use HS codes for precision. Commodity descriptions can be ambiguous. Use the specific HS code (e.g., "2709" for crude petroleum) rather than trying to match by name.
  • Check data availability. COMTRADE data typically has a 1-2 year lag. If you query the current year and get no results, try the previous year or two years back.
  • Multi-year analysis. Pass comma-separated years like "2020,2021,2022,2023" to pull multiple years in a single run for trend analysis.
  • Country name flexibility. You do not need to look up M49 codes manually. Common names like "USA", "UK", "China", "Germany", "South Korea" are all recognized and resolved automatically.
  • Use the subscription key for large datasets. The free preview endpoint caps at 500 records. If you need comprehensive bilateral data across many partners or commodities, obtain a subscription key from the UN COMTRADE portal.
  • Schedule regular runs. Use Apify scheduling to pull updated trade data on a weekly or monthly basis and track changes over time.

Output

Output example (aggregate totals)

Each record in the output dataset represents a single bilateral trade flow for a given reporter-partner-commodity-year combination:

{
"reporter": "United States of America",
"reporterISO": "USA",
"reporterCode": 842,
"partner": "China",
"partnerISO": "CHN",
"partnerCode": 156,
"commodity": "TOTAL - Total of all HS commodities",
"commodityCode": "TOTAL",
"tradeFlow": "Import",
"year": 2023,
"period": "2023",
"tradeValue": 427235841926,
"cifValue": null,
"fobValue": null,
"netWeight": null,
"grossWeight": null,
"quantity": null,
"quantityUnit": "",
"isReported": true,
"isAggregate": true
}

Output example (specific commodity)

When querying specific commodities rather than TOTAL, the output includes physical quantities and weights:

{
"reporter": "United States of America",
"reporterISO": "USA",
"reporterCode": 842,
"partner": "Germany",
"partnerISO": "DEU",
"partnerCode": 276,
"commodity": "Motor cars and other motor vehicles principally designed for the transport of persons",
"commodityCode": "8703",
"tradeFlow": "Import",
"year": 2023,
"period": "2023",
"tradeValue": 28450672000,
"cifValue": 28450672000,
"fobValue": null,
"netWeight": 4350000000,
"grossWeight": null,
"quantity": 850000,
"quantityUnit": "u",
"isReported": true,
"isAggregate": false
}

Output fields

FieldTypeDescription
reporterStringFull name of the reporting country (e.g., "United States of America").
reporterISOStringISO 3-letter code of the reporter (e.g., "USA").
reporterCodeNumberUN M49 numeric code of the reporter (e.g., 842).
partnerStringFull name of the trading partner country.
partnerISOStringISO 3-letter code of the partner.
partnerCodeNumberUN M49 numeric code of the partner.
commodityStringFull commodity description from the HS classification.
commodityCodeStringHarmonized System commodity code (e.g., "8703", "TOTAL").
tradeFlowStringDirection of trade flow (e.g., "Import", "Export", "Re-Export").
yearNumberReference year of the trade data.
periodStringReporting period string (typically matches year).
tradeValueNumberPrimary trade value in US Dollars.
cifValueNumberCost, Insurance, and Freight value in USD (typically for imports).
fobValueNumberFree on Board value in USD (typically for exports).
netWeightNumberNet weight in kilograms.
grossWeightNumberGross weight in kilograms.
quantityNumberPhysical quantity traded.
quantityUnitStringUnit of measurement for quantity (e.g., "u" for units, "kg" for kilograms). Empty if not applicable.
isReportedBooleanWhether the record was directly reported by the country (true) or estimated/mirrored (false).
isAggregateBooleanWhether the record represents an aggregate total (true) or commodity-level detail (false).

Use cases

  • Supply chain analysis -- track bilateral trade flows in specific commodities (e.g., semiconductors, rare earths, automotive parts) to map global supply chains and identify concentration risks.
  • Trade compliance and tariff research -- investigate import/export volumes between specific countries to support tariff impact assessments, trade agreement analysis, and regulatory compliance.
  • Economic research -- download historical trade data across multiple years and countries for academic papers, policy analysis, or econometric modeling.
  • Journalism and data storytelling -- pull official UN trade statistics with full metadata and sourcing for data-driven reporting on trade wars, sanctions impacts, or commodity price dynamics.
  • Investment analysis -- monitor commodity trade volumes and values to inform investment decisions in sectors tied to international trade.
  • Government and policy -- analyze bilateral trade balances, identify emerging trade partnerships, and assess the effectiveness of trade policies.
  • Machine learning pipelines -- collect structured historical trade data to train forecasting models on trade flows, commodity demand, or economic relationships between countries.

Common HS commodity codes

HS CodeDescription
TOTALAll commodities (aggregate)
27Mineral fuels, oils, and products
2709Crude petroleum oils
2710Refined petroleum oils
2701Coal
84Machinery and mechanical appliances
8542Electronic integrated circuits
85Electrical machinery and equipment
87Vehicles other than railway
8703Motor cars and motor vehicles for passengers
30Pharmaceutical products
71Precious metals and stones
72Iron and steel
0101Live horses
10Cereals

API and integration

Use the Apify API to run UN COMTRADE International Trade Data programmatically. The actor ID is NJCh32GyIiVnSTzqO.

Python

from apify_client import ApifyClient
client = ApifyClient("YOUR_APIFY_TOKEN")
run = client.actor("ryanclinton/un-comtrade-search").call(run_input={
"reporter": "USA",
"partner": "China",
"tradeFlow": "Import",
"year": "2023",
"maxResults": 100
})
dataset = client.dataset(run["defaultDatasetId"])
for item in dataset.iterate_items():
print(f"{item['reporter']} -> {item['partner']}: ${item['tradeValue']:,} ({item['tradeFlow']})")

JavaScript

import { ApifyClient } from "apify-client";
const client = new ApifyClient({ token: "YOUR_APIFY_TOKEN" });
const run = await client.actor("ryanclinton/un-comtrade-search").call({
reporter: "Germany",
commodity: "8703",
tradeFlow: "Export",
year: "2022,2023",
maxResults: 200,
});
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) =>
console.log(`${item.partner}: $${item.tradeValue} - ${item.commodity}`)
);

cURL

curl "https://api.apify.com/v2/acts/NJCh32GyIiVnSTzqO/runs" \
-X POST \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_APIFY_TOKEN" \
-d '{
"reporter": "Japan",
"partner": "USA",
"tradeFlow": "All",
"year": "2023",
"maxResults": 100
}'

Integrations

  • Google Sheets -- automatically push trade data to spreadsheets for analysis, visualization, and dashboards.
  • Slack / Email -- receive notifications when new trade data is available after a scheduled run.
  • Webhooks -- trigger downstream workflows in Zapier, Make, or n8n when a run completes.
  • Apify API -- consume results programmatically from any language or platform.

How it works

UN COMTRADE International Trade Data
====================================
[Input Config] [UN COMTRADE API] [Apify Dataset]
| | |
v v v
+-----------+ +---------------------+ +------------------+
| reporter |---->| comtradeapi.un.org |---->| Clean JSON |
| partner | | | | output with |
| commodity | | /public/v1/preview | | 20 fields per |
| tradeFlow | | (free, 500 max) | | trade record |
| year | | OR | | |
| subKey | | /data/v1/get | | Export: JSON, |
| maxResults| | (auth, 250K max) | | CSV, Excel |
+-----------+ +---------------------+ +------------------+
| | |
v v v
Country name Single GET request Push to dataset
resolution to with M49 codes, via Actor.pushData
M49 codes HS codes, flow
codes, year, &
includeDesc=true
  1. The actor reads input configuration and resolves country names, ISO codes, or M49 numeric codes using a built-in lookup table covering 40+ commonly queried countries.
  2. It determines whether to use the free preview endpoint (/public/v1/preview/C/A/HS, max 500 records) or the authenticated endpoint (/data/v1/get/C/A/HS, max 250,000 records) based on whether a subscription key is provided.
  3. Trade flow directions are mapped to the API's internal flow codes: Import to M, Export to X, Re-Import to RM, Re-Export to RX, and All to M,X,RM,RX.
  4. A single GET request is made to the COMTRADE API with all parameters. The includeDesc=true flag ensures human-readable descriptions are returned for countries and commodities.
  5. The raw API response is transformed into clean output records with 20 well-labeled fields. Quantity units with "N/A" values are filtered to empty strings for cleaner output.
  6. All results are pushed to the Apify dataset, where they can be exported or accessed via the Apify API.

Performance and cost

ScenarioMemoryDurationEst. cost
Single country pair, 1 year, aggregate128 MB~5 sec~$0.001
Single reporter, all partners, 1 year128 MB~10 sec~$0.001
Single reporter, specific commodity, 3 years256 MB~10 sec~$0.002
Authenticated query, 10,000 records256 MB~15 sec~$0.003
Authenticated query, 250,000 records512 MB~30 sec~$0.005

This actor is extremely lightweight. It makes a single API call per run with no web crawling, browser rendering, or pagination loops involved. Each execution typically completes in under 30 seconds.

  • Apify Free Tier: New Apify accounts receive $5 of free platform credits per month. A typical run costs a fraction of a cent, so you could execute thousands of queries per month within the free tier.
  • UN COMTRADE API: The free preview endpoint (used by default) allows up to 500 records per query at no cost. For larger data pulls, subscription keys are available from the UN COMTRADE portal.

Limitations

  • Data lag. COMTRADE data is reported by national statistical offices and typically has a 1-2 year lag. The most recent complete data is usually from one to two years before the current date.
  • Free endpoint caps at 500 records. Without a subscription key, the public preview endpoint returns a maximum of 500 records per query. For larger datasets, obtain a subscription key.
  • Single reporter/partner per run. The reporter and partner fields each accept a single country per run. To compare multiple reporter countries, run the actor multiple times with different inputs.
  • No real-time streaming. The actor fetches a snapshot of data per run. For continuous monitoring, schedule recurring runs on Apify.
  • Country lookup coverage. The built-in lookup table covers 40+ commonly queried countries. Less common countries may require their UN M49 numeric code to be entered directly.
  • HS classification only. This actor queries data classified by the Harmonized System (HS). Other classification systems (SITC, BEC) are not supported.
  • Null values for aggregate queries. When querying "TOTAL" commodities, physical quantity fields (netWeight, grossWeight, quantity) are typically null because aggregation across diverse commodities makes weight/quantity totals meaningless.

Responsible use

This actor retrieves data from the UN COMTRADE API, a public service provided by the United Nations Statistics Division. Please use it responsibly:

  • Comply with the UN COMTRADE Terms of Use when using retrieved data.
  • Attribute data to its original source (United Nations COMTRADE Database) in any publications, reports, or derived datasets.
  • Avoid excessive request volumes that could strain the COMTRADE API infrastructure.
  • Do not use this actor to redistribute raw COMTRADE data as a competing data service.
  • Respect the preview endpoint limitations and obtain a subscription key if your usage requires higher volumes.

FAQ

What is UN COMTRADE? UN COMTRADE (United Nations International Trade Statistics Database) is maintained by the UN Statistics Division. It contains annual and monthly trade data reported by statistical authorities of over 200 countries and territories, covering trillions of dollars in global merchandise trade. It is the most comprehensive source of international trade statistics available.

Do I need a UN COMTRADE API key? No. The actor works with the free public preview endpoint by default, which allows up to 500 records per query. For larger data pulls (up to 250,000 records), you can optionally provide a subscription key from the UN COMTRADE portal.

What are HS codes? The Harmonized System (HS) is an international standardized system of names and numbers to classify traded products. Codes range from 2 digits (broad chapters like "27" for mineral fuels) to 6 digits (specific products like "270900" for crude petroleum oils). This actor accepts HS codes at any level of specificity.

How current is the data? COMTRADE data typically has a 1-2 year lag because national statistical offices require time to compile and validate trade statistics. The most recent complete data is usually from one to two years before the current date.

Can I search for multiple countries at once? The reporter and partner fields each accept a single country per run. To compare multiple countries, run the actor multiple times with different inputs, or leave the partner field empty to get all trading partners for a given reporter.

What currency are trade values reported in? All trade values in COMTRADE are reported in US Dollars (USD).

What is the difference between CIF and FOB values? CIF (Cost, Insurance, and Freight) includes the cost of goods plus insurance and freight charges to the destination port -- typically used for import valuations. FOB (Free on Board) includes only the cost of goods loaded onto the transport vessel at the origin port -- typically used for export valuations. The tradeValue field represents the primary reported value.

What do the isReported and isAggregate flags mean? isReported indicates whether the data was directly reported by the country (true) or estimated/mirrored from the trading partner's data (false). isAggregate indicates whether the record represents a summary total across commodities (true) or a commodity-level detail (false).

How do I get a UN COMTRADE subscription key? Visit the UN COMTRADE Plus portal, create an account, and follow the instructions to request API access. The subscription key is provided as an Ocp-Apim-Subscription-Key header value.


ActorDescription
World Bank Development IndicatorsGlobal development indicators including GDP, population, and trade-related economic metrics that complement COMTRADE trade flow data.
OECD Economic StatisticsInternational economic data from OECD statistical datasets including trade balances, current account data, and macroeconomic indicators.
IMF Economic DataInternational Monetary Fund economic datasets covering balance of payments, international trade, and financial statistics.
FRED Economic Data SearchFederal Reserve Economic Data with 840,000+ US economic time series including trade-related indicators.
Currency Exchange Rate TrackerLive and historical currency exchange rates for converting trade values and analyzing currency impacts on trade flows.