Skip to main content
/

Code Examples

Practical examples for the most common API integration scenarios.


Setup

JavaScript / TypeScript (SDK)

npm install @alchemos/api-client
import { AlchemosClient } from '@alchemos/api-client';

const client = new AlchemosClient({
  apiKey: process.env.ALCHEMOS_API_KEY,
  baseUrl: 'https://api.alchemos.io/api/v1', // or sandbox URL
});

Python (requests)

import os
import requests

API_KEY = os.environ['ALCHEMOS_API_KEY']
BASE_URL = 'https://api.alchemos.io/api/v1'

session = requests.Session()
session.headers.update({
    'Authorization': f'Bearer {API_KEY}',
    'Content-Type': 'application/json',
    'Accept': 'application/json',
})

C# (HttpClient)

var client = new HttpClient { BaseAddress = new Uri("https://api.alchemos.io/api/v1/") };
client.DefaultRequestHeaders.Authorization =
    new AuthenticationHeaderValue("Bearer", Environment.GetEnvironmentVariable("ALCHEMOS_API_KEY"));

Create an emission entry

TypeScript

const entry = await client.emissions.create({
  scope: 2,
  category: 'electricity',
  subcategory: 'grid_electricity_uk',
  quantity: 12500,
  unit: 'kwh',
  periodStart: '2024-10-01',
  periodEnd: '2024-10-31',
  locationId: 'loc_london_hq',
  reference: 'ELEC-OCT-2024',
});
console.log(`Created entry ${entry.id}: ${entry.tco2e} tCO₂e`);

Python

response = session.post(f'{BASE_URL}/emissions', json={
    'scope': 2,
    'category': 'electricity',
    'subcategory': 'grid_electricity_uk',
    'quantity': 12500,
    'unit': 'kwh',
    'periodStart': '2024-10-01',
    'periodEnd': '2024-10-31',
})
entry = response.json()['data']
print(f"Created {entry['id']}: {entry['tco2e']} tCO₂e")

Export all approved entries for a year

Python

entries = []
page = 1
while True:
    r = session.get(f'{BASE_URL}/emissions', params={
        'state': 'approved',
        'periodStart': '2024-01-01',
        'periodEnd': '2024-12-31',
        'page': page,
        'pageSize': 200,
    })
    data = r.json()
    entries.extend(data['data'])
    if page >= data['pagination']['totalPages']:
        break
    page += 1

import csv
with open('emissions-2024.csv', 'w', newline='') as f:
    writer = csv.DictWriter(f, fieldnames=['id', 'scope', 'category', 'tco2e', 'periodStart'])
    writer.writeheader()
    writer.writerows([{k: e[k] for k in writer.fieldnames} for e in entries])

Generate and download a GHG inventory report

TypeScript

// Submit generation job
const job = await client.reports.generate({
  reportId: 'ghg_inventory',
  periodStart: '2024-01-01',
  periodEnd: '2024-12-31',
  format: 'pdf',
});

// Poll until complete
let status = job.status;
while (status === 'queued' || status === 'processing') {
  await new Promise(r => setTimeout(r, 3000));
  const updated = await client.reports.getJob(job.jobId);
  status = updated.status;
  if (status === 'complete') {
    console.log('Download URL:', updated.downloadUrl);
    break;
  }
}

Receive and verify a webhook

Node.js (Express)

import express from 'express';
import crypto from 'crypto';

const app = express();
app.use(express.raw({ type: 'application/json' }));

const WEBHOOK_SECRET = process.env.ALCHEMOS_WEBHOOK_SECRET;

app.post('/webhooks/alchemos', (req, res) => {
  const signature = req.headers['alchemos-signature'];
  const parts = Object.fromEntries(signature.split(',').map(p => p.split('=')));
  
  const signedPayload = `${parts.t}.${req.body}`;
  const expected = crypto.createHmac('sha256', WEBHOOK_SECRET)
    .update(signedPayload).digest('hex');

  if (!crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(parts.v1))) {
    return res.status(401).json({ error: 'Invalid signature' });
  }

  const event = JSON.parse(req.body);
  console.log(`Event: ${event.type}`, event.data);

  res.json({ received: true });
});

Retire credits and get a certificate

Python

# Initiate retirement
retirement = session.post(f'{BASE_URL}/offsets/retirements', json={
    'projectId': 'proj_abc123',
    'vintage': 2023,
    'quantity': 100,
    'purpose': 'net_zero_claim',
    'beneficiaryName': 'ACME Corporation Ltd',
    'periodStart': '2024-01-01',
    'periodEnd': '2024-12-31',
}).json()['data']

print(f"Retirement {retirement['id']} status: {retirement['status']}")

# Request certificate after retirement is confirmed
certificate = session.post(f'{BASE_URL}/certificates', json={
    'type': 'carbon_neutral',
    'periodStart': '2024-01-01',
    'periodEnd': '2024-12-31',
    'beneficiaryName': 'ACME Corporation Ltd',
    'scopeCoverage': [1, 2, 3],
    'retirementIds': [retirement['id']],
    'signatoryName': 'Jane Smith',
    'signatoryTitle': 'CSO',
}).json()['data']

print(f"Certificate {certificate['certId']} status: {certificate['status']}")

Was this page helpful?