JavaScript / TypeScript
Examples assume UNIFYUNITS_API_KEY is set in the environment.
The public JavaScript and TypeScript client repository has SDK source and usage notes. The examples below use direct HTTP requests.
Single conversion
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"Batch conversion
typescript
const response = await fetch("https://api.unifyunits.com/v1/batch", {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.UNIFYUNITS_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
conversions: [
{ value: "10", from: "kg", to: "lb" },
{ value: "100", from: "km", to: "mi" },
],
}),
});
const { data } = await response.json();
for (const item of 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
async function convert(value: string, from: string, to: string) {
const url = new URL("https://api.unifyunits.com/v1/convert");
url.searchParams.set("value", value);
url.searchParams.set("from", from);
url.searchParams.set("to", to);
const res = await fetch(url, {
headers: { Authorization: `Bearer ${process.env.UNIFYUNITS_API_KEY}` },
});
const body = await res.json();
if (!res.ok) {
switch (body.error.code) {
case "UNKNOWN_UNIT":
throw new Error("Unknown unit. Check GET /v1/units for valid IDs.");
case "INCOMPATIBLE_UNITS":
throw new Error(`Cannot convert between ${from} and ${to}.`);
case "RATE_LIMIT_EXCEEDED":
throw new Error("Rate limited. Retry after backoff.");
default:
throw new Error(`API error: ${body.error.code}`);
}
}
return body.data.result.value;
}