# Consulta CNPJ em Lote: Brazil CNPJ Lookup (Receita Federal) (`hanielazevedo/brazil-cnpj-company-lookup`) Actor

Consulta CNPJ em lote (Brazil company lookup): bulk CNPJ lookup from Receita Federal open data. Razão social, CNAE, QSA partners, address, phone, Simples/MEI, for leads & KYC. $1.20 per 1,000 found.

- **URL**: https://apify.com/hanielazevedo/brazil-cnpj-company-lookup.md
- **Developed by:** [Haniel Azevedo](https://apify.com/hanielazevedo) (community)
- **Categories:** Lead generation, Automation
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $1.20 / 1,000 company results

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

**Português (BR)** · [English](#english)

**Cole uma lista de CNPJs e receba, em segundos, o cadastro completo de cada empresa:**

- razão social e nome fantasia
- situação cadastral e data de abertura
- natureza jurídica, porte e capital social
- CNAE principal e secundários
- endereço, telefone e e-mail
- quadro de sócios e administradores (QSA)
- opção pelo Simples Nacional e MEI

São dados abertos oficiais da Receita Federal, e você **paga só pelas empresas encontradas** (US$ 1,20 por 1.000).

✅ Valida dígitos verificadores e remove duplicados · ✅ CNPJ com ou sem máscara, incluindo o novo **CNPJ alfanumérico** · ✅ Linhas de erro gratuitas · ✅ Fonte reserva automática · ✅ Visões prontas para Excel ("Overview") e uma linha por sócio ("Partners (QSA)")

### Para quem é

- **Vendas e marketing B2B**: enriquecimento de leads com CNAE, porte, capital, cidade/UF, telefone e e-mail.
- **Compliance, KYC/KYB e compras**: situação cadastral (ATIVA, BAIXADA, INAPTA…) e sócios de fornecedores e clientes.
- **Financeiro e fiscal**: confira Simples Nacional e MEI antes de faturar.
- **CRM/ERP e dados**: padronize razão social e endereço e recupere os zeros à esquerda perdidos no Excel.
- **Desenvolvedores e agentes de IA**: uma API de CNPJ confiável, sem chave.

### Experimente

Clique em **Start** sem mudar nada. A entrada pré-preenchida consulta Petrobras, Banco do Brasil e Itaú Unibanco com o QSA. No nosso teste (31/10/2026), as 3 foram encontradas em cerca de 2 segundos (8, 41 e 142 sócios), por **US$ 0,0036**. Com a entrada vazia `{}`, só a Petrobras é consultada. Depois cole sua lista, um CNPJ por linha, em qualquer formato.

### Como consultar CNPJ em lote (passo a passo)

1. Cole seus CNPJs no campo **CNPJs**, um por linha, com ou sem máscara (`33.000.167/0001-01`, `33000167000101` ou até `191`, que vira `00000000000191`). Pela API, envie `cnpjs` como lista ou como texto separado por quebra de linha, vírgula ou ponto e vírgula.
2. Deixe **Include partners (QSA)** ligado se precisar dos sócios; desligue se não precisar.
3. Opcional: defina *Maximum cost per run* nas opções da execução para limitar o gasto.
4. Clique em **Start**.
5. Abra a aba **Output** e baixe em Excel ou CSV pela visão **Overview** (uma linha por empresa) ou **Partners (QSA)** (uma linha por sócio), ou consuma pela API, Make, Zapier ou n8n.

### Exemplo de saída

O JSON real está na seção em inglês. Os principais campos são:

- `legalName` (razão social) e `tradeName` (nome fantasia)
- `registrationStatus` (situação), `openingDate` e `legalNature`
- `companySize` e `shareCapitalBRL`
- `primaryCnae` e `secondaryCnaes`
- `address` e `fullAddress`, `phones` e `email`
- `simplesNacional` e `mei` (`true`/`false` com as datas; `null` quando a fonte não tem registro do Simples para a empresa)
- `partners` (QSA, com CPF mascarado)

### Códigos de erro

| `errorCode` | Significado | Cobrado? |
|---|---|---|
| `null` (`success: true`) | Empresa encontrada | Sim, US$ 0,0012 |
| `INVALID_FORMAT` | Não é um CNPJ | Não |
| `INVALID_CHECK_DIGITS` | Dígito verificador errado (erro de digitação) | Não |
| `NOT_FOUND` | Número válido que não está no cadastro da Receita | Não |
| `UPSTREAM_ERROR` | Todas as fontes falharam após as tentativas; rode de novo só esses CNPJs | Não |

### Quanto custa consultar CNPJ em lote?

**US$ 0,0012 por empresa encontrada**, mais a taxa de início da Apify (US$ 0,00005). Exemplos: as 3 empresas da entrada padrão custam **US$ 0,0036**; 1.000 CNPJs com 950 encontrados custam **US$ 1,14**; 10.000 custam **US$ 12,00**. CNPJs inválidos, duplicados, não encontrados ou com falha não são cobrados. Defina um *Maximum cost per run* e o Actor para ao atingir esse limite.

**Comparação** (preços da Apify Store consultados em 31/10/2026, no plano gratuito): este Actor cobra **US$ 1,20 por 1.000 empresas encontradas**; outros três Actors de CNPJ cobram US$ 1,50, US$ 2,00 (mais US$ 0,10 por execução) e US$ 5,00 por 1.000. Um deles chega a US$ 1,20 só no maior nível de desconto. Aqui CNPJs inválidos, duplicados ou não encontrados não são cobrados.

### Fontes de dados

Os dados são públicos, da **Receita Federal do Brasil** (CNPJ – Dados Abertos), acessados via [Minha Receita](https://minhareceita.org) (fonte principal) e [BrasilAPI](https://brasilapi.com.br) (reserva). A [API pública do CNPJá](https://cnpja.com/api/open) é uma reserva opcional, desligada por padrão. Não há login nem scraping, e o Actor respeita os limites de cada fonte.

### Perguntas frequentes

**E se o CNPJ estiver errado ou uma fonte cair?** Erros de digitação são detectados antes da consulta e não são cobrados. Se a Minha Receita falhar, o Actor tenta de novo e passa para a BrasilAPI. Só se todas as fontes falharem você recebe `UPSTREAM_ERROR`, também grátis.

**Quais são os limites?** Não há limite fixo de CNPJs por execução. A velocidade é de cerca de 5 por segundo (~18 mil por hora), e o único limite rígido é o seu *Maximum cost per run*. Os dados acompanham a última base mensal da Receita carregada pela fonte.

**Dá para monitorar mudanças?** Não há modo de diferenças embutido. Agende o Actor (por exemplo, mensalmente) com sua lista e compare situação, sócios ou endereço entre as execuções.

**É permitido? E a LGPD?** O cadastro CNPJ, incluindo o QSA, é dado aberto publicado pelo governo, e os CPFs dos sócios já vêm mascarados. Nomes de sócios e contatos de MEIs podem ser dados pessoais: use-os com base legal adequada e desative `includePartners` se não precisar deles.

**Quais formatos de saída?** Excel, CSV, JSON, XML, RSS ou HTML, além das visões "Overview" (uma linha por empresa) e "Partners (QSA)" (uma linha por sócio).

**Integra com o quê?** Make, Zapier, n8n, Google Sheets, webhooks, API e clientes JS/Python da Apify, e o servidor MCP da Apify (`https://mcp.apify.com`) para agentes de IA.

**Por que o e-mail ou telefone veio vazio?** O Actor retorna só o que a empresa informou à Receita Federal.

**Suporta CNPJ alfanumérico e filiais?** Sim, o CNPJ alfanumérico segue a IN RFB 2.229/2024. Cada CNPJ, matriz ou filial, é consultado individualmente, e `branchType` indica qual é.

### Uso com agentes de IA (MCP) e Python

**MCP:** adicione este Actor como ferramenta no Claude Desktop, Cursor, VS Code ou outro cliente MCP pelo servidor MCP da Apify: `https://mcp.apify.com?tools=hanielazevedo/brazil-cnpj-company-lookup`. O agente lê o schema de entrada, roda o Actor e lê o dataset.

**Python** (`pip install apify-client`): veja o exemplo na seção em inglês.

### Outros Actors do Haniel

- [PDF to Markdown & Text Extractor with OCR (DOCX)](https://apify.com/hanielazevedo/document-to-markdown-ocr): PDF, PDF escaneado, DOCX, HTML e imagens para Markdown ou texto limpo, para RAG e agentes de IA. US$ 3 por 1.000 documentos.
- [SAM.gov Scraper: Federal Contract Opportunities Monitor](https://apify.com/hanielazevedo/samgov-contract-opportunities): Novas oportunidades de contratos federais dos EUA no SAM.gov por NAICS, set-aside e órgão. Sem chave de API. US$ 2 por 1.000.
- [Greenhouse, Lever & Ashby Jobs Scraper: New Jobs Monitor](https://apify.com/hanielazevedo/greenhouse-lever-ashby-new-jobs-monitor): Vagas de páginas de carreira Greenhouse, Lever e Ashby, com modo monitor que traz só as vagas novas. US$ 1,50 por 1.000 vagas.
- [Floor Plan Takeoff: PDF Room Areas, Wall LF & Door Counts](https://apify.com/hanielazevedo/floor-plan-takeoff): Levantamento de quantitativos de plantas em PDF vetorial: área dos ambientes, metros lineares de parede e portas. US$ 2,50 por prancha medida.

***

### English

**Paste a list of CNPJs and get a full Brazilian company profile for each one in seconds: razão social, status, CNAE, address, phone, partners (QSA) and Simples Nacional / MEI. Official Receita Federal open data, and you pay only for companies found ($1.20 per 1,000).**

✅ Validates check digits and removes duplicates before any lookup · ✅ Formatted or raw CNPJs, including the new **alphanumeric CNPJ** (2026) · ✅ Free error rows for invalid CNPJs · ✅ Automatic fallback between data sources · ✅ Excel/CSV-ready "Overview" view and a one-row-per-partner "Partners (QSA)" view

#### Who it's for

- **B2B sales and marketing teams** enriching lead lists with industry (CNAE), size, capital, city/state, phone and email.
- **Compliance, KYC/KYB and procurement** checking that suppliers and customers are `ATIVA` and who their partners and administrators are.
- **Finance and tax teams** confirming Simples Nacional / MEI status before invoicing.
- **CRM/ERP admins and data teams** cleaning names and addresses, catching closed (`BAIXADA`) or unfit (`INAPTA`) companies, and fixing CNPJs that lost their leading zeros in Excel.
- **Developers and AI agents** that need a reliable CNPJ API with no key to manage.

#### Try it

Click **Start** without changing anything. The prefilled input looks up three well-known companies (Petrobras, Banco do Brasil, Itaú Unibanco) with their partners:

```json
{
    "cnpjs": ["33.000.167/0001-01", "00000000000191", "60701190000104"],
    "includePartners": true
}
```

In our test run (31 Oct 2026) all 3 were found in about 2 seconds, with 8, 41 and 142 partners, for **$0.0036**. An empty input `{}` looks up Petrobras only. Then paste your own list: one per line, any format (`33.000.167/0001-01`, `33000167000101`, even `191`, which is padded to `00000000000191`).

#### How to look up CNPJs in bulk (step by step)

1. Paste your CNPJs into **CNPJs** (or send `cnpjs` through the API: an array, or one string with CNPJs separated by new lines, commas or semicolons).
2. Keep **Include partners (QSA)** on if you need partners, or turn it off.
3. Optional: set *Maximum cost per run* in the run options to cap spend.
4. Click **Start**.
5. Download the results as Excel, CSV, JSON or XML, or fetch them with the Apify API, integrations (Make, Zapier, n8n…) or the Apify MCP server.

| Field | Default | Description |
|---|---|---|
| `cnpjs` | Petrobras (`33.000.167/0001-01`) | List of CNPJs, formatted or raw (numeric or alphanumeric). |
| `includePartners` | `true` | Include the partners/administrators list (QSA). |
| `includeTaxRegimeHistory` | `false` | Include the yearly tax regime history when available. |
| `includeRawData` | `false` | Attach the untouched source JSON. |
| `outputInvalid` | `true` | Add a free error row for each invalid CNPJ. |
| `padLeadingZeros` | `true` | Restore leading zeros dropped by spreadsheets. |
| `maxConcurrency` | `5` | Parallel lookups (1–25). |
| `enableBrasilApiFallback` | `true` | Retry on BrasilAPI if the primary source fails. |
| `enableCnpjaFallback` | `false` | Slow last-resort fallback (5 requests/min). |
| `minhaReceitaBaseUrl` | `https://minhareceita.org` | Point to your own self-hosted Minha Receita instance if you like. |

#### Sample output

This is a real record from the test run above (secondary CNAEs and partners shortened, partner name hidden here):

```json
{
    "input": "33.000.167/0001-01",
    "success": true,
    "errorCode": null,
    "error": null,
    "cnpj": "33000167000101",
    "cnpjFormatted": "33.000.167/0001-01",
    "cnpjRoot": "33000167",
    "legalName": "PETROLEO BRASILEIRO S A PETROBRAS",
    "tradeName": "PETROBRAS - EDISE",
    "branchType": "HEADQUARTERS",
    "registrationStatus": "ATIVA",
    "registrationStatusCode": 2,
    "registrationStatusDate": "2005-11-03",
    "registrationStatusReason": "SEM MOTIVO",
    "specialStatus": null,
    "specialStatusDate": null,
    "openingDate": "1966-09-28",
    "legalNatureCode": "2038",
    "legalNature": "Sociedade de Economia Mista",
    "companySize": "DEMAIS",
    "shareCapitalBRL": 205431960000,
    "responsibleFederativeEntity": null,
    "primaryCnae": {
        "code": "0600001",
        "codeFormatted": "0600-0/01",
        "description": "Extração de petróleo e gás natural"
    },
    "secondaryCnaes": [
        {
            "code": "1921700",
            "codeFormatted": "1921-7/00",
            "description": "Fabricação de produtos do refino de petróleo"
        },
        {
            "code": "3520401",
            "codeFormatted": "3520-4/01",
            "description": "Produção de gás; processamento de gás natural"
        }
    ],
    "address": {
        "streetType": "AVENIDA",
        "street": "REPUBLICA DO CHILE",
        "number": "65",
        "complement": null,
        "neighborhood": "CENTRO",
        "city": "RIO DE JANEIRO",
        "cityIbgeCode": "3304557",
        "state": "RJ",
        "zipCode": "20031-170",
        "country": "BRASIL"
    },
    "fullAddress": "AVENIDA REPUBLICA DO CHILE, 65, CENTRO, RIO DE JANEIRO - RJ, CEP 20031-170",
    "phones": [
        "(21) 2166-0000"
    ],
    "fax": "213224",
    "email": null,
    "simplesNacional": {
        "optant": null,
        "optionDate": null,
        "exclusionDate": null
    },
    "mei": {
        "optant": null,
        "optionDate": null,
        "exclusionDate": null
    },
    "partnersCount": 8,
    "partners": [
        {
            "name": "…",
            "type": "PERSON",
            "documentMasked": "***912137**",
            "qualification": "Diretor",
            "qualificationCode": 10,
            "entryDate": "2025-07-29",
            "ageRange": "Entre 71 a 80 anos",
            "country": null,
            "legalRepresentativeName": null,
            "legalRepresentativeQualification": null
        }
    ],
    "source": "minhareceita",
    "fetchedAt": "2026-10-31T21:13:19.134Z"
}
```

`simplesNacional` / `mei` hold `true` / `false` plus the option and exclusion dates. They are `null` when the source has no Simples record for the company, which is typical for large companies like this one. Banco do Brasil in the same run returned `optant: false`.

Invalid or unknown CNPJs return a free row like this:

```json
{ "input": "12345678000100", "cnpj": "12345678000100", "success": false, "errorCode": "INVALID_CHECK_DIGITS", "error": "Invalid check digits (expected 95, got 00)" }
```

#### Error codes

| `errorCode` | Meaning | Charged? |
|---|---|---|
| `null` (`success: true`) | Company found and enriched | Yes, $0.0012 |
| `INVALID_FORMAT` | Not a CNPJ (wrong length or characters) | No |
| `INVALID_CHECK_DIGITS` | Check digits don't match (typo) | No |
| `NOT_FOUND` | Valid number, but not in the Receita Federal registry (too new, or never issued) | No |
| `UPSTREAM_ERROR` | All data sources failed after retries. Re-run just these CNPJs | No |

Duplicates are removed silently (counted in `SUMMARY`). If `cnpjs` is explicitly empty, the run fails with a clear message. Each run saves a `SUMMARY` record (key-value store) with found / not-found / invalid / error counts, the provider used, charged results and speed.

#### How much does it cost to look up CNPJs in bulk?

Pay per event:

| Event | Price |
|---|---|
| `apify-actor-start` | $0.00005 per run (Apify's standard start fee) |
| `company-result` | **$0.0012 per company found** |

Invalid, duplicate or not-found CNPJs and failed lookups are free. Set a *Maximum cost per run* and the Actor stops cleanly at that limit.

| Job | Calculation | Cost |
|---|---|---|
| The prefilled input (3 companies) | 3 × $0.0012 | **$0.0036** |
| 1,000 CNPJs, 950 found, 50 invalid | 950 × $0.0012 | **$1.14** |
| 10,000 CNPJs | 10,000 × $0.0012 | **$12.00** |
| Monthly re-check of 500 suppliers | 500 × $0.0012 per month | **$0.60 per month** |

**How it compares** (Apify Store prices checked on 31 Oct 2026, free plan): this Actor charges **$1.20 per 1,000 companies found**; three other CNPJ Actors charge $1.50, $2.00 (plus $0.10 per run) and $5.00 per 1,000. One of them reaches $1.20 only at its highest discount tier. Here, invalid, duplicate and not-found CNPJs are free.

#### Data sources

All data is **public open data published by Receita Federal do Brasil** (Cadastro Nacional da Pessoa Jurídica – Dados Abertos), served through free public APIs:

1. **[Minha Receita](https://minhareceita.org)** (primary). An open-source API over the official Receita Federal dumps, by Eduardo Cuducos and contributors.
2. **[BrasilAPI](https://brasilapi.com.br)** (automatic fallback). A community API that serves the same dataset with caching.
3. **[CNPJá public API](https://cnpja.com/api/open)** (optional, off by default). An independent source, limited to 5 requests/min.

The Actor is gentle on these free services: it caps concurrency and request rate, retries with exponential backoff, and never logs in or scrapes protected pages. The data is as fresh as the latest monthly Receita Federal release that the source has loaded.

#### FAQ

**What if a CNPJ is wrong or a data source is down?** Typos are caught before any lookup (`INVALID_FORMAT`, `INVALID_CHECK_DIGITS`) and cost nothing. If Minha Receita fails, the Actor retries with backoff and then falls back to BrasilAPI (and optionally CNPJá). Only if every source fails do you get `UPSTREAM_ERROR`, which is also free, so you can re-run just those rows.

**What are the limits?** There is no fixed cap on list size: thousands of CNPJs per run are fine. Speed is about 5 CNPJs per second with the default concurrency of 5, roughly 18,000 per hour. Your *Maximum cost per run* is the only hard stop. The data is as fresh as the latest monthly Receita Federal release loaded by the source.

**Can I monitor companies for changes?** There is no built-in diff mode. Schedule the Actor (Console > Schedules) with your list, for example monthly, and compare `registrationStatus`, partners or address between runs. Each re-check costs $0.0012 per company.

**Where does the data come from? Is it legal (LGPD)?** It is the CNPJ registry published by Receita Federal as government open data, served through public APIs, with no login or scraping. Partner CPFs are already masked by Receita Federal. Partner names, and contact details of sole proprietors/MEIs, can still be personal data under LGPD: use them only with a valid legal basis (legitimate interest, compliance…), and turn off `includePartners` if you don't need them.

**Which output formats are available?** JSON, CSV, Excel, XML, RSS or HTML from the dataset. The **Overview** view gives one flat row per company (good for Excel), and **Partners (QSA)** gives one row per partner. You can also fetch results through the API.

**What can I connect it to?** Make, Zapier, n8n, Google Sheets, webhooks, the Apify API and JS/Python clients, and the Apify MCP server (`https://mcp.apify.com`), so AI agents can look up CNPJs.

**Why are email or phone empty?** The Actor returns only what the company registered with Receita Federal, and large companies often leave the email blank.

**Does it support the new alphanumeric CNPJ and branches (filiais)?** Yes. Validation follows IN RFB 2.229/2024 (for example `12.ABC.345/01DE-35`). Every CNPJ, head office `/0001` or branch, is looked up individually, and `branchType` tells you which one it is.

#### Use with AI agents (MCP) and Python

**MCP:** add this Actor as a tool in Claude Desktop, Cursor, VS Code or any MCP client through the Apify MCP server: `https://mcp.apify.com?tools=hanielazevedo/brazil-cnpj-company-lookup` (sign in with your Apify account or pass your API token). The agent sees the input schema and can run the Actor and read the dataset itself.

**Python** (`pip install apify-client`):

```python
from apify_client import ApifyClient

client = ApifyClient("<YOUR_APIFY_TOKEN>")
run = client.actor("hanielazevedo/brazil-cnpj-company-lookup").call(run_input={
    "cnpjs": [
        "33.000.167/0001-01",
        "00000000000191"
    ],
    "includePartners": True
})
for item in client.dataset(run["defaultDatasetId"]).iterate_items():
    print(item)
```

#### Other Actors by Haniel

- [PDF to Markdown & Text Extractor with OCR (DOCX)](https://apify.com/hanielazevedo/document-to-markdown-ocr): PDF, scanned PDF, DOCX, HTML and images to clean Markdown or text for RAG and AI agents. $3 per 1,000 documents.
- [SAM.gov Scraper: Federal Contract Opportunities Monitor](https://apify.com/hanielazevedo/samgov-contract-opportunities): New SAM.gov contract opportunities, RFPs and sources sought by NAICS, set-aside and agency. No API key. $2 per 1,000 notices.
- [Greenhouse, Lever & Ashby Jobs Scraper: New Jobs Monitor](https://apify.com/hanielazevedo/greenhouse-lever-ashby-new-jobs-monitor): Jobs from Greenhouse, Lever and Ashby career pages, with a monitor mode that returns only new postings. $1.50 per 1,000 jobs.
- [Floor Plan Takeoff: PDF Room Areas, Wall LF & Door Counts](https://apify.com/hanielazevedo/floor-plan-takeoff): Construction takeoff from vector floor-plan PDFs: room SF, wall linear feet, door counts and a check overlay. $2.50 per measured sheet.

# Actor input Schema

## `cnpjs` (type: `array`):

List of Brazilian CNPJ numbers, formatted (33.000.167/0001-01) or raw (33000167000101). Numeric and the new alphanumeric CNPJ are supported. Check digits are validated and duplicates removed before any lookup. Invalid CNPJs are reported in the dataset and never charged.

## `includePartners` (type: `boolean`):

Include the public partner/shareholder list (Quadro de Sócios e Administradores) published by Receita Federal. Partner CPFs are already masked at the source. Turn off if you don't need personal data (LGPD data minimization).

## `includeTaxRegimeHistory` (type: `boolean`):

Include the yearly tax regime history (Lucro Real / Presumido / Arbitrado / Imune) when available.

## `includeRawData` (type: `boolean`):

Also attach the untouched JSON returned by the data source in a rawData field.

## `outputInvalid` (type: `boolean`):

Add a free (uncharged) row with an error for each input that fails CNPJ format/check-digit validation.

## `padLeadingZeros` (type: `boolean`):

Spreadsheets often drop leading zeros (00000000000191 becomes 191). When on, purely numeric inputs with 3-13 digits are left-padded with zeros to 14 digits before validation.

## `maxConcurrency` (type: `integer`):

Maximum number of CNPJs looked up in parallel. Keep it modest to respect the free public data sources.

## `requestTimeoutSecs` (type: `integer`):

Timeout for a single HTTP request to a data source. Failed requests are retried with exponential backoff.

## `primaryRequestsPerMinute` (type: `integer`):

Politeness cap on requests per minute to the primary source (Minha Receita). 0 = no cap.

## `enableBrasilApiFallback` (type: `boolean`):

If the primary source errors or times out, retry the CNPJ on BrasilAPI (throttled to 30 requests/minute).

## `enableCnpjaFallback` (type: `boolean`):

Optional last resort for CNPJs that failed on all other sources. The CNPJá public API allows only 5 requests/minute, so this is slow. Off by default.

## `minhaReceitaBaseUrl` (type: `string`):

Base URL of a Minha Receita instance. Use the public one or point to your own self-hosted instance (open source) for very large jobs.

## Actor input object example

```json
{
  "cnpjs": [
    "33.000.167/0001-01",
    "00000000000191",
    "60701190000104"
  ],
  "includePartners": true,
  "includeTaxRegimeHistory": false,
  "includeRawData": false,
  "outputInvalid": true,
  "padLeadingZeros": true,
  "maxConcurrency": 5,
  "requestTimeoutSecs": 20,
  "primaryRequestsPerMinute": 300,
  "enableBrasilApiFallback": true,
  "enableCnpjaFallback": false,
  "minhaReceitaBaseUrl": "https://minhareceita.org"
}
```

# Actor output Schema

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

Um item por CNPJ informado / one dataset item per input CNPJ: dados cadastrais da Receita Federal (razão social, situação, CNAE, endereço, contatos, Simples/MEI, sócios/QSA). Invalid or not-found CNPJs come back with success false and an errorCode (not charged).

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

SUMMARY record: input values, unique valid CNPJs, invalid, duplicates removed, found, not found, upstream errors, charged results, results by provider and speed.

# 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 = {
    "cnpjs": [
        "33.000.167/0001-01",
        "00000000000191",
        "60701190000104"
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("hanielazevedo/brazil-cnpj-company-lookup").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 = { "cnpjs": [
        "33.000.167/0001-01",
        "00000000000191",
        "60701190000104",
    ] }

# Run the Actor and wait for it to finish
run = client.actor("hanielazevedo/brazil-cnpj-company-lookup").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 '{
  "cnpjs": [
    "33.000.167/0001-01",
    "00000000000191",
    "60701190000104"
  ]
}' |
apify call hanielazevedo/brazil-cnpj-company-lookup --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,hanielazevedo/brazil-cnpj-company-lookup"
        }
    }
}
```

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/pBOw6lw13hTgWQzeZ/builds/XRV8NnhkNmEr2IaWl/openapi.json
