data.egov.kz legal entities (Kazakhstan)

reference Facts, options, APIs

On this page

This example looks up a Kazakh business identification number (BIN) in the registration data of legal entities, branches and representative offices (dataset gbd_ul) that the Ministry of Justice publishes on the national open data portal, data.egov.kz. It uses the portal’s API version 4. For each golden record it stores the name, status, registration date, legal address and main activity, in Russian and in Kazakh, and the full name of the head of the entity.

Enricher version: V2
API key: your data.egov.kz API key (free; sign in to data.egov.kz and get the key from For developers › Developer cabinet)

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 – your data.egov.kz API key. The script sends it in the apiKey query parameter. If the field is empty, the script adds nothing and doesn’t call the portal.

  • Filters – we recommend a rule that only accepts golden records where organization.bin has a value. Otherwise, every record without a BIN is listed on the enricher’s Logs tab as having returned no results.

Vocabulary and Properties

organization.bin

organization.bin holds the 12-digit BIN (БИН / БСН), for example 940140000385. If your data uses another vocabulary key, change this field and the BIN_KEY value at the top of the script.

Request and response

Base URL: https://data.egov.kz/api/v4
Endpoint: GET /gbd_ul/v1?apiKey=<key>&source=<query>
Authentication: API key in the apiKey query parameter
Rate limits: none published. Requests take about 1.5–2.5 seconds.

The portal’s search is built on Elasticsearch. source is a JSON search query, URL-encoded; the script asks for the records whose bin matches:

{ "size": 10, "query": { "bool": { "must": [{ "match": { "bin": "940140000385" } }] } } }
GET https://data.egov.kz/api/v4/gbd_ul/v1?apiKey=<your API key>&source=%7B%22size%22%3A10%2C%22query%22%3A%7B%22bool%22%3A%7B%22must%22%3A%5B%7B%22match%22%3A%7B%22bin%22%3A%22940140000385%22%7D%7D%5D%7D%7D%7D
Accept: application/json

API version 4 returns an array of records. The field names and values below are real (from the portal’s open data); the response as a whole is illustrative. Many older entities are in the dataset twice: once from an older load, whose datereg has no time zone, and once from the load that is kept up to date, whose datereg ends with a UTC offset. The script prefers the up-to-date record, here the second one:

[
  {
    "datereg": "1994-01-20",
    "addresskz": "A26M3K5, АЛМАТЫ ҚАЛАСЫ, МЕДЕУ АУДАНЫ, ДАҢҒЫЛЫ АЛЬ-ФАРАБИ, д. 40",
    "okedru": "ДЕЯТЕЛЬНОСТЬ СБЕРЕГАТЕЛЬНЫХ БАНКОВ",
    "namekz": "\"Қазақстан халық жинақ Банкі\" акционерлік қоғамы",
    "bin": "940140000385",
    "director": "ШАЯХМЕТОВА УМУТ БОЛАТХАНОВНА",
    "statusru": "Зарегистрирован",
    "nameru": "Акционерное общество \"Народный сберегательный банк Казахстана\"",
    "addressru": "A26M3K5, ГОРОД АЛМАТЫ, РАЙОН МЕДЕУСКИЙ, ПР. АЛЬ-ФАРАБИ, д. 40",
    "okedkz": "ЖИНАҚ БАНКІЛЕРІНІҢ ҚЫЗМЕТІ",
    "statuskz": "Тіркелді",
    "id": "7141272"
  },
  {
    "datereg": "1994-01-20+06:00",
    "addresskz": "A26M3K5, Алматы қаласы, Медеу ауданы, АЛЬ-ФАРАБИ даңғылы, 40 ү.",
    "okedru": "ДЕЯТЕЛЬНОСТЬ СБЕРЕГАТЕЛЬНЫХ БАНКОВ",
    "namekz": "\"Қазақстан Халық Банкі\" акционерлік қоғамы",
    "bin": "940140000385",
    "director": "ШАЯХМЕТОВА УМУТ БОЛАТХАНОВНА",
    "statusru": "Зарегистрирован",
    "nameru": "Акционерное общество \"Народный Банк Казахстана\"",
    "addressru": "A26M3K5, город Алматы, Медеуский район, пр. АЛЬ-ФАРАБИ, д. 40",
    "okedkz": "ЖИНАҚ БАНКІЛЕРІНІҢ ҚЫЗМЕТІ",
    "statuskz": "Тіркелді",
    "id": "7141272"
  }
]

Without a valid key, the portal answers HTTP 403 with {"error":"API key is required","status":"403"} or {"error":"API key is invalid","status":"403"}. The field descriptions are in the dataset’s metadata, https://data.egov.kz/meta/gbd_ul/v1.

Properties added by the enricher

