PYTHON

Python

The API is four JSON endpoints, so requests is all you need.

There is no maintained SDK for the current API. The PyPI package zerocarbon-python-sdk (2.0.0) was published for an earlier version of the API: its documented usage prices flights from airport codes without a distance and calls report and webhook endpoints that do not exist here. Don't use it; use the client below.

A small client

terminalbash
pip install requests
zerocarbon.pypython
import os
import requests

BASE = "https://zerocarbon.org.in/api/v1"


class ZeroCarbonError(Exception):
    def __init__(self, status, code, message):
        super().__init__(f"{status} {code}: {message}")
        self.status, self.code = status, code


def calculate(endpoint, body, api_key=None):
    """endpoint is one of: electricity, fuel, flight, spend."""
    api_key = api_key or os.environ.get("ZEROCARBON_API_KEY")
    headers = {"Authorization": f"Bearer {api_key}"} if api_key else {}
    res = requests.post(f"{BASE}/calculate/{endpoint}", json=body, headers=headers, timeout=30)
    data = res.json()
    if data.get("success"):
        return data["data"]
    # Refusals: {error: str, code, guidance}. Other errors: {error: {code, message}}.
    if isinstance(data.get("error"), str):
        raise ZeroCarbonError(res.status_code, data.get("code"), f"{data['error']} {data.get('guidance', '')}")
    err = data.get("error") or {}
    raise ZeroCarbonError(res.status_code, err.get("code"), err.get("message", res.reason))

Usage

example.pypython
from zerocarbon import calculate, ZeroCarbonError

fuel = calculate("fuel", {"fuel_type": "diesel", "amount": 100, "unit": "L", "country": "IN"})
print(fuel["emissions_kg_co2e"], fuel["formula"])
# 268.795 100 liter × 2.687954 kgCO2e/liter = 268.7950 kgCO2e

try:
    calculate("flight", {"distance_km": 1150, "cabin_class": "business"})
except ZeroCarbonError as err:
    print(err.status, err.code)
    # 422 cabin_class_unsupported

Without ZEROCARBON_API_KEY set, electricity, fuel and flight run in test mode; spend needs the key. Fields for each endpoint are in the API Reference.