Look up CNPJ in Python
This guide shows how to look up a CNPJ with the CNPJAPI REST API in Python, using the requests library. The response comes as JSON, with fields in PascalCase (RazaoSocial, SituacaoCadastral, ...).
Prerequisites
- Python 3.8+ and the
requestslibrary (pip install requests). - An API key from CNPJAPI. Create your account at https://app.cnpjapi.com.br and generate the key (see Authentication).
Simple lookup
import requests
CNPJ = "00776574000156" # only the 14 digits, without punctuation
API_KEY = "cnpj_sua_chave"
resposta = requests.get(
f"https://api.cnpjapi.com.br/{CNPJ}",
headers={"Authorization": f"Bearer {API_KEY}"},
timeout=10,
)
resposta.raise_for_status()
empresa = resposta.json()
print(empresa["RazaoSocial"])
print(empresa["SituacaoCadastral"]["Descricao"])
print(empresa["AtividadePrincipal"]["Descricao"])
Handling errors and rate limits
When you exceed the per-minute limit or the monthly quota, the API responds 429 with a Retry-After header (seconds). Treat it as recoverable:
import time
resposta = requests.get(
f"https://api.cnpjapi.com.br/{CNPJ}",
headers={"Authorization": f"Bearer {API_KEY}"},
timeout=10,
)
if resposta.status_code == 429:
espera = int(resposta.headers.get("Retry-After", "60"))
time.sleep(espera)
# retry...
elif resposta.status_code == 404:
print("CNPJ não encontrado na base pública")
elif resposta.ok:
empresa = resposta.json()
print(empresa["RazaoSocial"])
else:
resposta.raise_for_status()
State Registration (IE, premium)
On a plan that includes State Registration (IE), look up a company's IE from the official SEFAZ source. Pass uf for a single state (1 credit) or omit it for the nationwide sweep (3 credits):
resposta = requests.get(
f"https://api.cnpjapi.com.br/consulta/ie/{CNPJ}",
params={"uf": "SP"},
headers={"Authorization": f"Bearer {API_KEY}"},
timeout=15,
)
resposta.raise_for_status()
for ie in resposta.json()["resultados"]:
print(ie["uf"], ie["ie"], ie["situacao"])
Full contract (fields, coverage, credits) at Look up the State Registration.
Next steps
Create your free account at https://app.cnpjapi.com.br and make your first lookup in minutes.