Property Response field Example
kzegov.bin bin 940140000385
kzegov.name nameru Акционерное общество "Народный Банк Казахстана"
kzegov.nameKz namekz "Қазақстан Халық Банкі" акционерлік қоғамы
kzegov.status statusru Зарегистрирован
kzegov.statusKz statuskz Тіркелді
kzegov.registrationDate datereg, without the time zone 1994-01-20
kzegov.address addressru A26M3K5, город Алматы, Медеуский район, пр. АЛЬ-ФАРАБИ, д. 40
kzegov.addressKz addresskz A26M3K5, Алматы қаласы, Медеу ауданы, АЛЬ-ФАРАБИ даңғылы, 40 ү.
kzegov.mainActivity okedru ДЕЯТЕЛЬНОСТЬ СБЕРЕГАТЕЛЬНЫХ БАНКОВ
kzegov.mainActivityKz okedkz ЖИНАҚ БАНКІЛЕРІНІҢ ҚЫЗМЕТІ
kzegov.director director ШАЯХМЕТОВА УМУТ БОЛАТХАНОВНА

A property is added only when the register has a value for it.

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 Kazakhstan Legal Entity with the key prefix kzegov, 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, dashes, and a leading BIN, БИН or БСН are removed, so БИН 9401 4000 0385 is looked up as 940140000385. The check digit is verified. Golden records without a valid BIN are skipped without calling the portal.

  • If the register has no entity with the BIN, or the portal returns another error, the script logs the reason and adds nothing.

  • If the portal rejects the API key (HTTP 401 or 403), the script throws an error, so the golden record is listed on the Logs tab with a message to check the API Key field.

  • If the portal reports that it is too busy (HTTP 429 or 503), the script throws an error that makes the enricher try the golden record again later.

  • Successful results are cached for 24 hours per BIN. To change this, edit CACHE_MILLISECONDS in the script.

Testing the enricher

  • Test connection checks only that the script runs. It doesn’t call the portal.

  • To try the setup, create a golden record with organization.bin set to 940140000385 (Halyk Bank) or 990140000483 (Mangistaumunaigas). 180440017350 returns a liquidated entity, with kzegov.status = Ликвидирован.

Limitations

  • Names, statuses, addresses and activities are in Russian and Kazakh only; the dataset has no English names.

  • The dataset is updated as needed, not in real time, and it holds very few liquidated entities. An entity that is no longer registered may return nothing.

  • Only the main activity and the head of the entity are included. There are no founders, shareholders or capital.

  • The portal doesn’t publish rate limits or terms for API version 4. Keep the cache on when you enrich a large number of golden records.

Process script

// REST API enricher (V2) - Kazakh company lookup with the data.egov.kz open data API
//
// Looks up a golden record's Kazakh business identification number (BIN) in the register of
// legal entities, branches and representative offices that the Ministry of Justice publishes on
// the national open data portal (dataset gbd_ul, https://data.egov.kz/datasets/view?index=gbd_ul),
// using the portal's API version 4 (https://data.egov.kz/pages/samples), and adds the result to
// the golden record as kzegov.* properties:
//
//   kzegov.bin               12-digit BIN that was looked up
//   kzegov.name              name in Russian
//   kzegov.nameKz            name in Kazakh
//   kzegov.status            status in Russian, for example Зарегистрирован
//   kzegov.statusKz          status in Kazakh, for example Тіркелді
//   kzegov.registrationDate  date of registration (YYYY-MM-DD)
//   kzegov.address           legal address in Russian
//   kzegov.addressKz         legal address in Kazakh
//   kzegov.mainActivity      main activity (OKED) in Russian
//   kzegov.mainActivityKz    main activity (OKED) in Kazakh
//   kzegov.director          full name of the head of the entity
//
// Needs a data.egov.kz API key, entered in the enricher's API Key field. Sign in to
// data.egov.kz and get the key from For developers > Developer cabinet. See README.md next to
// this file for the enricher settings.
//
// A record gets no result (nothing is stored) when it has no valid BIN, when the BIN isn't in
// the register, or when the API can't answer. A key that the portal rejects fails the record
// with an error, so the problem is visible on the enricher's Logs tab.

// ---- Settings -------------------------------------------------------------------------

// Vocabulary key to read. Add the same key to the Vocabulary and Properties field.
const BIN_KEY = "organization.bin";

const API_URL = "https://data.egov.kz/api/v4/gbd_ul/v1";

// The {APIKey} placeholder is replaced with the API Key field value.
const API_KEY = "{APIKey}";

// How long to reuse an answer for the same BIN. 0 turns caching off.
const CACHE_MILLISECONDS = 24 * 60 * 60 * 1000;

