Skip to content
First API request with curl and JavaScript
API

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 curl or a backend running Node.js 18 or later, which includes fetch.

Creating an API key

  1. Open Settings > API keys and click Create key.
  2. Name the key after the application that will use it, such as “Production server”, and click Create key.
  3. Click the Copy key icon and store the key on the application’s server, in an environment variable such as CNPJA_API_KEY or in a secrets manager.

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://api.cnpja.com, 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 Bearer before the key. The whole header value is treated as the key, so Bearer YOUR_API_KEY is rejected with 401 API_KEY_INVALID, as explained in Sending the key.

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
ElementValue
taxId, in the pathCNPJ with 14 characters, no punctuation and uppercase letters in an alphanumeric CNPJ
AuthorizationAPI key, required outside public access
Accept-LanguageOptional: pt-BR (default) or en-US, the language of display texts, as explained in Response format
Accept-EncodingOptional: 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.ok accepts any 2xx status, including the 206 of 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 504 REQUEST_TIMED_OUT. 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.

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"
  }
}
FieldContent
updatedAtDate and time of the last update of the registration data from the Receita Federal
taxIdCNPJ looked up, with no punctuation
incorporationDateOpening date, in the YYYY-MM-DD format
typeHead office (HEAD) or branch (BRANCH)
statusRegistration status, such as ACTIVE or CLOSED
companyData of the company, shared by all of its establishments, such as the legal name and size
addressRegistered address, with the municipality’s IBGE code in municipality
  • Every object with code and label holds a stable code for program logic and a display-only text that changes with the language. Base the logic on code, 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 valueAdds
company.taxRegimeThe company’s tax regime and its options for the Simples Nacional, SIMEI and the IBS and CBS regular regime
stateRegistryThe establishment’s state registrations
suframaSUFRAMA registrations
address.coordinatesLatitude 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.taxRegime:

{
  "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.taxRegime,stateRegistry, or by repeating the parameter.
  • Parameters that configure a resource, such as company.taxRegime.view, are accepted only with that resource in expand. Without it, the response is 400 REQUEST_VALIDATION_FAILED, with the DEPENDENCIES code in errors.
  • Requests without a key accept neither expand nor any other query parameter and, with them, receive 401 API_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.

StatusCodeCauseAction
400REQUEST_VALIDATION_FAILEDCNPJ with punctuation, lowercase letters, a length other than 14 or invalid check digitsSend the 14 characters with no punctuation and check the number
400REQUEST_VALIDATION_FAILEDMisspelled parameter (ADDITIONAL_PROPERTIES in errors) or a parameter without its resource in expand (DEPENDENCIES)Check the spelling of the parameters and the value of expand
401API_KEY_MISSINGMissing or empty Authorization header, such as an unset environment variable, or a request without a key that has query parameters, such as expandCheck that the key reaches the header, or remove the parameters from a request without a key
401API_KEY_INVALIDBearer before the key, or an incomplete keySend only the full key as the Authorization value
401API_KEY_REVOKEDRevoked keyUse another active key of the organization or create a new one
402CACHED_QUERY_QUOTA_EXCEEDED, LIVE_QUERY_QUOTA_EXCEEDED or OVERAGE_BUDGET_EXCEEDEDThe organization’s quota or overage budget is used up. What each code means is in Error codesFollow one of the ways out in Quota used up
404ESTABLISHMENT_NOT_FOUNDCNPJ not in the Receita Federal registryCheck the number and repeat the lookup only when the registration may have changed
429RATE_LIMIT_EXCEEDED or CONCURRENCY_LIMIT_EXCEEDEDRequests per second or concurrent requests above the limitReduce the pace or parallelism and retry after a short wait
500 or 504UNEXPECTED_ERROR or REQUEST_TIMED_OUTFailure on the API side or a request over 60 secondsRetry 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

Informational content that may change without notice. It is not tax, accounting or legal advice, and CNPJá's terms and policies prevail over this page.