Ministerio de Hacienda (Costa Rica)
reference Facts, options, APIs
On this page
- Settings
- Vocabulary and Properties
- Request and response
- Properties added by the enricher
- How the script handles input and errors
- Testing the enricher
- Limitations
- Process script
This example looks up an organization’s cédula jurídica (the 10-digit identification number of a legal entity) in the taxpayer register of Costa Rica’s Ministry of Finance (Ministerio de Hacienda) by using its public API. For each golden record it stores the name registered with the tax administration, the tax registration status, the tax regime, whether the taxpayer has overdue debts or missing returns, the tax office, and its economic activities. No API key is needed.
This is the tax administration’s taxpayer record, not the company record of the National Registry (Registro Nacional), which has no public API. It has no incorporation date, registered address, legal representatives, or share capital, and its status is the tax registration status (for example Inscrito), not whether the company is legally active.
Enricher version: V2
API key: not needed
To set up the enricher, see Add REST API enricher, then use the settings and script on this page.
Settings
-
Accepted Business Domain –
/Organization, or the business domain that holds your companies. -
Version – V2 (recommended).
-
API Key – leave empty.
-
Filters – we recommend a rule that only accepts golden records where
organization.cedulaJuridicahas a value. Otherwise, every record without a cédula jurídica is listed on the enricher’s Logs tab as having returned no results.
Vocabulary and Properties
organization.cedulaJuridica
organization.cedulaJuridica holds the 10-digit cédula jurídica, with or without dashes (for example 3-101-005744). If your data uses another vocabulary key, change this field and the CEDULA_JURIDICA_KEY value at the top of the script.
Request and response
Base URL: https://api.hacienda.go.cr
Endpoint: GET /fe/ae?identificacion={cedulaJuridica}
Authentication: none
Rate limits: published in the API documentation: at most 20 requests per second over 5 seconds, and 10 requests per second on average over 2 minutes, per IP address. An IP address that goes over either limit is blocked for 10 minutes. The Ministerio de Hacienda asks API users to cache answers and not to repeat lookups of numbers that don’t exist. Each request takes about 0.4–2 seconds.
The script sends one request per golden record:
GET https://api.hacienda.go.cr/fe/ae?identificacion=3101005744
Accept: application/json
Shortened response (from a real response):
{
"nombre": "PURDY MOTOR SOCIEDAD ANONIMA",
"tipoIdentificacion": "02",
"regimen": { "codigo": 1, "descripcion": "Régimen general" },
"situacion": {
"moroso": "NO",
"omiso": "NO",
"estado": "Inscrito",
"administracionTributaria": "Dirección de Grandes Contribuyentes Nacionales"
},
"actividades": [
{ "estado": "A", "tipo": "P", "codigo": "4520.0", "descripcion": "Mantenimiento y reparación de vehículos automotores" },
{ "estado": "A", "tipo": "S", "codigo": "4774.0", "descripcion": "Venta al por menor de artículos de segunda mano" },
{ "estado": "A", "tipo": "S", "codigo": "7710.1", "descripcion": "Alquiler de automóviles sin conductor" }
]
}
A number that isn’t in the taxpayer register returns HTTP 404:
{ "code": 404, "status": "Information no available on this system, please try again with new values" }
Properties added by the enricher
| Property | Response field | Example |
|---|---|---|
hacienda.identification | the cédula jurídica that was looked up | 3101005744 |
hacienda.name | nombre | PURDY MOTOR SOCIEDAD ANONIMA |
hacienda.identificationType | tipoIdentificacion (02 is Cédula jurídica, 04 is NITE) | Cédula jurídica |
hacienda.taxStatus | situacion.estado | Inscrito |
hacienda.taxRegime | regimen.descripcion | Régimen general |
hacienda.taxRegimeCode | regimen.codigo | 1 |
hacienda.delinquent | situacion.moroso (SI / NO): has overdue tax debts | False |
hacienda.nonFiler | situacion.omiso (SI / NO): has missing tax returns | False |
hacienda.taxOffice | situacion.administracionTributaria | Dirección de Grandes Contribuyentes Nacionales |
hacienda.mainActivityCode | codigo of the active activity whose tipo is P (principal) | 4520.0 |
hacienda.mainActivity | descripcion of that activity (in Spanish) | Mantenimiento y reparación de vehículos automotores |
hacienda.activityCodes | codigo of every active activity (estado A), separated by ; | 4520.0; 4774.0; 7710.1 |
A property is added only when the API returns a value for it. Taxpayers registered by the tax administration itself have the status Inscrito de Oficio, and often no tax office.
If the enricher has a Preview tab, the results appear there first. To add them to golden records, go to the Map tab, select Map Data, and choose Auto Mapping. Select the business domain, enter a new vocabulary named Hacienda with the key prefix hacienda, and then create the mapping. Auto mapping also uses name as the golden record name, so remove that from the mapping if you want to keep your existing names. Then process the data on the Process tab. If the enricher has no Preview tab, the properties are added to the golden record as soon as it is enriched.
How the script handles input and errors
-
Spaces, dots and dashes are removed, so
3-101-005744is looked up as3101005744. Golden records without a 10-digit number that doesn’t start with 0 are skipped without calling the API. The cédula jurídica has no check digit, so a mistyped number is only caught by the API. Personal identification numbers (9-digit cédula física, DIMEX) are not looked up. -
If the number isn’t in the taxpayer register (HTTP 404), the script logs it and adds nothing.
-
If the API doesn’t accept the number (HTTP 400 or 403, with an HTML page), the script logs it and adds nothing. HTTP 403 for a valid number can also mean that the API has blocked the CluedIn server’s IP address for 10 minutes.
-
If the API reports that it is too busy (HTTP 429), the script throws an error that makes the enricher try the golden record again later.
-
Successful results are cached for 24 hours per number. Not-found answers and errors aren’t cached. To change this, edit
CACHE_MILLISECONDSin the script.
Testing the enricher
-
Test connection checks only that the script runs. It doesn’t call the API.
-
To try the setup, create a golden record with
organization.cedulaJuridicaset to3101005744(Purdy Motor S.A.) or3101000046(Compañía Nacional de Fuerza y Luz S.A.).
Limitations
-
The data comes from the tax administration, not the Registro Nacional. It doesn’t say whether a company is legally active, dissolved or merged; a company can still be
Inscritofor tax purposes, and the API has no incorporation date, address, directors, or capital. -
The rate limits apply per IP address, and an IP address that goes over them is blocked for 10 minutes. Enrich large numbers of golden records in smaller batches, keep the cache on, and use a filter so that records without a cédula jurídica aren’t sent. The Ministerio de Hacienda lists repeated lookups of numbers that don’t exist as a common cause of blocks.
-
Activity codes and descriptions are the tax administration’s, in Spanish.
-
The
mensajefield (a message for electronic invoicing when the status isn’tInscrito) isn’t added.
Process script
// REST API enricher (V2) - Costa Rican taxpayer lookup with the Ministerio de Hacienda
//
// Looks up a golden record's Costa Rican cédula jurídica (legal entity identification number)
// in the taxpayer register of the Ministry of Finance's tax administration (Ministerio de
// Hacienda, Dirección General de Tributación), using its public API
// (https://api.hacienda.go.cr/docs/, endpoint /fe/ae), and adds the result to the golden record
// as hacienda.* properties:
//
// hacienda.identification 10-digit cédula jurídica that was looked up
// hacienda.name name registered with the tax administration
// hacienda.identificationType identification type, for example Cédula jurídica
// hacienda.taxStatus tax registration status, for example Inscrito or Inscrito de Oficio
// hacienda.taxRegime tax regime, for example Régimen General
// hacienda.taxRegimeCode tax regime code, for example 1
// hacienda.delinquent "True" / "False" - has overdue tax debts (moroso)
// hacienda.nonFiler "True" / "False" - has missing tax returns (omiso)
// hacienda.taxOffice tax office that manages the taxpayer (administración tributaria)
// hacienda.mainActivityCode code of the main economic activity, for example 4520.0
// hacienda.mainActivity description of the main economic activity (Spanish)
// hacienda.activityCodes codes of all active economic activities, separated by "; "
//
// This is the tax administration's taxpayer record, not the National Registry (Registro
// Nacional) company record: it has no incorporation date, address, directors or capital. The
// Registro Nacional has no public API.
//
// No API key is needed. See README.md next to this file for the enricher settings.
//
// A record gets no result (nothing is stored) when it has no valid cédula jurídica, when the
// number isn't in the taxpayer register, or when the API can't answer.
// ---- Settings -------------------------------------------------------------------------
// Vocabulary key to read. Add the same key to the Vocabulary and Properties field.
const CEDULA_JURIDICA_KEY = "organization.cedulaJuridica";
const HACIENDA_URL = "https://api.hacienda.go.cr/fe/ae?identificacion=";
// How long to reuse an answer for the same number. 0 turns caching off. The Ministerio de
// Hacienda asks API users to cache answers, and blocks IP addresses that send too many requests.
const CACHE_MILLISECONDS = 24 * 60 * 60 * 1000;
// ---- Script ---------------------------------------------------------------------------
const IDENTIFICATION_TYPES = {
"01": "Cédula física",
"02": "Cédula jurídica",
"03": "DIMEX",
"04": "NITE",
};
function getValue(key) {
// A plain loop rather than vocabularies.find(...): vocabularies is a .NET list, and when
// .find is called from inside a function, later calls return the first call's match.
const items = vocabularies || [];
for (let i = 0; i < items.length; i++) {
if (items[i].Key === key) {
const value = items[i].Value;
return value === null || value === undefined ? "" : String(value).trim();
}
}
return "";
}
// Accepts "3101005744", "3-101-005744", "3 101 005744", etc. Returns the 10 digits, or null when
// it isn't a cédula jurídica (10 digits, not starting with 0). The cédula jurídica has no check
// digit. Personal identification numbers (cédula física, DIMEX) are not looked up.
function parseCedulaJuridica(raw) {
const text = raw.replace(/[\s.\-]/g, "");
return /^[1-9]\d{9}$/.test(text) ? text : null;
}
function clean(value) {
if (value === null || value === undefined) {
return null;
}
const text = String(value).replace(/\s+/g, " ").trim();
return text === "" ? null : text;
}
function parseJson(text) {
try {
return JSON.parse(text);
} catch (e) {
return null;
}
}
function yesNo(value) {
const text = clean(value);
return text === "SI" ? true : text === "NO" ? false : null;
}
// Calls the API. Returns the taxpayer, or null when there's no answer to store.
function lookUp(cedula) {
const apiResponse = http.send({
url: HACIENDA_URL + cedula,
method: "GET",
headers: [{ Key: "Accept", Value: "application/json" }],
});
const status = String(apiResponse.HttpStatus || "");
const body = parseJson(apiResponse.Content);
if (status === "TooManyRequests") {
throw new Error("TooManyRequests - the Ministerio de Hacienda API is busy, the record will be retried");
}
if (status === "OK" && body && clean(body.nombre)) {
return body;
}
// 404: the number isn't in the taxpayer register. 400 and 403 (an HTML page): the API didn't
// accept the number, or has blocked this IP address for sending too many requests.
const detail = body && body.status ? String(body.status) : String(apiResponse.Content || "").substring(0, 200);
log(`Ministerio de Hacienda could not look up ${cedula}. HTTP ${status}. ${detail}`);
return null;
}
function run() {
const cedula = parseCedulaJuridica(getValue(CEDULA_JURIDICA_KEY));
if (!cedula) {
// No valid cédula jurídica on this record (this is also what Test connection hits, because
// it passes placeholder values instead of real ones).
return [];
}
const cacheKey = `hacienda:${cedula}`;
const cached = CACHE_MILLISECONDS > 0 ? cache.get(cacheKey) : null;
let taxpayer = cached ? parseJson(String(cached)) : null;
if (!taxpayer) {
taxpayer = lookUp(cedula);
if (!taxpayer) {
return [];
}
if (CACHE_MILLISECONDS > 0) {
cache.set(cacheKey, JSON.stringify(taxpayer), CACHE_MILLISECONDS);
}
}
const regime = taxpayer.regimen || {};
const situation = taxpayer.situacion || {};
const activities = (Array.isArray(taxpayer.actividades) ? taxpayer.actividades : [])
.filter((x) => x && clean(x.codigo) && clean(x.estado) === "A");
let mainActivity = null;
for (let i = 0; i < activities.length; i++) {
if (clean(activities[i].tipo) === "P") {
mainActivity = activities[i];
break;
}
}
mainActivity = mainActivity || {};
const typeCode = clean(taxpayer.tipoIdentificacion);
const data = {
"hacienda.identification": cedula,
"hacienda.name": clean(taxpayer.nombre),
"hacienda.identificationType": typeCode ? IDENTIFICATION_TYPES[typeCode] || typeCode : null,
"hacienda.taxStatus": clean(situation.estado),
"hacienda.taxRegime": clean(regime.descripcion),
"hacienda.taxRegimeCode": clean(regime.codigo),
"hacienda.delinquent": yesNo(situation.moroso),
"hacienda.nonFiler": yesNo(situation.omiso),
"hacienda.taxOffice": clean(situation.administracionTributaria),
"hacienda.mainActivityCode": clean(mainActivity.codigo),
"hacienda.mainActivity": clean(mainActivity.descripcion),
"hacienda.activityCodes": activities.length > 0 ? activities.map((x) => clean(x.codigo)).join("; ") : null,
};
// Leave out values the register didn't return, so they don't overwrite existing data with blanks.
Object.keys(data).forEach((key) => {
if (data[key] === null) {
delete data[key];
}
});
return [{ Data: data, Score: 100 }];
}
response = JSON.stringify(run());