UnifyUnits Developers

JavaScript / TypeScript

Prefer the official client for server-side apps. It wraps HTTP for you and keeps measurement values as decimal strings. Source and release notes: unifyunits-js. Do not put API keys in browser bundles.

Install

Node.js 18+. Until the package is on npm, install the tagged GitHub release:

bash
npm install github:unifyunits/unifyunits-js#v0.1.0

After npm publication, use npm install @unifyunits/sdk instead.

Convert with the SDK

typescript
import { UnifyUnits, UnifyUnitsApiError } from "@unifyunits/sdk";

const units = new UnifyUnits({
  apiKey: process.env.UNIFYUNITS_API_KEY,
});

// The client returns untyped JSON; narrow it to the fields you use.
const result = (await units.convert({
  value: "1",
  from: "ft",
  to: "m",
})) as { data: { result: { value: string; unit: string } } };
console.log(result.data.result); // { value: "0.3048", unit: "m" }
The client covers convert, batch, categories, units, and health. It does not yet accept decimals or format_locale, and has no parse, normalize, currency, substance, or unit-price calls. Use raw HTTP for those.

Batch with the SDK

typescript
import { UnifyUnits } from "@unifyunits/sdk";

const units = new UnifyUnits({
  apiKey: process.env.UNIFYUNITS_API_KEY,
});

type BatchItem =
  | { index: number; status: "success"; result: { value: string; unit: string } }
  | { index: number; status: "error"; error: { code: string } };

const batch = (await units.convertBatch([
  { value: "10", from: "kg", to: "lb" },
  { value: "100", from: "km", to: "mi" },
])) as { data: BatchItem[] };

for (const item of batch.data) {
  if (item.status === "success") {
    console.log(`Item ${item.index}: ${item.result.value} ${item.result.unit}`);
  } else {
    console.error(`Item ${item.index} failed: ${item.error.code}`);
  }
}

Error handling

typescript
import { UnifyUnits, UnifyUnitsApiError } from "@unifyunits/sdk";

const units = new UnifyUnits({
  apiKey: process.env.UNIFYUNITS_API_KEY,
});

try {
  await units.convert({ value: "1", from: "ft", to: "kg" });
} catch (error) {
  if (error instanceof UnifyUnitsApiError) {
    console.error(error.errorCode, error.requestId, error.message);
  } else {
    throw error;
  }
}

Same calls with raw HTTP

Use these when you cannot install the client, or when debugging against the OpenAPI contract.

typescript
const response = await fetch(
  "https://api.unifyunits.com/v1/convert?value=1&from=ft&to=m",
  {
    headers: {
      Authorization: `Bearer ${process.env.UNIFYUNITS_API_KEY}`,
    },
  },
);

if (!response.ok) {
  const error = await response.json();
  throw new Error(`${error.error.code}: ${error.error.message}`);
}

const body = await response.json();
console.log(body.data.result.value); // "0.3048"