If you sell to, audit, or onboard Brazilian businesses, sooner or later you need to check a CNPJ (the 14-digit company registry number) and pull the official company data behind it: legal name, status, size, activity code, address.
The data comes from Receita Federal open data, and there is a free public API in front of it, BrasilAPI. Here is a small, honest walkthrough: validate the number first, then fetch the record.
Step 1: validate the check digits offline
A CNPJ has two check digits. Validating them locally saves requests and catches typos before you hit any API.
import re def valid_cnpj(raw: str) -> bool: d = re.sub(r"\D", "", raw) if len(d) != 14 or len(set(d)) == 1: return False def dv(nums, weights): s = sum(int(n) * w for n, w in zip(nums, weights)) r = s % 11 return "0" if r < 2 else str(11 - r) w1 = [5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2] w2 = [6] + w1 return d[12] == dv(d[:12], w1) and d[13] == dv(d[:13], w2) print(valid_cnpj("00.000.000/0001-91")) # True print(valid_cnpj("00.000.000/0001-92")) # False Step 2: fetch the company record
import re, time, requests def get_company(cnpj: str) -> dict: d = re.sub(r"\D", "", cnpj) if not valid_cnpj(d): return {"cnpj": d, "error": "invalid_check_digits"} r = requests.get(f"https://brasilapi.com.br/api/cnpj/v1/{d}", timeout=30) if r.status_code == 404: return {"cnpj": d, "error": "not_found"} r.raise_for_status() j = r.json() return { "cnpj": d, "status": j.get("descricao_situacao_cadastral"), "legal_name": j.get("razao_social"), "opened": j.get("data_inicio_atividade"), "main_activity": j.get("cnae_fiscal_descricao"), "city": j.get("municipio"), "state": j.get("uf"), } for c in ["00.000.000/0001-91", "33.000.167/0001-01"]: print(get_company(c)) time.sleep(1) # be gentle: it is a free public API Things worth knowing
- Throttle yourself. It is a free community API. About one request per second is polite; for thousands of numbers, run it as a slow batch job.
- Check field names against the live response. Upstream fields can change, so print one raw JSON record before relying on specific keys.
- Mind personal data. Sole proprietors (MEI) are registered under a person's name, sometimes with CPF digits. If you store results, decide up front whether to drop those rows.
- Freshness depends on the official source, not on your code.
If you would rather not run the batch yourself
Full disclosure: I built a small tool that does exactly the above as a hosted job: paste a list of CNPJs, get clean JSON back, with invalid numbers and sole proprietors skipped and not charged. It is on Apify as Brazil CNPJ Lookup (pay per result, $0.004 per record). But the code above is enough for most small jobs, and it is free.
Questions or other public registries you would like a walkthrough for? Tell me in the comments.
