UnifyUnitsDevelopers

Python

The public Python client repository has SDK source and usage notes. The examples below use direct HTTP requests.

Single conversion

python
import os
import requests

response = requests.get(
    "https://api.unifyunits.com/v1/convert",
    params={"value": "1", "from": "ft", "to": "m"},
    headers={"Authorization": f"Bearer {os.environ['UNIFYUNITS_API_KEY']}"},
    timeout=10,
)

response.raise_for_status()
data = response.json()
print(data["data"]["result"]["value"])  # "0.3048"

Batch conversion

python
import os
import requests

response = requests.post(
    "https://api.unifyunits.com/v1/batch",
    json={
        "conversions": [
            {"value": "10", "from": "kg", "to": "lb"},
            {"value": "100", "from": "km", "to": "mi"},
        ]
    },
    headers={"Authorization": f"Bearer {os.environ['UNIFYUNITS_API_KEY']}"},
    timeout=10,
)

response.raise_for_status()
result = response.json()

for item in result["data"]:
    if item["status"] == "success":
        print(f"Item {item['index']}: {item['result']['value']} {item['result']['unit']}")
    else:
        print(f"Item {item['index']} failed: {item['error']['code']}")

Error handling

python
import os
import requests
from requests.exceptions import HTTPError

def convert(value: str, from_unit: str, to_unit: str) -> str:
    try:
        r = requests.get(
            "https://api.unifyunits.com/v1/convert",
            params={"value": value, "from": from_unit, "to": to_unit},
            headers={"Authorization": f"Bearer {os.environ['UNIFYUNITS_API_KEY']}"},
            timeout=10,
        )
        r.raise_for_status()
        return r.json()["data"]["result"]["value"]
    except HTTPError as e:
        err = e.response.json()["error"]
        raise ValueError(f"{err['code']}: {err['message']}")