Look up CNPJ in PHP
This guide shows how to look up a CNPJ with the CNPJAPI REST API in PHP, using cURL (available by default). The response comes as JSON, with fields in PascalCase (RazaoSocial, SituacaoCadastral, ...).
Prerequisites
- PHP 8.0+ with the cURL extension enabled.
- An API key from CNPJAPI. Create your account at https://app.cnpjapi.com.br and generate the key (see Authentication).
Simple lookup
<?php
$cnpj = '00776574000156'; // only the 14 digits, without punctuation
$apiKey = 'cnpj_sua_chave';
$ch = curl_init("https://api.cnpjapi.com.br/{$cnpj}");
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => ["Authorization: Bearer {$apiKey}"],
CURLOPT_TIMEOUT => 10,
]);
$body = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($status === 200) {
$empresa = json_decode($body, true);
echo $empresa['RazaoSocial'], PHP_EOL;
echo $empresa['SituacaoCadastral']['Descricao'], PHP_EOL;
}
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). To read it, capture the response headers:
<?php
$ch = curl_init("https://api.cnpjapi.com.br/{$cnpj}");
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HEADER => true, // include the headers in the return value
CURLOPT_HTTPHEADER => ["Authorization: Bearer {$apiKey}"],
]);
$resposta = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$tamanhoCabecalho = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
curl_close($ch);
if ($status === 429) {
$cabecalhos = substr($resposta, 0, $tamanhoCabecalho);
preg_match('/retry-after:\s*(\d+)/i', $cabecalhos, $m);
$espera = (int) ($m[1] ?? 60);
sleep($espera);
// retry...
} elseif ($status === 404) {
echo 'CNPJ não encontrado na base pública', PHP_EOL;
}
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):
<?php
$ch = curl_init("https://api.cnpjapi.com.br/consulta/ie/{$cnpj}?uf=SP");
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => ["Authorization: Bearer {$apiKey}"],
CURLOPT_TIMEOUT => 15,
]);
$body = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($status === 200) {
$ie = json_decode($body, true);
foreach ($ie['resultados'] as $r) {
echo $r['uf'], ' ', $r['ie'], ' ', $r['situacao'], PHP_EOL;
}
}
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.