---
title: Bolagsverket (Sweden)
url: http://0.0.0.0:4000/govern/rest-api-enricher-samples/bolagsverket-sweden
content_type: reference
section: Govern & improve > REST API enricher samples
---

# Bolagsverket (Sweden)

> reference: Facts, options, APIs.

This example looks up an organization's Swedish organisation number (organisationsnummer) with the Swedish Companies Registration Office's (Bolagsverket) free API for high-value datasets, **Värdefulla datamängder** ([Bolagsverket's APIs and open data](https://bolagsverket.se/apierochoppnadata)). For each golden record it stores the registered name and other names, the organisation form and legal form, the registration date, the business description, SNI industry codes, the postal address, whether the organisation is active, and deregistration and ongoing liquidation or bankruptcy details.

**Enricher version:** V2  
**API key:** your Bolagsverket client ID and client secret (free; register on [Bolagsverket's API portal](https://portal.api.bolagsverket.se/))

> **Important:** This sample couldn't be tried with real credentials. The request, response and token flow follow Bolagsverket's OpenAPI specification for the API, and the example response on this page is the example from that specification. The token endpoint and the API gateway were checked live with made-up credentials, and their error responses are handled as described below.

To set up the enricher, see [Add REST API enricher](http://0.0.0.0:4000/govern/enrichment/rest-api#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 client credentials, as `clientId:clientSecret`. To get them, create an account on [Bolagsverket's API portal](https://portal.api.bolagsverket.se/), register an application with access to the **Värdefulla datamängder** API, and generate its client ID (consumer key) and client secret (consumer secret). Enter them in the **API Key** field separated by a colon.

  The script gets an access token from the token endpoint with these credentials and reuses it until shortly before it expires. If the field is empty, the script adds nothing and doesn't call Bolagsverket.

- **Filters** – we recommend a rule that only accepts golden records where `organization.organisationNumber` has a value. Otherwise, every record without an organisation number is listed on the enricher's **Logs** tab as having returned no results.

## Vocabulary and Properties

```
organization.organisationNumber
```

`organization.organisationNumber` holds the 10-digit Swedish organisation number, for example `556016-0680`. If your data uses another vocabulary key, change this field and the `ORGANISATION_NUMBER_KEY` value at the top of the script.

## Request and response

**Gateway URL:** `https://gw.api.bolagsverket.se/vardefulla-datamangder/v1`  
**Endpoint:** `POST /organisationer` with the organisation number in a JSON body  
**Authentication:** OAuth2 bearer token in the `Authorization` header. Tokens come from `https://portal.api.bolagsverket.se/oauth2/token` with the client credentials grant and the scope `vardefulla-datamangder:read`.  
**Test environment:** `https://gw-accept2.api.bolagsverket.se/vardefulla-datamangder/v1`, with tokens from `https://portal-accept2.api.bolagsverket.se/oauth2/token`

When it has no valid token, the script first requests one:

```http
POST https://portal.api.bolagsverket.se/oauth2/token
Content-Type: application/x-www-form-urlencoded
Accept: application/json

grant_type=client_credentials&client_id=<client ID>&client_secret=<client secret>&scope=vardefulla-datamangder%3Aread
```

```json
{ "access_token": "eyJ4NXQiOi...", "scope": "vardefulla-datamangder:read", "token_type": "Bearer", "expires_in": 3600 }
```

Then it sends one request per golden record:

```http
POST https://gw.api.bolagsverket.se/vardefulla-datamangder/v1/organisationer
Authorization: Bearer eyJ4NXQiOi...
Content-Type: application/json
Accept: application/json

{ "identitetsbeteckning": "5299999994" }
```

Shortened response (the example from Bolagsverket's specification; the company is fictitious):

```json
{
  "organisationer": [
    {
      "organisationsidentitet": { "identitetsbeteckning": "5299999994" },
      "organisationsnamn": {
        "organisationsnamnLista": [
          { "namn": "Cykelbolaget AB", "organisationsnamntyp": { "kod": "FORETAGSNAMN", "klartext": "Företagsnamn" }, "registreringsdatum": "2020-03-15" },
          { "namn": "Mopedbolaget AB", "organisationsnamntyp": { "kod": "SARSKILT_FORETAGSNAMN", "klartext": "Särskilt företagsnamn" }, "registreringsdatum": "2024-03-15" },
          { "namn": "Bicycle expert", "organisationsnamntyp": { "kod": "FORETAGSNAMN_PA_FRAMMANDE_SPRAK", "klartext": "Företagsnamn på främmande språk" }, "registreringsdatum": "2020-04-01" }
        ],
        "fel": null
      },
      "registreringsland": { "kod": "SE-LAND", "klartext": "Sverige" },
      "organisationsform": { "kod": "AB", "klartext": "Aktiebolag", "fel": null },
      "reklamsparr": { "kod": "JA", "fel": null },
      "juridiskForm": { "kod": "49", "klartext": "Övriga aktiebolag", "fel": null },
      "verksamOrganisation": { "kod": "NEJ", "fel": null },
      "postadressOrganisation": {
        "postadress": { "coAdress": "C/o Annat företag", "utdelningsadress": "Jobbstigen 2", "postnummer": "12345", "postort": "Grönköping", "land": "Sverige" },
        "fel": null
      },
      "verksamhetsbeskrivning": { "beskrivning": "Bedriva handel med cyklar och tillbehör till cyklar", "fel": null },
      "organisationsdatum": { "registreringsdatum": "2000-01-23", "fel": null },
      "avregistreradOrganisation": { "avregistreringsdatum": "2023-05-05T00:00:00.000+00:00", "fel": null },
      "avregistreringsorsak": { "kod": "LIAV", "klartext": "Likvidation", "fel": null },
      "pagandeAvvecklingsEllerOmstruktureringsforfarande": {
        "pagandeAvvecklingsEllerOmstruktureringsforfarandeLista": [
          { "kod": "KK", "klartext": "Konkurs", "fromDatum": "2024-01-26T00:00:00.000+00:00" },
          { "kod": "LI", "klartext": "Likvidation", "fromDatum": "2024-05-26T00:00:00.000+00:00" }
        ],
        "fel": null
      },
      "naringsgrenOrganisation": {
        "sni": [
          { "kod": "47642", "klartext": "Specialiserad butikshandel med cyklar" },
          { "kod": "45400", "klartext": "EU-mopeder, reservdelar och tillbehör, handel med" }
        ],
        "fel": null
      }
    }
  ]
}
```

## Properties added by the enricher

| Property | Response field | Example |
| -------- | -------------- | ------- |
| `bolagsverket.organisationNumber` | `organisationsidentitet.identitetsbeteckning` | `5299999994` |
| `bolagsverket.name` | `namn` of the `FORETAGSNAMN` entry in `organisationsnamn.organisationsnamnLista` | `Cykelbolaget AB` |
| `bolagsverket.otherNames` | the other names in `organisationsnamnLista`, separated by `; ` | `Mopedbolaget AB; Bicycle expert` |
| `bolagsverket.organisationForm` | `organisationsform.klartext` | `Aktiebolag` |
| `bolagsverket.organisationFormCode` | `organisationsform.kod` | `AB` |
| `bolagsverket.legalForm` | `juridiskForm.klartext` | `Övriga aktiebolag` |
| `bolagsverket.legalFormCode` | `juridiskForm.kod` | `49` |
| `bolagsverket.registrationDate` | `organisationsdatum.registreringsdatum` | `2000-01-23` |
| `bolagsverket.businessDescription` | `verksamhetsbeskrivning.beskrivning` | `Bedriva handel med cyklar och tillbehör till cyklar` |
| `bolagsverket.industryCode` | `kod` of the first entry in `naringsgrenOrganisation.sni` | `47642` |
| `bolagsverket.industry` | `klartext` of that entry (in Swedish) | `Specialiserad butikshandel med cyklar` |
| `bolagsverket.industryCodes` | all `naringsgrenOrganisation.sni[].kod`, separated by `; ` | `47642; 45400` |
| `bolagsverket.postalAddress` | `postadressOrganisation.postadress`, on one line | `C/o Annat företag, Jobbstigen 2, 12345 Grönköping` |
| `bolagsverket.postalCode` | `postadress.postnummer` | `12345` |
| `bolagsverket.city` | `postadress.postort` | `Grönköping` |
| `bolagsverket.registrationCountry` | `registreringsland.klartext` | `Sverige` |
| `bolagsverket.active` | `verksamOrganisation.kod` (`JA` or `NEJ`) | `False` |
| `bolagsverket.advertisingBlocked` | `reklamsparr.kod` (`JA` or `NEJ`) | `True` |
| `bolagsverket.deregistered` | `True` when `avregistreradOrganisation.avregistreringsdatum` has a value | `True` |
| `bolagsverket.deregistrationDate` | `avregistreradOrganisation.avregistreringsdatum`, as `YYYY-MM-DD` | `2023-05-05` |
| `bolagsverket.deregistrationReason` | `avregistreringsorsak.klartext` | `Likvidation` |
| `bolagsverket.ongoingProceedings` | `klartext` of each ongoing liquidation, bankruptcy or restructuring proceeding, separated by `; ` | `Konkurs; Likvidation` |

A property is added only when Bolagsverket returns a value for it. The `active`, `legalForm` and `advertisingBlocked` values come from Statistics Sweden (SCB) through the same API.

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 `Bolagsverket` with the key prefix `bolagsverket`, 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, dashes and dots are removed, a 12-digit number with the `16` prefix is shortened to 10 digits, and a Swedish VAT number such as `SE556016068001` is converted to its organisation number. The number must have a valid check digit (Luhn) and a third digit of 2 or more, which is what distinguishes the organisation number of a legal entity from a personal identity number. Golden records without a valid organisation number are skipped without calling Bolagsverket.

- If the token endpoint rejects the client ID and secret (for example HTTP 401 `invalid_client`), or the API rejects the token (HTTP 401 or 403, or HTTP 500 with a gateway authentication error such as code `900900`), the script throws an error, so the golden record is listed on the **Logs** tab with a message to check the **API Key** field. When a token is rejected, the script first gets a new token and tries once more.

- If the organisation number isn't registered (HTTP 400 or an empty `organisationer` list), or the API returns another error, the script logs the reason and adds nothing.

- Bolagsverket collects the data from several sources. If a source can't answer, the API marks that part of the response with a `fel` error. When the names are missing for this reason, the script adds nothing. When another part is missing, the script adds the other properties, but doesn't cache the answer, so the next golden record with the same number asks again.

- If Bolagsverket reports that it is too busy (HTTP 429, or a gateway throttling error such as code `900800`), the script throws an error that makes the enricher try the golden record again later.

- Successful results are cached for 24 hours per organisation number. To change this, edit `CACHE_MILLISECONDS` in the script.

## Testing the enricher

- **Test connection** checks only that the script runs. It doesn't call Bolagsverket.

- To try the setup against Bolagsverket's test environment, change `BOLAGSVERKET_URL` and `TOKEN_URL` at the top of the script to the test environment addresses (see the comment above them), and use credentials for the test environment.

- To try it in production, create a golden record with `organization.organisationNumber` set to the organisation number of a company you know, for example `556016-0680`, then enrich it.

## Limitations

- Only organisations with an organisation number are looked up. Sole traders (enskilda näringsidkare), who are registered under a personal identity number, are skipped.

- The API returns basic company information only. Board members, signatories, share capital and annual reports aren't part of this API (annual reports are listed by a separate `/dokumentlista` endpoint that this script doesn't use).

- SNI descriptions and other code texts are in Swedish.

- Bolagsverket's terms of use and any rate limits for the API are on its API portal. Keep the cache on when you enrich a large number of golden records.

## Process script

```javascript
// REST API enricher (V2) - Swedish company lookup with Bolagsverket
//
// Looks up a golden record's Swedish organisation number (organisationsnummer) with the Swedish
// Companies Registration Office's (Bolagsverket) free API for high-value datasets, "Värdefulla
// datamängder" (https://bolagsverket.se/apierochoppnadata), and adds the result to the golden
// record as bolagsverket.* properties:
//
//   bolagsverket.organisationNumber   10-digit organisation number that was looked up
//   bolagsverket.name                 registered company name (företagsnamn)
//   bolagsverket.otherNames           other registered names (secondary and foreign-language names), separated by "; "
//   bolagsverket.organisationForm     organisation form, for example Aktiebolag
//   bolagsverket.organisationFormCode organisation form code, for example AB
//   bolagsverket.legalForm            legal form from Statistics Sweden (SCB), for example Övriga aktiebolag
//   bolagsverket.legalFormCode        legal form code from SCB, for example 49
//   bolagsverket.registrationDate     date the organisation was registered (YYYY-MM-DD)
//   bolagsverket.businessDescription  registered description of the business (verksamhetsbeskrivning)
//   bolagsverket.industryCode         first SNI industry code, for example 47642
//   bolagsverket.industry             description of that SNI code (Swedish)
//   bolagsverket.industryCodes        all SNI industry codes, separated by "; "
//   bolagsverket.postalAddress        postal address on one line
//   bolagsverket.postalCode           postal code
//   bolagsverket.city                 postal town (postort)
//   bolagsverket.registrationCountry  country of registration, for example Sverige
//   bolagsverket.active               "True" / "False" - whether SCB records the organisation as active
//   bolagsverket.advertisingBlocked   "True" / "False" - whether the organisation has opted out of direct advertising (reklamspärr)
//   bolagsverket.deregistered         "True" when the organisation has been deregistered
//   bolagsverket.deregistrationDate   date it was deregistered (YYYY-MM-DD)
//   bolagsverket.deregistrationReason reason it was deregistered, for example Likvidation
//   bolagsverket.ongoingProceedings   ongoing liquidation, bankruptcy or restructuring proceedings, separated by "; "
//
// Needs free API credentials (a client ID and client secret) from Bolagsverket's API portal.
// Enter them in the enricher's API Key field as clientId:clientSecret. The script gets an access
// token itself and reuses it until shortly before it expires. See README.md next to this file
// for the enricher settings.
//
// A record gets no result (nothing is stored) when it has no valid organisation number, when the
// number isn't registered, or when the API can't answer. Missing credentials make no call;
// rejected credentials fail the record with an error that says so.

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

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

// Bolagsverket's test environment is https://gw-accept2.api.bolagsverket.se/vardefulla-datamangder/v1
// with the token endpoint https://portal-accept2.api.bolagsverket.se/oauth2/token.
const BOLAGSVERKET_URL = "https://gw.api.bolagsverket.se/vardefulla-datamangder/v1/organisationer";
const TOKEN_URL = "https://portal.api.bolagsverket.se/oauth2/token";
const SCOPE = "vardefulla-datamangder:read";

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

// How long to reuse an answer for the same organisation number. 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 "556016-0680", "5560160680", "16 556016-0680" (12 digits with the 16 prefix) and the
// VAT number "SE556016068001". Returns the 10 digits, or null when it isn't a valid organisation
// number of a legal entity (the third digit is 2 or more, and the last digit is a Luhn check
// digit). Personal identity numbers (sole traders) are not looked up.
function parseOrganisationNumber(raw) {
  let text = raw.toUpperCase().replace(/[\s.\-+]/g, "");
  const vat = /^SE(\d{10})01$/.exec(text);
  if (vat) {
    text = vat[1];
  }
  if (/^16\d{10}$/.test(text)) {
    text = text.substring(2);
  }
  if (!/^\d{10}$/.test(text) || Number(text.charAt(2)) < 2) {
    return null;
  }
  let sum = 0;
  for (let i = 0; i < 10; i++) {
    let digit = Number(text.charAt(i));
    if (i % 2 === 0) {
      digit *= 2;
      if (digit > 9) {
        digit -= 9;
      }
    }
    sum += digit;
  }
  return sum % 10 === 0 ? text : null;
}

function clean(value) {
  if (value === null || value === undefined) {
    return null;
  }
  const text = String(value).replace(/\\n/g, " ").replace(/\s+/g, " ").trim();
  return text === "" || text.toLowerCase() === "n/a" ? null : text;
}

function parseJson(text) {
  try {
    return JSON.parse(text);
  } catch (e) {
    return null;
  }
}

function dateOnly(value) {
  const text = clean(value);
  return text && /^\d{4}-\d{2}-\d{2}/.test(text) ? text.substring(0, 10) : null;
}

// Returns a section of the organisation, or null when it is missing or Bolagsverket reports
// that its source couldn't supply it (the section's "fel" field).
function section(organisation, name) {
  const value = organisation ? organisation[name] : null;
  return value && !value.fel ? value : null;
}

function hasSourceError(organisation) {
  const keys = Object.keys(organisation || {});
  for (let i = 0; i < keys.length; i++) {
    const value = organisation[keys[i]];
    if (value && typeof value === "object" && value.fel) {
      return true;
    }
  }
  return false;
}

function yesNo(value) {
  const code = value ? clean(value.kod) : null;
  return code === "JA" ? true : code === "NEJ" ? false : null;
}

function credentials() {
  const value = clean(API_KEY) || "";
  const separator = value.indexOf(":");
  if (separator <= 0 || separator === value.length - 1) {
    return null;
  }
  return { clientId: value.substring(0, separator), clientSecret: value.substring(separator + 1) };
}

// WSO2 API gateway error codes: 9009xx are authentication failures (sometimes sent with HTTP 500),
// 9008xx are throttling.
function gatewayCode(body) {
  return body && body.code ? String(body.code) : "";
}

// Gets an access token with the OAuth2 client credentials grant.
function requestToken(creds) {
  const tokenResponse = http.send({
    url: TOKEN_URL,
    method: "POST",
    headers: [
      { Key: "Content-Type", Value: "application/x-www-form-urlencoded" },
      { Key: "Accept", Value: "application/json" },
    ],
    body:
      "grant_type=client_credentials" +
      `&client_id=${encodeURIComponent(creds.clientId)}` +
      `&client_secret=${encodeURIComponent(creds.clientSecret)}` +
      `&scope=${encodeURIComponent(SCOPE)}`,
  });

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

  if (status === "TooManyRequests") {
    throw new Error("TooManyRequests - the Bolagsverket token endpoint is busy, the record will be retried");
  }

  if (status === "OK" && body && body.access_token) {
    return { accessToken: String(body.access_token), expiresIn: Number(body.expires_in) || 3600 };
  }

  const reason = body && (body.error || body.error_description) ? `${body.error || ""} ${body.error_description || ""}`.trim() : `HTTP ${status}`;
  if (status === "BadRequest" || status === "Unauthorized" || status === "Forbidden") {
    throw new Error(`Bolagsverket rejected the client ID and secret in the API Key field (${reason}).`);
  }
  log(`Could not get a Bolagsverket access token. ${reason}. ${String(tokenResponse.Content || "").substring(0, 200)}`);
  return null;
}

// Returns an access token, from the cache when there's one that hasn't expired.
function getAccessToken(creds, forceNew) {
  const cacheKey = `bolagsverket:token:${creds.clientId}`;
  if (!forceNew) {
    const cached = cache.get(cacheKey);
    if (cached) {
      return String(cached);
    }
  }

  const token = requestToken(creds);
  if (!token) {
    return null;
  }
  // Reuse the token until 5 minutes before it expires (at least 1 minute). A forced new token
  // isn't cached, because cache.set does nothing when the key already exists.
  if (!forceNew) {
    cache.set(cacheKey, token.accessToken, Math.max(60, token.expiresIn - 300) * 1000);
  }
  return token.accessToken;
}

function callApi(organisationNumber, accessToken) {
  return http.send({
    url: BOLAGSVERKET_URL,
    method: "POST",
    headers: [
      { Key: "Authorization", Value: `Bearer ${accessToken}` },
      { Key: "Accept", Value: "application/json" },
    ],
    body: { identitetsbeteckning: organisationNumber },
  });
}

function isAuthFailure(status, body) {
  return status === "Unauthorized" || status === "Forbidden" || gatewayCode(body).indexOf("9009") === 0;
}

// Calls the API. Returns { organisation, complete }, or null when there's no answer to store.
function lookUp(organisationNumber, creds) {
  const accessToken = getAccessToken(creds, false);
  if (!accessToken) {
    return null;
  }

  let apiResponse = callApi(organisationNumber, accessToken);
  let status = String(apiResponse.HttpStatus || "");
  let body = parseJson(apiResponse.Content);

  // A cached token can stop working before it expires. Try once more with a new token.
  if (isAuthFailure(status, body)) {
    const newToken = getAccessToken(creds, true);
    if (!newToken) {
      return null;
    }
    apiResponse = callApi(organisationNumber, newToken);
    status = String(apiResponse.HttpStatus || "");
    body = parseJson(apiResponse.Content);
  }

  if (status === "TooManyRequests" || gatewayCode(body).indexOf("9008") === 0) {
    throw new Error("TooManyRequests - the Bolagsverket API is busy, the record will be retried");
  }

  if (isAuthFailure(status, body)) {
    const message = body ? body.detail || body.description || body.message || "" : String(apiResponse.Content || "").substring(0, 200);
    throw new Error(`The Bolagsverket API rejected the credentials in the API Key field (HTTP ${status}). ${message}`.trim());
  }

  if (status === "OK" && body && Array.isArray(body.organisationer)) {
    const organisations = body.organisationer;
    for (let i = 0; i < organisations.length; i++) {
      const organisation = organisations[i];
      const identity = organisation && organisation.organisationsidentitet;
      const names = section(organisation, "organisationsnamn");
      if (identity && clean(identity.identitetsbeteckning) === organisationNumber && names && Array.isArray(names.organisationsnamnLista)) {
        return { organisation: organisation, complete: !hasSourceError(organisation) };
      }
    }
    log(`Bolagsverket returned no usable data for ${organisationNumber}. ${String(apiResponse.Content || "").substring(0, 200)}`);
    return null;
  }

  // 400 (for example an organisation number that isn't registered), 404, 500 and others
  const detail = body && (body.detail || body.title) ? `${body.title || ""}: ${body.detail || ""}` : String(apiResponse.Content || "").substring(0, 200);
  log(`Bolagsverket could not look up ${organisationNumber}. HTTP ${status}. ${detail}`);
  return null;
}

function formatAddress(address) {
  if (!address) {
    return null;
  }
  const lines = [clean(address.coAdress), clean(address.utdelningsadress)].filter((x) => !!x);
  const postalTown = [clean(address.postnummer), clean(address.postort)].filter((x) => !!x).join(" ");
  if (postalTown) {
    lines.push(postalTown);
  }
  const country = clean(address.land);
  if (country && country.toLowerCase() !== "sverige") {
    lines.push(country);
  }
  return lines.length > 0 ? lines.join(", ") : null;
}

function toData(organisationNumber, organisation) {
  const nameList = section(organisation, "organisationsnamn").organisationsnamnLista;
  let name = null;
  const otherNames = [];
  for (let i = 0; i < nameList.length; i++) {
    const entry = nameList[i] || {};
    const entryName = clean(entry.namn);
    const type = entry.organisationsnamntyp ? clean(entry.organisationsnamntyp.kod) : null;
    if (!entryName) {
      continue;
    }
    if (!name && type === "FORETAGSNAMN") {
      name = entryName;
    } else if (otherNames.indexOf(entryName) < 0) {
      otherNames.push(entryName);
    }
  }
  if (!name && otherNames.length > 0) {
    name = otherNames.shift();
  }

  const form = section(organisation, "organisationsform") || {};
  const legalForm = section(organisation, "juridiskForm") || {};
  const dates = section(organisation, "organisationsdatum") || {};
  const description = section(organisation, "verksamhetsbeskrivning") || {};
  const industry = section(organisation, "naringsgrenOrganisation") || {};
  const sni = Array.isArray(industry.sni) ? industry.sni.filter((x) => x && clean(x.kod)) : [];
  const postal = section(organisation, "postadressOrganisation");
  const address = postal ? postal.postadress : null;
  const country = organisation.registreringsland || {};
  const deregistered = section(organisation, "avregistreradOrganisation") || {};
  const deregistrationDate = dateOnly(deregistered.avregistreringsdatum);
  const reason = section(organisation, "avregistreringsorsak") || {};
  // The API documentation spells this section both ways
  const proceedings =
    section(organisation, "pagaendeAvvecklingsEllerOmstruktureringsforfarande") ||
    section(organisation, "pagandeAvvecklingsEllerOmstruktureringsforfarande") ||
    {};
  const proceedingList =
    proceedings.pagaendeAvvecklingsEllerOmstruktureringsforfarandeLista || proceedings.pagandeAvvecklingsEllerOmstruktureringsforfarandeLista || [];

  const data = {
    "bolagsverket.organisationNumber": organisationNumber,
    "bolagsverket.name": name,
    "bolagsverket.otherNames": otherNames.length > 0 ? otherNames.join("; ") : null,
    "bolagsverket.organisationForm": clean(form.klartext),
    "bolagsverket.organisationFormCode": clean(form.kod),
    "bolagsverket.legalForm": clean(legalForm.klartext),
    "bolagsverket.legalFormCode": clean(legalForm.kod),
    "bolagsverket.registrationDate": dateOnly(dates.registreringsdatum),
    "bolagsverket.businessDescription": clean(description.beskrivning),
    "bolagsverket.industryCode": sni.length > 0 ? clean(sni[0].kod) : null,
    "bolagsverket.industry": sni.length > 0 ? clean(sni[0].klartext) : null,
    "bolagsverket.industryCodes": sni.length > 0 ? sni.map((x) => clean(x.kod)).join("; ") : null,
    "bolagsverket.postalAddress": formatAddress(address),
    "bolagsverket.postalCode": address ? clean(address.postnummer) : null,
    "bolagsverket.city": address ? clean(address.postort) : null,
    "bolagsverket.registrationCountry": clean(country.klartext),
    "bolagsverket.active": yesNo(section(organisation, "verksamOrganisation")),
    "bolagsverket.advertisingBlocked": yesNo(section(organisation, "reklamsparr")),
    "bolagsverket.deregistered": deregistrationDate ? true : null,
    "bolagsverket.deregistrationDate": deregistrationDate,
    "bolagsverket.deregistrationReason": clean(reason.klartext) || clean(reason.kod),
    "bolagsverket.ongoingProceedings": Array.isArray(proceedingList)
      ? proceedingList.map((x) => x && (clean(x.klartext) || clean(x.kod))).filter((x) => !!x).join("; ") || null
      : null,
  };

  // Leave out values Bolagsverket 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;
}

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

  const creds = credentials();
  if (!creds) {
    log("The Bolagsverket API needs credentials. Enter clientId:clientSecret in the enricher's API Key field.");
    return [];
  }

  const cacheKey = `bolagsverket:${organisationNumber}`;
  const cached = CACHE_MILLISECONDS > 0 ? cache.get(cacheKey) : null;
  let organisation = cached ? parseJson(String(cached)) : null;

  if (!organisation) {
    const answer = lookUp(organisationNumber, creds);
    if (!answer) {
      return [];
    }
    organisation = answer.organisation;
    // Only complete answers are cached: when one of Bolagsverket's sources couldn't answer, the
    // next record with this number asks again.
    if (CACHE_MILLISECONDS > 0 && answer.complete) {
      cache.set(cacheKey, JSON.stringify(organisation), CACHE_MILLISECONDS);
    }
  }

  return [{ Data: toData(organisationNumber, organisation), Score: 100 }];
}

response = JSON.stringify(run());
```

Up: [REST API enricher samples](http://0.0.0.0:4000/govern/rest-api-enricher-samples.md)
