First API request with curl and JavaScript
From account to your first API response: create an API key, look up a CNPJ, read the JSON, request optional resources and see what the request consumed.
This guide takes you from a CNPJá account to the first API response authenticated with an API key: creating the key, sending a CNPJ lookup with curl and JavaScript, reading the response, requesting an optional resource and checking what the request consumed. Lookup CNPJ and Lookup CEP also accept requests without a key, as described in Public API access, no key.
Prerequisites
- Account and organization. You need a CNPJá account (Sign up) and access to an organization, which owns the keys, the quota and the limits, as explained in Organizations.
- A role that manages keys. Owner, Administrator or Developer. With any other role, ask someone who has one of them to create the key, or ask for your role to be changed, as described in Members and roles.
- A runtime environment. A terminal with
curlor a backend running Node.js 18 or later, which includesfetch.
Creating an API key
- Open Settings > API keys and click Create key.
- Name the key after the application that will use it, such as “Production server”, and click Create key.
- Click the Copy key icon and store the key on the application’s server, in an environment variable such as
CNPJA_or in a secrets manager.API_ KEY
The full key is shown only once and cannot be retrieved later. The full steps are in Create a key, and the current active key limit is in Usage limits.
Sending the first request
The API receives requests over HTTPS at the base URL https:/, and every operation is under the /v2 prefix. The key goes as the entire value of the Authorization header, with no prefix.
Important: do not write
Bearerbefore the key. The whole header value is treated as the key, soBearer YOUR_is rejected withAPI_ KEY 401API_, as explained in Sending the key.KEY_ INVALID
The example uses Lookup CNPJ, which returns the Receita Federal registration of a CNPJ with the company data:
GET /v2/establishments/37335118000180 HTTP/1.1
Host: api.cnpja.com
Authorization: YOUR_API_KEY | Element | Value |
|---|---|
taxId, in the path | CNPJ with 14 characters, no punctuation and uppercase letters in an alphanumeric CNPJ |
Authorization | API key, required outside public access |
Accept-Language | Optional: pt-BR (default) or en-US, the language of display texts, as explained in Response format |
Accept-Encoding | Optional: zstd, br, gzip or deflate, to receive a compressed response |
With curl
curl https://api.cnpja.com/v2/establishments/37335118000180 \
-H "Authorization: $CNPJA_API_KEY" With JavaScript
Run the call on the backend, never in the browser or in a mobile app, where any user can extract the key:
const response = await fetch('https://api.cnpja.com/v2/establishments/37335118000180', {
headers: { Authorization: process.env.CNPJA_API_KEY },
signal: AbortSignal.timeout(70_000),
});
const body = await response.json();
if (!response.ok) {
throw new Error(`${body.code}: ${body.message}`);
}
console.log(body.company.legalName); response.accepts anyok 2xxstatus, including the206of a partial success, which must also be treated as success.- A live query at the Receita Federal can take a few seconds, and each request has up to 60 seconds to finish, or the API responds
504REQUEST_. Keep the HTTP client timeout above 60 seconds, such as the 70 seconds in the example, to receive that response instead of closing the connection first.TIMED_ OUT
Response
The 200 response holds the establishment’s registration, trimmed here:
{
"updatedAt": "2026-01-27T03:00:00.000Z",
"taxId": "37335118000180",
"incorporationDate": "2020-06-05",
"type": { "code": "HEAD", "label": "Matriz" },
"tradeName": "Cnpja",
"status": { "code": "ACTIVE", "label": "Ativa" },
"company": {
"id": "37335118",
"legalName": "CNPJA TECNOLOGIA LTDA",
"size": { "code": "SMALL", "label": "Empresa de Pequeno Porte" }
},
"address": {
"city": "São Paulo",
"state": "SP",
"municipality": "3550308"
}
} | Field | Content |
|---|---|
updatedAt | Date and time of the last update of the registration data from the Receita Federal |
taxId | CNPJ looked up, with no punctuation |
incorporationDate | Opening date, in the YYYY-MM-DD format |
type | Head office (HEAD) or branch (BRANCH) |
status | Registration status, such as ACTIVE or CLOSED |
company | Data of the company, shared by all of its establishments, such as the legal name and size |
address | Registered address, with the municipality’s IBGE code in municipality |
- Every object with
codeandlabelholds a stable code for program logic and a display-only text that changes with the language. Base the logic oncode, as explained in Codes and labels. - Without query parameters, the API applies its defaults:
maxAge=45d, that is, data up to 45 days old, and no optional resources. The age rules are in Max age and partial success.
Phones, e-mails, economic activities, partners and the other fields are in CNPJ lookup in the API and in the Reference.
Optional resources
Some resources are left out of the default response and are included only when requested in the expand parameter. Each resource is charged separately and may need a live query.
expand value | Adds |
|---|---|
company. | The company’s tax regime and its options for the Simples Nacional, SIMEI and the IBS and CBS regular regime |
stateRegistry | The establishment’s state registrations |
suframa | SUFRAMA registrations |
address. | Latitude and longitude of the address, described in Location and maps in the API |
This request adds the tax regime:
curl "https://api.cnpja.com/v2/establishments/37335118000180?expand=company.taxRegime" \
-H "Authorization: $CNPJA_API_KEY" The expand value is also the path of the field it adds, company.:
{
"company": {
"taxRegime": {
"updatedAt": "2026-01-27T03:00:00.000Z",
"type": { "code": "PRESUMED_PROFIT", "label": "Lucro Presumido" }
}
}
} - Send several values separated by commas, such as
expand=company., or by repeating the parameter.taxRegime,stateRegistry - Parameters that configure a resource, such as
company., are accepted only with that resource intaxRegime. view expand. Without it, the response is400REQUEST_, with theVALIDATION_ FAILED DEPENDENCIEScode inerrors. - Requests without a key accept neither
expandnor any other query parameter and, with them, receive401API_.KEY_ MISSING
The parameters of each resource are in CNPJ lookup in the API.
Request consumption
API usage is measured in live queries and cached queries, and each resource of the response is charged separately. The example request consumes one cached query when the registration data is within the max age, or one live query when the API has to fetch it from the Receita Federal, and each resource requested in expand is charged on top. The rules are in the metering rules, under CNPJ lookup, and what is not charged, such as rejections, failures and public access, under What is not charged.
Responses carry no cost or balance headers. Usage shows up in Settings > Requests, with the status, consumption and trace ID of each request, and in Settings > Usage, with the period’s total by type and by member or key. Who can see these pages and how to filter them are covered in Track usage.
Frequent errors
Every error response has a 4xx or 5xx status and a JSON body in the same shape:
{
"status": 400,
"code": "REQUEST_VALIDATION_FAILED",
"traceId": "4bf92f3577b34da6a3ce929d0e0e4736",
"message": "company.taxRegime.view requires company.taxRegime to be present at expand",
"errors": [
{
"field": "company.taxRegime.view",
"code": "DEPENDENCIES",
"message": "Requires company.taxRegime to be present at expand"
}
]
} Base error handling on code, never on message, which is meant for display only. Keep the traceId: it identifies the request when you contact us.
| Status | Code | Cause | Action |
|---|---|---|---|
400 | REQUEST_ | CNPJ with punctuation, lowercase letters, a length other than 14 or invalid check digits | Send the 14 characters with no punctuation and check the number |
400 | REQUEST_ | Misspelled parameter (ADDITIONAL_ in errors) or a parameter without its resource in expand (DEPENDENCIES) | Check the spelling of the parameters and the value of expand |
401 | API_ | Missing or empty Authorization header, such as an unset environment variable, or a request without a key that has query parameters, such as expand | Check that the key reaches the header, or remove the parameters from a request without a key |
401 | API_ | Bearer before the key, or an incomplete key | Send only the full key as the Authorization value |
401 | API_ | Revoked key | Use another active key of the organization or create a new one |
402 | CACHED_, LIVE_ or OVERAGE_ | The organization’s quota or overage budget is used up. What each code means is in Error codes | Follow one of the ways out in Quota used up |
404 | ESTABLISHMENT_ | CNPJ not in the Receita Federal registry | Check the number and repeat the lookup only when the registration may have changed |
429 | RATE_ or CONCURRENCY_ | Requests per second or concurrent requests above the limit | Reduce the pace or parallelism and retry after a short wait |
500 or 504 | UNEXPECTED_ or REQUEST_ | Failure on the API side or a request over 60 seconds | Retry with increasing intervals |
429, 500 and 504 errors are usually temporary and can be retried unchanged. The others are not fixed by retrying the same request: fix the request or check the CNPJ first and, on a 402, follow the ways out in Quota used up. An unknown code must be handled by its HTTP status. Limits, the full error format and retries are in Limits and errors.
Next steps
- CNPJ lookup in the API: every registration field and the parameters of the optional resources.
- CNPJ search and lists in the API: establishments by filters, without knowing the CNPJ.
- Max age and partial success:
maxAgeand the206status. The concept of live and cached queries is in Data freshness. - Response format: structure, missing values, language and pagination.
- Queries and quota: the two units, the organization’s quota, packs and budget.
- Limits and errors: request limits, timeout and retries.
- Authentication: sending, rotating and revoking keys.
- Reference: every operation, parameter and response. Trying an operation in the Reference with your key consumes the organization’s quota like any request, under the Metering Rules.