A company's data by its CUI, from code: PHP, Python, JavaScript, Google Sheets, Excel
Every example asks for the data of the company with the CUI 13548146. You need an API key, which you create in your account; the account is free. The key is sent in the Authorization: Bearer ... header, and in the examples it is taken from the environment variable APIFIRME_API_KEY.
Do not put the key in a web page or in an app that others download: whoever sees it can use it. Keep it on the server. A key that got out is revoked in the account, and you make another.
The responses to handle
| Code | What it means and what to do |
|---|---|
200 | The company's data, as JSON. |
202 | The company was not with us yet and is being looked up at ANAF right now. Ask again after the number of seconds in the Retry-After header; it is not counted. |
404 | There is no taxpayer with this CUI. |
400 | The CUI is not valid; detail says why. |
401 | The key is missing or wrong. |
429 | You went over the limit per minute or the month's requests; the Retry-After header says how long to wait. It is not counted. |
Errors have their body in the RFC 7807 format: title and detail say what happened.
curl
curl https://api.apifirme.dev/rest/v1/companies/13548146 \
-H "Authorization: Bearer $APIFIRME_API_KEY"
PHP
With the curl extension, from PHP 7.4 on:
<?php
// APIFIRME_API_KEY=af_live_... php firma.php
function apifirme(string $path): array
{
for ($attempt = 1; $attempt <= 5; $attempt++) {
$retryAfter = 1;
$ch = curl_init('https://api.apifirme.dev/rest/v1/' . $path);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . getenv('APIFIRME_API_KEY')],
CURLOPT_HEADERFUNCTION => function ($ch, $header) use (&$retryAfter) {
if (stripos($header, 'Retry-After:') === 0) {
$retryAfter = max(1, (int) trim(substr($header, 12)));
}
return strlen($header);
},
]);
$body = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
// 202: the company is being fetched from ANAF; ask again shortly.
if ($status !== 202) {
return [$status, json_decode((string) $body, true)];
}
sleep($retryAfter);
}
return [$status, null];
}
[$status, $company] = apifirme('companies/13548146');
if ($status === 200) {
echo $company['denumire'], ' | ', $company['stare'], ' | VAT: ', var_export($company['scp_tva'], true), PHP_EOL;
} else {
echo 'Error ', $status, ': ', $company['detail'] ?? '', PHP_EOL;
}
Python
With the requests library:
# APIFIRME_API_KEY=af_live_... python3 firma.py
import os
import time
import requests
API = "https://api.apifirme.dev/rest/v1"
HEADERS = {"Authorization": f"Bearer {os.environ['APIFIRME_API_KEY']}"}
def apifirme(path, payload=None):
for _ in range(5):
if payload is None:
response = requests.get(f"{API}/{path}", headers=HEADERS, timeout=30)
else:
response = requests.post(f"{API}/{path}", headers=HEADERS, json=payload, timeout=30)
# 202: the company is being fetched from ANAF; ask again shortly.
if response.status_code != 202:
return response
time.sleep(int(response.headers.get("Retry-After", "1")))
return response
response = apifirme("companies/13548146")
if response.status_code == 200:
company = response.json()
print(company["denumire"], "|", company["stare"], "| VAT:", company["scp_tva"])
else:
print("Error", response.status_code, response.json().get("detail"))
JavaScript (Node.js)
With fetch, from Node.js 18 on, in a .mjs file:
// APIFIRME_API_KEY=af_live_... node firma.mjs
const API = "https://api.apifirme.dev/rest/v1";
async function apifirme(path) {
for (let attempt = 1; ; attempt++) {
const response = await fetch(`${API}/${path}`, {
headers: { Authorization: `Bearer ${process.env.APIFIRME_API_KEY}` },
});
// 202: the company is being fetched from ANAF; ask again shortly.
if (response.status !== 202 || attempt === 5) return response;
const seconds = Number(response.headers.get("Retry-After")) || 1;
await new Promise((resolve) => setTimeout(resolve, seconds * 1000));
}
}
const response = await apifirme("companies/13548146");
const body = await response.json();
if (response.ok) {
console.log(body.denumire, "|", body.stare, "| VAT:", body.scp_tva);
} else {
console.log("Error", response.status, body.detail);
}
From a browser, the key would be visible in the page: the request is made from your server, and the page asks your server.
The check before invoicing
The same function, with invoice-check instead of companies. The response has only what an invoice needs: valid_for_invoicing, vat_number, vat_on_collection, inactive, struck_off, efactura_registered. In Python:
check = apifirme("invoice-check/13548146").json()
if not check["exists"]:
print("No taxpayer with this CUI")
elif not check["valid_for_invoicing"]:
print("Struck off or fiscally inactive:", check["stare"])
else:
print("Invoice to", check["denumire"], check["vat_number"] or "(not VAT-registered)")
What each field means: checking a company by its CUI.
Many companies at once
POST /rest/v1/companies/batch takes up to 100 CUIs and answers from what is already in the database: the companies in data, in the order asked, and in not_stored and incomplete the CUIs you then ask for one at a time (they are looked up at ANAF). Each company returned counts as one request; for the limit per minute, the whole request is one. In Python, with the function above:
result = apifirme("companies/batch", {"cuis": ["13548146", "RO4221306"]}).json()
for company in result["data"]:
print(company["cui"], company["denumire"], company["stare"])
for cui in result["not_stored"] + result["incomplete"]:
print(cui, apifirme(f"companies/{cui}").json().get("denumire"))
print("Not a valid CUI:", result["invalid"])
Google Sheets
A function of your own in the sheet: =APIFIRME(A2) for one CUI or =APIFIRME(A2:A101) for a whole column, with the name, the state and the VAT registration on each row. A column of up to 100 CUIs is a single batch request; only the CUIs we do not have yet are then asked for one at a time.
- In the sheet, open Extensions → Apps Script, delete what is there and paste the code below, with your key instead of
af_live_.... Save. - Still in the editor, choose the function
APIFIRMEand press Run: Google asks you once to allow the script to connect to an external service. Running it from the editor makes no request. - In the sheet, type
=APIFIRME(A2:A101), where column A holds the CUIs. - The sheet recalculates the formula when its cells change, and every calculation costs requests. When you no longer need the data to update, copy the result and paste it as values.
- Whoever can edit the sheet sees the key in the script. Make a key for the sheet alone, which you can revoke at any time.
const APIFIRME_API_KEY = "af_live_...";
/**
* Name, state and VAT registration for one CUI or a column of up to 100.
* @param {string|Array<Array<string>>} cuis A CUI or a range of CUIs.
* @return The name, state and VAT registration, one row per CUI.
* @customfunction
*/
function APIFIRME(cuis) {
const rows = Array.isArray(cuis) ? cuis.map((row) => row[0]) : [cuis];
const clean = (cui) => (cui == null ? "" : String(cui)).trim().toUpperCase().replace(/^RO\s*/, "");
const asked = rows.map(clean).filter((cui) => cui !== "");
if (asked.length === 0) return "";
if (asked.length > 100) return "At most 100 CUIs at a time";
const response = UrlFetchApp.fetch("https://api.apifirme.dev/rest/v1/companies/batch", {
method: "post",
contentType: "application/json",
headers: { Authorization: "Bearer " + APIFIRME_API_KEY },
payload: JSON.stringify({ cuis: asked }),
muteHttpExceptions: true,
});
const body = JSON.parse(response.getContentText());
if (response.getResponseCode() !== 200) return "Error: " + (body.detail || response.getResponseCode());
const found = {};
body.data.forEach((company) => (found[String(company.cui)] = company));
// Not with us yet, or incomplete: asked for alone, which looks them up at ANAF.
body.not_stored.concat(body.incomplete).forEach((cui) => {
const one = UrlFetchApp.fetch("https://api.apifirme.dev/rest/v1/companies/" + cui, {
headers: { Authorization: "Bearer " + APIFIRME_API_KEY },
muteHttpExceptions: true,
});
if (one.getResponseCode() === 200) found[String(cui)] = JSON.parse(one.getContentText());
if (one.getResponseCode() === 404) found[String(cui)] = null;
});
return rows.map((cui) => {
if (clean(cui) === "") return ["", "", ""];
if (body.invalid.map(String).includes(clean(cui))) return ["not a valid CUI", "", ""];
const company = found[clean(cui)];
if (company === null) return ["no taxpayer with this CUI", "", ""];
if (company === undefined) return ["not available now, try again later", "", ""];
return [company.denumire, company.stare, company.scp_tva ? "VAT" : "no VAT"];
});
}
Excel
With Power Query, in Excel 2016 or Microsoft 365 on Windows, without any add-in. The names below are those of Excel in English; in other languages they are translated (Data → From Web is Date → Din web in Romanian).
- Data → From Web, then choose Advanced.
- Under URL parts, type
https://api.apifirme.dev/rest/v1/companies/13548146. - Under HTTP request header parameters, choose or type
Authorization, and beside itBearer af_live_..., with your key. - When Excel asks how to connect, choose Anonymous: the key in the header is what counts.
- In Power Query, press Into Table, then Close & Load.
The file keeps the key: make a key for it alone, which you can revoke. For a whole column of CUIs, Google Sheets or a program that uses batch works better than one query per company.
Further
- Every request, parameter and field: the API documentation, and the OpenAPI 3.1 description at
https://api.apifirme.dev/openapi.json, from which clients can be generated in any language. - Newly registered companies, filtered by county and activity code:
GET /rest/v1/registrations, described in the documentation; how many there are and the newest, on newly registered companies. - The same data right in Claude, ChatGPT or another AI assistant, without code: apifirme in your AI assistant.
- The plans and their limits: prices.