# Brazil Import/Export Data by NCM (Importação por NCM) (`kman-br/importacao-ncm`) Actor

Importações e exportações oficiais do Brasil por NCM, mês e país, UF ou via, direto da API pública Comex Stat (MDIC). FOB, CIF, frete, seguro, kg líquido e US$/kg, com link e hash da fonte. Você paga só pelas linhas válidas.

- **URL**: https://apify.com/kman-br/importacao-ncm.md
- **Developed by:** [Kman](https://apify.com/kman-br) (community)
- **Categories:** Business, Developer tools
- **Stats:** 2 total users, 1 monthly users, 63.6% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

$1.50 / 1,000 linha ncm retornadas

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

## Importação por NCM — Comex Stat (Brasil)

### Português

Dados **oficiais, públicos e agregados** de importação e exportação do Brasil, direto da API pública Comex Stat (MDIC). Uma linha por NCM × mês × país, UF ou via de transporte, com FOB (US$), peso líquido (kg), quantidade estatística, CIF, frete, seguro e FOB US$/kg. Não identifica importadores nem pessoas físicas.

#### Para que serve

- Acompanhar volume e preço médio (US$/kg) de importação de um produto (NCM).
- Ver de quais países o Brasil compra e por quais UFs ou vias a mercadoria entra.
- Montar séries mensais e tendências de 12 meses.

#### Input

```json
{
  "flow": "import",
  "ncms": ["10019900", "27090010"],
  "periodoDe": "2025-01",
  "periodoAte": "2025-01",
  "paises": [],
  "ufs": [],
  "detalhar": "pais",
  "metricas": ["metricFOB", "metricKG", "metricStatistic", "metricFreight", "metricInsurance", "metricCIF"],
  "incremental": false,
  "maxItems": 1000,
  "timeoutSecs": 30
}
```

| Campo | Descrição |
| --- | --- |
| `flow` | `import` ou `export`. Na exportação não há CIF, frete nem seguro. |
| `ncms` | NCMs de 8 dígitos ou prefixos de 2 a 7 dígitos (expandidos pela tabela oficial). |
| `periodoDe`, `periodoAte` | Mês no formato `AAAA-MM`, desde 1997 (até 120 meses por run). |
| `paises` | Códigos de país do MDIC (não ISO). Vazio = todos. |
| `ufs` | Siglas de UF, como `SP`. Vazio = todas. |
| `detalhar` | `pais`, `uf` ou `via`. NCM e mês sempre vêm. |
| `metricas` | Métricas oficiais; FOB e KG sempre incluídas. |
| `maxItems` | Máximo de linhas de dados (1 a 100.000). |
| `incremental` | Se `true`, só consulta de novo quando a fonte oficial for atualizada. |
| `timeoutSecs` | Tempo máximo por requisição (1 a 120 s). |

O transporte usa conexão direta com a API oficial. O modo de proxy residencial foi removido desta versão pública; inputs antigos com `proxyResidencialBR` são rejeitados.

#### Saída

Cada linha traz `source_url`, `source_request` (corpo do POST para reproduzir a consulta), `source_sha256`, `retrieved_at` (ISO 8601, -03:00), `source_name`, `warnings` e `status`:

| Status | Significado |
| --- | --- |
| `ok` | Linha completa: todo dado solicitado presente, sem `warnings`. Pode ter `notas` (métrica não solicitada, dimensão não detalhada, `kg_liquido` = 0 com `usd_por_kg` null); `kg_liquido` = 0 sai `ok` e é cobrada. |
| `parcial` | Falta dado **solicitado** (dimensão detalhada, descrição do NCM, métrica pedida ou usd_por_kg sem FOB/KG). **Linhas `parcial` não são cobradas**; só linhas `ok` geram o evento `relatorio-ncm`. Métricas não solicitadas e dimensões não detalhadas vão para `notas` e não mudam o status. |
| `sem_resultado` | Consulta sem linhas (diagnóstico gratuito). |
| `fonte_indisponivel` | A Comex Stat ficou fora do ar (HTTP 429/5xx, timeout ou falha de conexão) mesmo após as retentativas, com `error_message` (diagnóstico gratuito). |
| `erro` | Input inválido, layout da fonte mudou ou falha de processamento, com `error_message` (gratuito). |

Os meses são consultados em lotes de 12. Um mês vazio dentro de um lote não gera linha `sem_resultado`; só um lote inteiro sem linhas gera essa linha, do primeiro ao último mês do lote.

`RUN_SUMMARY.motivo` pode ser `tempo_limite_run` (prazo do run), `teto_gasto_atingido` (teto de gasto), `maxItems_atingido` (limite de linhas) ou `fonte_indisponivel` (fonte caiu no meio da coleta). Com linhas já entregues, o **status do run** (`RUN_SUMMARY.status`) fica `parcial` — isso indica coleta interrompida e é diferente do `parcial` de linha (dado solicitado ausente, não cobrado); as linhas `ok` já entregues continuam cobradas. Se o prazo estoura antes de qualquer linha, o status fica `erro` e o motivo continua `tempo_limite_run`. Rodar de novo depois de um run parcial cobra outra vez as linhas já entregues.

Valores ausentes ficam `null` com aviso; nada é inventado. US$/kg agregado = soma FOB / soma kg. O resumo da execução (`RUN_SUMMARY`) traz rankings, série mensal e tendências de 12 meses. Quando a fonte limita requisições (HTTP 429) ou falha (5xx), o Actor espera e tenta de novo automaticamente, com no máximo 150 s de espera somados no run.

#### Quando a Comex Stat está fora do ar

- **Nenhuma linha entregue:** o run termina com **sucesso (código de saída 0)**, grava uma linha de diagnóstico gratuita com status `fonte_indisponivel`, o `RUN_SUMMARY` fica com `status` e `motivo` `fonte_indisponivel`, e a mensagem de status mostra `Comex Stat indisponível (HTTP xxx); nada cobrado`. **Nada é cobrado.** Antes, HTTP 429/5xx terminava o run com código de saída diferente de zero; isso mudou.
- **Fonte cai no meio:** o run termina com sucesso, `RUN_SUMMARY.status` = `parcial` e `motivo` = `fonte_indisponivel`; só as linhas já entregues são cobradas, e uma linha de diagnóstico gratuita marca os meses não coletados.
- **Input inválido ou layout da fonte alterado** continuam terminando com código de saída 1 (`status` = `erro`).
- O Actor encerra a coleta até 45 s antes do timeout do run; com timeout de até 300 s, encerra no máximo 180 s após o início.
- Em runs não incrementais cujo período termina há mais de 3 meses, a consulta de data de atualização da fonte é dispensada (`RUN_SUMMARY.atualizacao_dispensada` = `true`), o que evita uma pausa de 11 s.

#### Preço

**US$ 1,50 por 1.000 linhas válidas** (US$ 0,0015 por evento `relatorio-ncm`). Você paga só pelas linhas válidas: diagnósticos, erros e consultas sem resultado são gratuitos. O teto de gasto definido por você é respeitado. Sem custo de plataforma para o usuário.

### English

**Official, public, aggregated** Brazilian import/export statistics from the Comex Stat public API (MDIC). One row per NCM code × month × country, state or transport mode, with FOB USD, net weight (kg), statistical quantity, CIF, freight, insurance and FOB USD/kg. No importer or personal data.

**Input:** flow (`import`/`export`), NCM codes or prefixes, period (`YYYY-MM`), optional MDIC country codes and state abbreviations, breakdown (`pais`, `uf` or `via`), metrics, `maxItems`, optional `incremental` mode and per-request timeout. See the example above.

**Transport:** direct connection to the official API. Residential proxy mode is removed; old inputs containing `proxyResidencialBR` are rejected.

**Output:** every row includes the official source URL, the replayable POST body, a SHA-256 of the response, timestamp, warnings and status (`ok`, `parcial`, `sem_resultado`, `fonte_indisponivel`, `erro`). Missing values are `null` with a warning, never invented. The run summary includes rankings, monthly series and 12-month trends. Rate limits (HTTP 429) and 5xx errors are retried automatically with backoff, capped at 150 s of total waiting per run.

**When Comex Stat is down:**

- **No rows delivered:** the run **succeeds (exit code 0)**, writes one free diagnostic row with status `fonte_indisponivel`, sets `RUN_SUMMARY.status` and `motivo` to `fonte_indisponivel`, and the status message reads `Comex Stat indisponível (HTTP xxx); nada cobrado` ("Comex Stat unavailable; nothing charged"). **Nothing is charged.** Previously, HTTP 429/5xx ended the run with a non-zero exit code; that contract has changed.
- **Source fails mid-run:** the run succeeds with `RUN_SUMMARY.status` = `parcial` and `motivo` = `fonte_indisponivel`; only rows already delivered are charged, and a free diagnostic row marks the months not collected.
- **Invalid input or a changed source layout** still end with exit code 1 (`status` = `erro`).
- Collection stops at least 45 s before the run timeout; with a timeout of 300 s or less, it stops no later than 180 s after start.
- Non-incremental runs whose period ended more than 3 months ago skip the source's last-update lookup (`RUN_SUMMARY.atualizacao_dispensada` = `true`), avoiding an 11 s pause.

`parcial` rows (requested data missing) are **never charged**; only `ok` rows trigger `relatorio-ncm`. Unrequested metrics and non-detailed dimensions go to `notas` and do not change the status.

Months are queried in batches of 12. An empty month inside a batch does not emit a `sem_resultado` row; only a fully empty batch does, covering the first through the last month of that batch.

`RUN_SUMMARY.motivo` can be `tempo_limite_run` (run time limit), `teto_gasto_atingido` (spending cap), `maxItems_atingido` (row cap) or `fonte_indisponivel` (source went down mid-run). When rows were already delivered, the **run status** (`RUN_SUMMARY.status`) is `parcial`: the run was cut short. This is not the row-level `parcial` (requested data missing, not charged); `ok` rows already delivered remain charged. If the time limit hits before any row, status is `erro` and the motivo stays `tempo_limite_run`. Rerunning after a partial run charges again for rows already delivered.

**Pricing:** **US$1.50 per 1,000 valid rows** (US$0.0015 per `relatorio-ncm` event). You pay only for valid rows; diagnostics, errors and empty queries are free. Your spending limit is respected. No platform usage cost for users.

Data source: [Comex Stat / MDIC](https://comexstat.mdic.gov.br/pt/geral). This Actor is independent and not affiliated with the Brazilian government.

### Related Actors

More Actors from the same publisher:

- [Brazil Diesel Fuel Prices ANP (Preço do Diesel)](https://apify.com/kman-br/diesel-anp): Weekly average, minimum and maximum diesel prices (S10/S500) from the ANP survey, by state or city.
- [Brazil CNPJ Bulk Lookup - Receita Federal (CNPJ em Lote)](https://apify.com/kman-br/cnpj-lote): Bulk lookup of Brazilian company CNPJs in Receita Federal open data. Companies only, no partners or contacts.
- [Brazil Anatel Certified Products (Produtos Homologados)](https://apify.com/kman-br/anatel): Search, new-entry tracking and bulk validation of Anatel certified products from open data.
- [Brazil Public Tender Prices CATMAT/CATSER (Preço Público)](https://apify.com/kman-br/preco-publico-comparavel): Public purchase prices by CATMAT, CATSER or description from Compras.gov.br, cross-checked on PNCP.

Browse the full catalog: [kman-br.github.io](https://kman-br.github.io/) ([Português](https://kman-br.github.io/pt/)).

# Actor input Schema

## `flow` (type: `string`):

Selecione importação (import) ou exportação (export). CIF, frete e seguro estão disponíveis apenas para importação.

## `ncms` (type: `array`):

Códigos de 8 dígitos ou prefixos de 2 a 7 dígitos, expandidos pela tabela oficial.

## `periodoDe` (type: `string`):

Primeiro mês da consulta, inclusive, no formato AAAA-MM, desde 1997-01. O intervalo pode ter no máximo 120 meses.

## `periodoAte` (type: `string`):

Último mês da consulta, inclusive, no formato AAAA-MM. Deve ser igual ou posterior ao início e não superar o último mês publicado pelo MDIC.

## `paises` (type: `array`):

Códigos da API, não ISO. Vazio inclui todos.

## `ufs` (type: `array`):

Selecione uma ou mais UFs para filtrar pela UF do produto. Vazio inclui todas. As siglas são convertidas pela tabela oficial MDIC, cujos códigos diferem dos códigos IBGE.

## `detalhar` (type: `string`):

Agrupe por país, UF do produto ou via de transporte, além de NCM e mês sempre presentes. As outras dimensões ficam null com aviso na saída.

## `metricas` (type: `array`):

Selecione uma ou mais métricas oficiais. FOB (US$) e KG (peso líquido) são sempre solicitados para US$/kg; quantidade estatística depende da unidade do NCM. CIF, frete e seguro são exclusivos de importação: desmarque essas opções ao selecionar exportação.

## `incremental` (type: `boolean`):

false repete resultados em cada execução. true reutiliza estado por filtro e consulta atualização uma vez/dia.

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

Máximo de linhas de dados por execução, de 1 a 100.000. Diagnósticos não contam neste limite. Uma entrega interrompida pelo limite não avança o estado incremental.

## `timeoutSecs` (type: `integer`):

Tempo máximo, de 1 a 120 segundos, para cada requisição e leitura da resposta. As esperas de retentativa por HTTP 429/5xx são separadas deste timeout.

## Actor input object example

```json
{
  "flow": "import",
  "ncms": [
    "10019900",
    "27090010"
  ],
  "periodoDe": "2025-01",
  "periodoAte": "2025-01",
  "paises": [],
  "ufs": [],
  "detalhar": "pais",
  "metricas": [
    "metricFOB",
    "metricKG",
    "metricStatistic",
    "metricFreight",
    "metricInsurance",
    "metricCIF"
  ],
  "incremental": false,
  "maxItems": 1000,
  "timeoutSecs": 30
}
```

# Actor output Schema

## `results` (type: `string`):

No description

## `summary` (type: `string`):

RUN_SUMMARY. motivo de parada antecipada: tempo_limite_run, teto_gasto_atingido, maxItems_atingido ou fonte_indisponivel (Comex Stat fora do ar; nada cobrado sem linhas entregues).

# 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 = {
    "flow": "import",
    "ncms": [
        "10019900",
        "27090010"
    ],
    "periodoDe": "2025-01",
    "periodoAte": "2025-01",
    "paises": [],
    "ufs": [],
    "detalhar": "pais",
    "metricas": [
        "metricFOB",
        "metricKG",
        "metricStatistic",
        "metricFreight",
        "metricInsurance",
        "metricCIF"
    ],
    "incremental": false,
    "maxItems": 1000,
    "timeoutSecs": 30
};

// Run the Actor and wait for it to finish
const run = await client.actor("kman-br/importacao-ncm").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 = {
    "flow": "import",
    "ncms": [
        "10019900",
        "27090010",
    ],
    "periodoDe": "2025-01",
    "periodoAte": "2025-01",
    "paises": [],
    "ufs": [],
    "detalhar": "pais",
    "metricas": [
        "metricFOB",
        "metricKG",
        "metricStatistic",
        "metricFreight",
        "metricInsurance",
        "metricCIF",
    ],
    "incremental": False,
    "maxItems": 1000,
    "timeoutSecs": 30,
}

# Run the Actor and wait for it to finish
run = client.actor("kman-br/importacao-ncm").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 '{
  "flow": "import",
  "ncms": [
    "10019900",
    "27090010"
  ],
  "periodoDe": "2025-01",
  "periodoAte": "2025-01",
  "paises": [],
  "ufs": [],
  "detalhar": "pais",
  "metricas": [
    "metricFOB",
    "metricKG",
    "metricStatistic",
    "metricFreight",
    "metricInsurance",
    "metricCIF"
  ],
  "incremental": false,
  "maxItems": 1000,
  "timeoutSecs": 30
}' |
apify call kman-br/importacao-ncm --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,kman-br/importacao-ncm"
        }
    }
}
```

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/TfyhhozzmsEZAZ1Bj/builds/EmfSgbwsweVvqAMbz/openapi.json
