# Brazil CNPJ → Company Markdown DD Card (`ingenious_quip_bxq/brazil-cnpj-markdown`) Actor

Batch Brazilian CNPJ lookups via BrasilAPI (keyless) with CNPJ.ws / ReceitaWS fallback or your own key. Markdown due-diligence cards: identity, status, CNAE, address, QSA partners, source. RAG chunks. No email/phone output. Failed rows free. 256 MB.

- **URL**: https://apify.com/ingenious_quip_bxq/brazil-cnpj-markdown.md
- **Developed by:** [新世紀書僮](https://apify.com/ingenious_quip_bxq) (community)
- **Categories:** Business, Developer tools, Automation
- **Security:** Limited permissions
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $3.00 / 1,000 cnpj company cards

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

## Brazil CNPJ → Company Markdown DD Card

Turn a list of **Brazilian CNPJs** into clean **company due-diligence cards** — Markdown for humans and LLM/RAG pipelines, structured JSON for your ERP, KYB or vendor-master cleanup.

- **Keyless by default** — uses the public **BrasilAPI** CNPJ JSON (Receita Federal open data), with automatic fallback to **CNPJ.ws** and **ReceitaWS** public endpoints
- **Bring your own key** for production volume — ReceitaWS token or CNPJ.ws commercial token
- **Markdown card per company**: Identity · Status · CNAE · Address · QSA (partners) · Source attribution
- **RAG chunks** (`CHUNKS.jsonl`) — one self-describing chunk per card section, ready to embed
- **No contact harvesting** — email, telephone, fax and DDD fields are stripped from every provider payload. This is a due-diligence tool, not a lead list.
- **256 MB** default memory, no browser, official/public JSON APIs only
- **Failed rows are free** — invalid CNPJ, not found, rate-limited, provider errors

### Quick start

```json
{
  "cnpjs": ["33.000.167/0001-01", "00.000.000/0001-91"]
}
```

That is all you need — `provider: auto` tries BrasilAPI first and falls back automatically.

### Input

| Field | Type | Default | Notes |
|---|---|---|---|
| `cnpjs` | string\[] | — | Punctuation OK. Digits-only values shorter than 14 are left-padded with zeros (spreadsheets drop them). Check digits are validated; invalid rows are free. Supports the 2026 alphanumeric CNPJ format. |
| `datasetId` | string | — | Read CNPJs from another run's dataset (`cnpjField`, else `cnpj` / `CNPJ` / `taxId` / `documento`) |
| `keyValueStoreId` + `keyValueRecordKey` | string | `INPUT_CNPJS` | JSON array, `{"cnpjs": [...]}` or one CNPJ per line |
| `cnpjField` | string | — | Field name in dataset items / JSON objects |
| `provider` | enum | `auto` | `auto` · `brasilapi` · `cnpjws` · `receitaws` |
| `apiKey` | secret | — | Optional ReceitaWS token (`Authorization: Bearer`) or CNPJ.ws commercial token (`x_api_token`) |
| `keyProvider` | enum | `receitaws` | Which provider your key belongs to in `auto` mode |
| `stopOnAuthError` | boolean | true | After a 401/403 from the keyed provider, skip it for the remaining CNPJs |
| `includeQsa` | boolean | true | Partners/administrators: **name, role, entry date only** |
| `includeRagChunks` | boolean | true | Write `CHUNKS.jsonl` |
| `maxItems` | integer | 100 | 0 = no limit |
| `maxConcurrency` | integer | 2 | 1–5 |
| `maxRetries` | integer | 3 | 429 (honours `Retry-After`), 5xx, timeouts |
| `requestTimeoutSecs` | integer | 30 | Per HTTP call |

#### Provider order (`auto`)

1. **BrasilAPI** `https://brasilapi.com.br/api/cnpj/v1/{cnpj}` (keyless)
2. With `apiKey`: your keyed provider (ReceitaWS or CNPJ.ws commercial). Without: **CNPJ.ws** public
3. The remaining keyless endpoint (ReceitaWS or CNPJ.ws public)

Keyless CNPJ.ws / ReceitaWS endpoints are rate-limited (about 3 requests/minute), which is why they are fallbacks only.

### Output

**Dataset** — one row per CNPJ:

`cnpj`, `cnpjFormatted`, `razaoSocial`, `nomeFantasia`, `matrizFilial`, `situacao`, `situacaoDate`, `situacaoMotivo`, `situacaoEspecial`, `dataInicioAtividade`, `naturezaJuridica {code, description}`, `porte`, `capitalSocial`, `cnaePrincipal {code, codeFormatted, description}`, `cnaesSecundarios[]`, `address {tipoLogradouro, logradouro, numero, complemento, bairro, municipio, uf, cep, codigoMunicipioIbge}`, `addressLine`, `simples`, `mei`, `qsa[] {name, role, since}`, `qsaCount`, `markdown`, `source`, `sourceUrl`, `sourceUpdatedAt`, `triedSources`, `status`, `errorClass`, `errorMessage`, `hint`.

Views: **Overview** and **Failed (not charged)**.

**Key-value store**:

- `REPORT.md` — all cards + a failed table
- `CHUNKS.jsonl` — `{id, cnpj, razaoSocial, section, source, text, chunkIndex, chunkCount}` per line
- `SUMMARY` / `OUTPUT` — counts by result class and source, charged events, duration, peak memory

#### Example card (excerpt)

```markdown
### PETROLEO BRASILEIRO S A PETROBRAS

**CNPJ** `33.000.167/0001-01` · **ATIVA** · source: BrasilAPI

#### CNAE (economic activity)

- **Principal:** `0600-0/01` — Extração de petróleo e gás natural
- **Secundários (5):** …

#### Address

AVENIDA REPUBLICA DO CHILE, 65 — CENTRO — RIO DE JANEIRO/RJ — CEP 20031-170
```

`errorClass` values: `invalid_input`, `not_found`, `rate_limited`, `unauthorized`, `forbidden`, `server_error`, `timeout`, `network`, `bad_response`, `skipped_auth`.

### Privacy

- Email, telephone, fax and DDD fields are **dropped** from every provider payload before processing, and every output string is scrubbed for email addresses.
- QSA contains **names and roles only** (plus entry date when the source has it) — no masked CPF fragments, no age bands, no contact data.
- Your `apiKey` is stored encrypted by Apify and is never logged or written to output.

### Pricing (pay per event)

| Event | Price | When |
|---|---|---|
| Actor start | $0.001 | once per run |
| `cnpj-card` | $0.003 | per **successful** company card |

Invalid CNPJs, not found, rate-limited after retries, auth errors and provider failures are **free**.

### Data sources

Company data originates from the **Receita Federal do Brasil** CNPJ open-data release, served by BrasilAPI, CNPJ.ws and ReceitaWS. Each card names the provider and endpoint it came from. Use of a keyed provider follows that provider's own terms.

# Changelog

This Actor's version history is a separate document: https://apify.com/ingenious_quip_bxq/brazil-cnpj-markdown/changelog.md

# Actor input Schema

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

One CNPJ per line, e.g. 33.000.167/0001-01 or 33000167000101. Punctuation and spaces are stripped, numbers shorter than 14 digits are left-padded with zeros, check digits are validated (invalid rows are free). Duplicates dropped.

## `datasetId` (type: `string`):

Optional. Read CNPJs from another run's dataset (field from 'CNPJ field', else cnpj / CNPJ / taxId / documento).

## `keyValueStoreId` (type: `string`):

Optional. Read CNPJs from a key-value record: JSON array, {"cnpjs": \[...]}, or plain text with one CNPJ per line.

## `keyValueRecordKey` (type: `string`):

Record key inside the key-value store.

## `cnpjField` (type: `string`):

Optional. Name of the field holding the CNPJ in dataset items or JSON objects.

## `provider` (type: `string`):

auto = BrasilAPI first, then (with apiKey) your keyed provider, then the remaining keyless public endpoint. brasilapi / cnpjws / receitaws = that provider only (cnpjws and receitaws use your apiKey when given, else their rate-limited public endpoints).

## `apiKey` (type: `string`):

Optional ReceitaWS token (sent as Authorization: Bearer) or CNPJ.ws commercial token (sent as x_api_token to comercial.cnpj.ws). Not needed for BrasilAPI. Stored encrypted, never logged or output. Placeholders like YOUR_KEY are ignored.

## `keyProvider` (type: `string`):

Which provider your apiKey is for when provider=auto.

## `stopOnAuthError` (type: `boolean`):

After the keyed provider returns 401/403 once, skip it for the remaining CNPJs (auto mode keeps using keyless providers). Failed rows are free.

## `includeQsa` (type: `boolean`):

Add a QSA summary: names, roles and entry date only. No CPF fragments, ages or contact details.

## `includeRagChunks` (type: `boolean`):

Write one self-describing chunk per card section to the key-value store record CHUNKS.jsonl.

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

Stop after this many unique valid CNPJs (0 = no limit).

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

Parallel lookups. Public endpoints are rate-limited; 2 is a safe default.

## `maxRetries` (type: `integer`):

Retries per provider for HTTP 429 (honours Retry-After, capped at 30 s), 5xx, timeouts and network errors. 400/401/403/404 are not retried.

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

Timeout for each provider HTTP call.

## Actor input object example

```json
{
  "cnpjs": [
    "33000167000101"
  ],
  "keyValueRecordKey": "INPUT_CNPJS",
  "provider": "auto",
  "keyProvider": "receitaws",
  "stopOnAuthError": true,
  "includeQsa": true,
  "includeRagChunks": true,
  "maxItems": 100,
  "maxConcurrency": 2,
  "maxRetries": 3,
  "requestTimeoutSecs": 30
}
```

# Actor output Schema

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

Dataset items: cnpj, razaoSocial, nomeFantasia, situacao, CNAE principal + secundários, address, capitalSocial, QSA summary, markdown, source, errorClass.

## `reportMarkdown` (type: `string`):

Due-diligence cards: Identity, Status, CNAE, Address, QSA, Source attribution.

## `chunks` (type: `string`):

One JSON line per card section with cnpj / section / text, ready to embed.

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

cnpjsOk, cnpjsFailed, byClass, bySource, charged, durationSecs, peakMemoryMb.

# 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": [
        "33000167000101"
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("ingenious_quip_bxq/brazil-cnpj-markdown").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": ["33000167000101"] }

# Run the Actor and wait for it to finish
run = client.actor("ingenious_quip_bxq/brazil-cnpj-markdown").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": [
    "33000167000101"
  ]
}' |
apify call ingenious_quip_bxq/brazil-cnpj-markdown --silent --output-dataset

```

## MCP server setup

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

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/JYu9qJgSI30N3MNVV/builds/ccUfMh5UOsLTtk24f/openapi.json