// ---- Script ---------------------------------------------------------------------------

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 "940140000385", "9401 4000 0385" and "BIN 940140000385" (or БИН/БСН). Returns the
// 12 digits, or null when the value isn't a valid BIN (check digit: weights 1 to 11, modulus
// 11, and weights 3 to 11, 1, 2 when the first result is 10).
function parseBin(raw) {
  const digits = raw.toUpperCase().replace(/^(BIN|БИН|БСН)/, "").replace(/[\s.\-]/g, "");
  if (!/^\d{12}$/.test(digits)) {
    return null;
  }
  let check = 0;
  for (let pass = 0; pass < 2; pass++) {
    let sum = 0;
    for (let i = 0; i < 11; i++) {
      sum += Number(digits.charAt(i)) * (((i + pass * 2) % 11) + 1);
    }
    check = sum % 11;
    if (check !== 10) {
      break;
    }
  }
  return check !== 10 && check === Number(digits.charAt(11)) ? digits : 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;
  }
}

// "1994-01-20+06:00" or "1994-01-20" -> "1994-01-20"
function dateOnly(value) {
  const text = clean(value);
  return text && /^\d{4}-\d{2}-\d{2}/.test(text) ? text.substring(0, 10) : null;
}

// Calls the API. Returns the entity's record, or null when there's no answer to store.
function lookUp(bin) {
  const source = { size: 10, query: { bool: { must: [{ match: { bin: bin } }] } } };
  const apiResponse = http.send({
    url: `${API_URL}?apiKey=${encodeURIComponent(API_KEY)}&source=${encodeURIComponent(JSON.stringify(source))}`,
    method: "GET",
    headers: [{ Key: "Accept", Value: "application/json" }],
  });

  const status = String(apiResponse.HttpStatus || "");
  const body = parseJson(apiResponse.Content);

  if (status === "TooManyRequests" || status === "ServiceUnavailable") {
    throw new Error(`TooManyRequests - data.egov.kz is busy (HTTP ${status}), the record will be retried`);
  }

  if (status === "Unauthorized" || status === "Forbidden") {
    const reason = body && body.error ? ` (${body.error})` : "";
    throw new Error(`data.egov.kz rejected the API key${reason}, HTTP ${status}. Check the API Key field of the enricher.`);
  }

  // API version 4 returns an array of records; the portal's other API wraps it in { data: [...] }.
  const records = Array.isArray(body) ? body : body && Array.isArray(body.data) ? body.data : null;
  if (status !== "OK" || !records) {
    log(`data.egov.kz could not look up BIN ${bin}. HTTP ${status}. ${String(apiResponse.Content || "").substring(0, 200)}`);
    return null;
  }

  // Many older entities are in the dataset twice: once from an older load, whose dates have no
  // time zone, and once from the load that is kept up to date, whose dates end with a UTC
  // offset (for example 1994-01-20+06:00). Prefer the up-to-date record.
  let match = null;
  for (let i = 0; i < records.length; i++) {
    const record = records[i];
    if (record && String(record.bin) === bin) {
      if (/[+-]\d{2}:\d{2}$/.test(String(record.datereg || ""))) {
        return record;
      }
      match = match || record;
    }
  }

  if (!match) {
    log(`The register of legal entities has no entity with BIN ${bin}.`);
  }
  return match;
}

function run() {
  const bin = parseBin(getValue(BIN_KEY));
  if (!bin) {
    // No valid BIN on this record (this is also what Test connection hits, because it passes
    // placeholder values instead of real ones).
    return [];
  }

  if (!API_KEY) {
    log("No data.egov.kz API key. Enter it in the API Key field of the enricher.");
    return [];
  }

  const cacheKey = `kzegov:${bin}`;
  const cached = CACHE_MILLISECONDS > 0 ? cache.get(cacheKey) : null;
  let record = cached ? parseJson(String(cached)) : null;

  if (!record) {
    record = lookUp(bin);
    if (!record) {
      return [];
    }
    if (CACHE_MILLISECONDS > 0) {
      cache.set(cacheKey, JSON.stringify(record), CACHE_MILLISECONDS);
    }
  }

  const data = {
    "kzegov.bin": bin,
    "kzegov.name": clean(record.nameru),
    "kzegov.nameKz": clean(record.namekz),
    "kzegov.status": clean(record.statusru),
    "kzegov.statusKz": clean(record.statuskz),
    "kzegov.registrationDate": dateOnly(record.datereg),
    "kzegov.address": clean(record.addressru),
    "kzegov.addressKz": clean(record.addresskz),
    "kzegov.mainActivity": clean(record.okedru),
    "kzegov.mainActivityKz": clean(record.okedkz),
    "kzegov.director": clean(record.director),
  };

  // 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());