Back to Documentation

Code Examples

Practical examples for integrating with the SyncBooks REST API.

Base URL:https://api.yourdomain.com/api/v1Full API Reference
🟩

Node.js

Authenticate & list unpaid invoicesNode.js
const res = await fetch('https://api.yourdomain.com/api/v1/invoices?status=sent', {
  headers: { Authorization: 'Bearer sk_live_YOUR_KEY' },
});
const { data } = await res.json();
console.log(data); // array of invoice objects
Create an invoiceNode.js
const res = await fetch('https://api.yourdomain.com/api/v1/invoices', {
  method: 'POST',
  headers: {
    Authorization: 'Bearer sk_live_YOUR_KEY',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    customerId: '65f1a2b3c4d5e6f7a8b9c0d1',
    invoiceDate: '2025-07-01',
    dueDate: '2025-07-31',
    lineItems: [
      { description: 'Consulting Services', quantity: 10, rate: 250, amount: 2500 },
    ],
    subtotal: 2500,
    taxAmount: 375,
    totalAmount: 2875,
    status: 'sent',
  }),
});
const { data } = await res.json();
console.log(data.invoiceNumber); // INV-000043
Record a paymentNode.js
const res = await fetch('https://api.yourdomain.com/api/v1/payments', {
  method: 'POST',
  headers: {
    Authorization: 'Bearer sk_live_YOUR_KEY',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    invoiceId: '65f1a2b3c4d5e6f7a8b9c0d2',
    customerId: '65f1a2b3c4d5e6f7a8b9c0d1',
    amount: 2875,
    paymentDate: '2025-07-10',
    paymentMethod: 'bank_transfer',
    reference: 'TXN-20250710-001',
  }),
});
const { data } = await res.json();
console.log(data.status); // completed
Handle rate limits with retryNode.js
async function apiFetch(url, options = {}, retries = 3) {
  for (let i = 0; i < retries; i++) {
    const res = await fetch(url, {
      ...options,
      headers: {
        Authorization: 'Bearer sk_live_YOUR_KEY',
        ...options.headers,
      },
    });
    if (res.status === 429) {
      const retryAfter = Number(res.headers.get('Retry-After') ?? 60);
      await new Promise(r => setTimeout(r, retryAfter * 1000));
      continue;
    }
    return res.json();
  }
  throw new Error('Max retries exceeded');
}
Verify a webhook signatureNode.js
import crypto from 'crypto';

export function verifyWebhook(payload, signature, secret) {
  const expected = crypto
    .createHmac('sha256', secret)
    .update(payload)
    .digest('hex');
  return crypto.timingSafeEqual(
    Buffer.from(expected),
    Buffer.from(signature),
  );
}

// In your webhook handler (e.g. Next.js route):
export async function POST(req) {
  const raw = await req.text();
  const sig = req.headers.get('x-syncbooks-signature');
  if (!verifyWebhook(raw, sig, process.env.WEBHOOK_SECRET)) {
    return new Response('Unauthorized', { status: 401 });
  }
  const event = JSON.parse(raw);
  if (event.type === 'invoice.paid') {
    // handle paid invoice
  }
  return new Response('OK');
}
🐍

Python

List all customersPython
import requests

BASE = 'https://api.yourdomain.com/api/v1'
HEADERS = {'Authorization': 'Bearer sk_live_YOUR_KEY'}

res = requests.get(f'{BASE}/customers', headers=HEADERS)
customers = res.json()['data']
for c in customers:
    print(c['name'], c['email'])
Create an expensePython
import requests
from datetime import date

res = requests.post(
    'https://api.yourdomain.com/api/v1/expenses',
    headers={
        'Authorization': 'Bearer sk_live_YOUR_KEY',
        'Content-Type': 'application/json',
    },
    json={
        'date': str(date.today()),
        'amount': 450.00,
        'description': 'Office supplies',
        'categoryId': '65f1a2b3c4d5e6f7a8b9c0d1',
        'paymentMethod': 'cash',
        'status': 'approved',
    },
)
print(res.json()['data']['_id'])
Get income statement reportPython
import requests

res = requests.get(
    'https://api.yourdomain.com/api/v1/reports/profit-loss',
    headers={'Authorization': 'Bearer sk_live_YOUR_KEY'},
    params={
        'startDate': '2025-01-01',
        'endDate': '2025-06-30',
    },
)
report = res.json()['data']
print(f"Revenue: {report['totalRevenue']}")
print(f"Net Income: {report['netIncome']}")
Paginate through all invoicesPython
import requests

BASE = 'https://api.yourdomain.com/api/v1'
HEADERS = {'Authorization': 'Bearer sk_live_YOUR_KEY'}

page, all_invoices = 1, []
while True:
    res = requests.get(
        f'{BASE}/invoices',
        headers=HEADERS,
        params={'page': page, 'limit': 50},
    ).json()
    all_invoices.extend(res['data'])
    if len(all_invoices) >= res['total']:
        break
    page += 1

print(f'Fetched {len(all_invoices)} invoices')
🖥️

cURL

Get invoice summarycURL
curl https://api.yourdomain.com/api/v1/invoices/summary \
  -H "Authorization: Bearer sk_live_YOUR_KEY"
Create a journal entrycURL
curl -X POST https://api.yourdomain.com/api/v1/journal-entries \
  -H "Authorization: Bearer sk_live_YOUR_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "date": "2025-07-01",
    "description": "Monthly depreciation",
    "lines": [
      { "accountId": "65f...depreciation-expense", "debit": 500, "credit": 0 },
      { "accountId": "65f...accumulated-depreciation", "debit": 0, "credit": 500 }
    ]
  }'
List bills with status filtercURL
curl "https://api.yourdomain.com/api/v1/bills?status=unpaid&page=1&limit=20" \
  -H "Authorization: Bearer sk_live_YOUR_KEY"
Delete an expensecURL
curl -X DELETE https://api.yourdomain.com/api/v1/expenses/65f1a2b3c4d5e6f7a8b9c0d1 \
  -H "Authorization: Bearer sk_live_YOUR_KEY"
Generate an API keycURL
curl -X POST https://api.yourdomain.com/api/v1/keys/generate \
  -H "Authorization: Bearer sk_live_ADMIN_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Zapier Integration",
    "scopes": ["invoices:read", "payments:read", "customers:read"]
  }'
🐘

PHP

List invoicesPHP
<?php
$ch = curl_init('https://api.yourdomain.com/api/v1/invoices?status=sent');
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => ['Authorization: Bearer sk_live_YOUR_KEY'],
]);
$response = json_decode(curl_exec($ch), true);
curl_close($ch);

foreach ($response['data'] as $invoice) {
    echo $invoice['invoiceNumber'] . ' — ' . $invoice['totalAmount'] . PHP_EOL;
}
Create a customerPHP
<?php
$data = json_encode([
    'name'  => 'Acme Corporation',
    'email' => 'billing@acme.com',
    'phone' => '+233201234567',
]);

$ch = curl_init('https://api.yourdomain.com/api/v1/customers');
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST           => true,
    CURLOPT_POSTFIELDS     => $data,
    CURLOPT_HTTPHEADER     => [
        'Authorization: Bearer sk_live_YOUR_KEY',
        'Content-Type: application/json',
    ],
]);
$result = json_decode(curl_exec($ch), true);
curl_close($ch);
echo 'Created: ' . $result['data']['_id'];