Developer documentation

Invoice API

Dual-mode invoice API for any service business: persist invoices into the same tables as the Surveai UI, or render a template-faithful PDF with no database write. Authenticate with API keys (sai_…) from Profile. Pro subscription required.

Overview

The Invoice API (External Invoice API) lets backends and integrations create invoices in a Surveai business account, generate PDFs without saving, read invoice metadata, and download template-styled PDFs—without using the web UI session.

  • POST /api/v1/invoices — persist an invoice (same tables as the app; allocates invoice number)
  • POST /api/v1/invoices/render — generate PDF only (no invoice row / number sequence; Surveai does not store the PDF). Use return_url: true for a ~10 min link, or omit it to receive raw application/pdf bytes to host yourself
  • GET /api/v1/invoices/:id — fetch invoice metadata
  • GET /api/v1/invoices/:id/pdf — download PDF for a persisted invoice (same HTML templates as the app)
  • GET /api/v1/invoices (no id) returns 405 — there is no list/audit endpoint. Keep create responses or your own records; a future list API is not available today.

Prerequisites

  1. An active Pro subscription (or trial/complimentary Pro access) on the business account.
  2. Create an API key in Profile → External Invoice API keys. Keys are shown once as sai_….
  3. Call the API from a trusted server—never from a public frontend.

Authentication

Send the raw API key in the Authorization header as a Bearer token:

Header
Authorization: Bearer sai_<prefix>_<secret>
In your client
-H "Authorization: Bearer sai_YOUR_PREFIX_YOUR_SECRET"
  • Missing token → 401 with Missing Bearer token
  • Invalid or revoked key → 401 with Invalid or revoked API key

Base URL

Origin
https://surveai.com

All paths below are relative to this origin (for example https://surveai.com/api/v1/invoices).

Quick start examples

Copy a language tab below. Store your key in an environment variable (SURVEAI_API_KEY) — never ship it to browsers.

1. Generate PDF only (+ return_url)

Recommended when you only need a Surveai-branded PDF and nothing should appear in invoice lists / books. Set return_url: true for a short-lived pdf_url (~10 min, no Bearer on download), or omit it / accept application/pdf and save the bytes yourself for permanent hosting. Optional business_* fields override the PDF header address block.

POST /api/v1/invoices/render
import os
import requests

API_KEY = os.environ["SURVEAI_API_KEY"]  # sai_…
BASE_URL = os.environ.get("SURVEAI_BASE_URL", "https://surveai.com").rstrip("/")

payload = {
    "return_url": True,
    "customer_name": "John Doe",
    "customer_phone": "+1-555-0100",
    "customer_email": "john.doe@example.com",
    "staff_name": "Jane Smith",
    "business_name": "Acme Services",
    "business_address": "123 Main Street",
    "business_city": "Springfield",
    "business_state": "CA",
    "business_country": "US",
    "business_phone": "+1-555-0199",
    "invoice_number": "EXT-1001",
    "currency": "USD",
    "items": [
        {"description": "Consulting session", "quantity": 1, "rate": 2500},
    ],
    "subtotal": 2500,
    "tax_rate": 18,
    "tax": 450,
    "grand_total": 2950,
    "amount_paid": 0,
    "outstanding_payment": 2950,
}

res = requests.post(
    f"{BASE_URL}/api/v1/invoices/render",
    headers={
        "Authorization": f"Bearer {API_KEY}",
        "Content-Type": "application/json",
        "Accept": "application/json",
    },
    json=payload,
    timeout=60,
)
print(res.status_code, res.text)  # inspect before raise_for_status
res.raise_for_status()
data = res.json()
print(data["pdf_url"])       # short-lived; open without Bearer
print(data["expires_at"])

2. Create invoice (persist)

Saves the invoice, allocates a number, and returns a durable pdf_url (download with the same Bearer key).

POST /api/v1/invoices
const API_KEY = process.env.SURVEAI_API_KEY; // sai_…
const BASE_URL = "https://surveai.com";

const res = await fetch(`${BASE_URL}/api/v1/invoices`, {
  method: "POST",
  headers: {
    Authorization: `Bearer ${API_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    customer_name: "John Doe",
    customer_phone: "+1-555-0100",
    customer_email: "john.doe@example.com",
    staff_name: "Jane Smith",
    business_name: "Acme Services",
    business_address: "123 Main Street",
    business_city: "Springfield",
    business_state: "CA",
    business_country: "US",
    business_phone: "+1-555-0199",
    invoice_date: "2026-11-03",
    items: [
      { description: "Consulting session", quantity: 1, rate: 2500 },
      { description: "Service fee", quantity: 1, rate: 800 },
    ],
    subtotal: 3300,
    tax_rate: 18,
    tax: 594,
    grand_total: 3894,
    amount_paid: 3894,
    outstanding_payment: 0,
    payment_type: "UPI",
    currency: "INR",
    notes: "Paid in full",
  }),
});

if (!res.ok) {
  throw new Error(await res.text());
}

const invoice = await res.json();
console.log(invoice.id, invoice.invoice_number);
console.log(invoice.pdf_url); // durable; GET with same Bearer (invoices:read)

Create invoice (persist)

POST/api/v1/invoices
scope invoices:write→ 201

Saves to the same invoice tables as the Surveai UI (stock, customers, numbering). Your business account ID is taken from the API key. Do not send account_id — ownership fields are ignored if present. Invoice numbers are assigned by Surveai (invoice_number in the body is ignored). Rows are tagged source: "external_api" with the creating api_key_id.

Totals are server-canonical. Surveai recomputes subtotal (Σ quantity × rate), tax from tax_rate / per-line tax, grand_total, and outstanding_payment from amount_paid. You may omit money totals or send values that match within ₹0.05; mismatched client totals return 400 with TOTALS_MISMATCH. PDF and DB always store the recomputed numbers. Negative rate, amounts, or tax_rate are rejected; quantity must be > 0. Unknown top-level JSON keys return 400 (UNKNOWN_FIELDS).

Request body

FieldTypeRequiredNotes
customer_namestringYesCustomer display name (also customerName)
customer_phonestringNoCustomer phone; stored hashed/encrypted for search & display (also customerPhone)
customer_emailstringNoOptional customer email (also customerEmail). Shown on the PDF billed-to block and mapped into template_field_values.email when templates show email.
itemsarray | object | stringNoLine items. Prefer [{ description, quantity, rate }, …]. quantity > 0; rate ≥ 0. Optional per-line tax_rate / amount must not be negative; amount must equal quantity × rate if sent.
invoice_datestringNoInvoice date (YYYY-MM-DD). When omitted, defaults to today (Asia/Kolkata calendar date). PDFs format dates by currency locale (INR → DD/MM/YYYY).
subtotalnumberNoOptional. Must match Σ quantity × rate (±0.05) when provided; otherwise omitted and computed.
tax_ratenumberNoTax rate percentage (≥ 0). Default 0. Used to compute tax.
taxnumberNoOptional. Must match server-computed tax (±0.05) when provided.
tax_breakdownobjectNoOptional structured tax breakdown (also taxBreakdown). Component amounts must sum to tax when provided.
grand_totalnumberNoOptional. Must match subtotal + tax (±0.05) when provided; PDF/DB use the recomputed total.
amount_paidnumberNoAmount already paid (≥ 0); sets paid_at when > 0. Default 0.
outstanding_paymentnumberNoOptional. Must match max(0, grand_total − amount_paid) (±0.05) when provided.
notesstringNoInternal / invoice notes
staff_namestringNoOptional staff or provider name shown on the invoice (also staffName)
business_namestringNoOptional business name on the PDF header (also businessName). Overrides account profile name when set.
business_addressstringNoOptional street / address line for the PDF header (also businessAddress, address_line1). Overrides account profile address when set.
business_citystringNoOptional city for the PDF header (also businessCity, city)
business_statestringNoOptional state / region for the PDF header (also businessState, state)
business_countrystringNoOptional country for the PDF header (also businessCountry, country)
business_phonestringNoOptional business phone on the PDF header (also businessPhone). Overrides account profile phone when set.
branch_idstring (UUID)NoBranch scope (also branchId)
currencystringNoISO currency code for PDF amounts: INR, AED, USD, SGD, EUR, or GBP. Symbol is derived (₹, $, …). When omitted: branch currency → business profile currency → INR.
payment_typestringNoe.g. Cash, UPI, Card
project_idstring (UUID)NoLink to a project (also projectId)
purchase_order_idstring (UUID)NoLink to a PO (also purchaseOrderId)
agenumberNoOptional age field
template_idstring (UUID)NoOptional invoice template id (must belong to this business account). When omitted, the account default template is attached (same as the vendor UI).
template_field_valuesobjectNoCustom template field values. When omitted with a resolved template, defaults from the template schema are applied.
public_order_idstringNoOptional public shop order enrichment (also publicOrderId)
Request
curl -X POST https://surveai.com/api/v1/invoices \
  -H "Authorization: Bearer sai_YOUR_PREFIX_YOUR_SECRET" \
  -H "Content-Type: application/json" \
  -d '{
    "customer_name": "John Doe",
    "customer_phone": "+1-555-0100",
    "customer_email": "john.doe@example.com",
    "staff_name": "Jane Smith",
    "business_name": "Acme Services",
    "business_address": "123 Main Street",
    "business_city": "Springfield",
    "business_state": "CA",
    "business_country": "US",
    "business_phone": "+1-555-0199",
    "invoice_date": "2026-11-03",
    "items": [
      { "description": "Consulting session", "quantity": 1, "rate": 2500 },
      { "description": "Service fee", "quantity": 1, "rate": 800 }
    ],
    "subtotal": 3300,
    "tax_rate": 18,
    "tax": 594,
    "grand_total": 3894,
    "amount_paid": 3894,
    "outstanding_payment": 0,
    "payment_type": "UPI",
    "currency": "INR",
    "notes": "Paid in full"
  }'
201 Created — example JSON
{
  "id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
  "account_id": "your-account-uid",
  "customer_id": null,
  "customer_name": "John Doe",
  "customer_phone": "+1-555-0100",
  "customer_email": "john.doe@example.com",
  "staff_name": "Jane Smith",
  "business_name": "Acme Services",
  "business_address": "123 Main Street",
  "business_city": "Springfield",
  "business_state": "CA",
  "business_country": "US",
  "business_phone": "+1-555-0199",
  "invoice_number": "1042",
  "invoice_date": "2026-11-03",
  "items": [
    { "description": "Consulting session", "quantity": 1, "rate": 2500 },
    { "description": "Service fee", "quantity": 1, "rate": 800 }
  ],
  "subtotal": 3300,
  "tax_rate": 18,
  "tax": 594,
  "tax_breakdown": null,
  "grand_total": 3894,
  "amount_paid": 3894,
  "outstanding_payment": 0,
  "notes": "Paid in full",
  "age": null,
  "branch_id": null,
  "payment_type": "UPI",
  "project_id": null,
  "purchase_order_id": null,
  "template_id": "tpl-uuid-or-default",
  "template_field_values": {},
  "currency": "INR",
  "paid_at": "2026-11-03T10:15:00.000Z",
  "source": "external_api",
  "api_key_id": "key-uuid",
  "created_at": "2026-11-03T10:15:00.000Z",
  "updated_at": "2026-11-03T10:15:00.000Z",
  "stock_warnings": [],
  "pdf_url": "https://surveai.com/api/v1/invoices/a1b2c3d4-e5f6-7890-abcd-ef1234567890/pdf"
}

Successful responses include an absolute pdf_url pointing at GET /api/v1/invoices/:id/pdf. Download that URL with the same Authorization: Bearer sai_… header (invoices:read). Responses may also include stock_warnings from catalog stock tracking. Response fields such as account_id, customer_name, and business_name map to your business account ID, customer name, and business/location label.

Generate PDF only

POST/api/v1/invoices/render
scope invoices:write

Same request body validation as create, but never creates an invoice row (nothing in lists / books), no invoice number allocation, and Surveai does not store the PDF (except a ~10 min in-memory token when return_url is set). Account branding and invoice templates are read read-only. You may pass invoice_number for display on the PDF only (defaults to DRAFT), and optional business_* fields to override the header address block. Use this when an external system owns the ledger and only needs Surveai layout/PDF.

FieldTypeRequiredNotes
(shared fields)—NoSame body as POST /api/v1/invoices (customer_name, items, totals, template_id, …)
invoice_numberstringNoOptional display-only number on the PDF. Not allocated or stored.
template_idstring (UUID)NoOptional; falls back to account default template when omitted.
currencystringNoSame as create: INR, AED, USD, SGD, EUR, GBP. Controls PDF symbols via getCurrencySymbol. Default: branch → business profile → INR.
return_urlbooleanNoWhen true (or Accept: application/json / ?as=json), respond with JSON { pdf_url, expires_at } instead of raw PDF bytes. Short-lived (~10 min) in-memory token only — Surveai does not store render PDFs.

Short-lived download link

Pass return_url: true, send Accept: application/json, or use ?as=json. The API caches the PDF in memory (~10 minutes, process-local) and returns a token URL you can open in a browser without a Bearer header. On multi-instance / serverless fleets the link may 404 if a different instance handled the download — omit return_url and save the raw PDF bytes yourself, or persist an invoice for a Bearer-authenticated pdf_url. Use BASE_URL.rstrip("/") when joining paths.

return_url request
curl -X POST https://surveai.com/api/v1/invoices/render \
  -H "Authorization: Bearer sai_YOUR_PREFIX_YOUR_SECRET" \
  -H "Content-Type: application/json" \
  -H "Accept: application/json" \
  -d '{
    "return_url": true,
    "customer_name": "John Doe",
    "customer_phone": "+1-555-0100",
    "customer_email": "john.doe@example.com",
    "staff_name": "Jane Smith",
    "business_name": "Acme Services",
    "business_address": "123 Main Street",
    "business_city": "Springfield",
    "business_state": "CA",
    "business_country": "US",
    "business_phone": "+1-555-0199",
    "invoice_number": "EXT-1001",
    "currency": "USD",
    "items": [
      { "description": "Consulting session", "quantity": 1, "rate": 2500 }
    ],
    "subtotal": 2500,
    "tax_rate": 18,
    "tax": 450,
    "grand_total": 2950,
    "amount_paid": 0,
    "outstanding_payment": 2950
  }'
200 — short-lived JSON
{
  "pdf_url": "https://surveai.com/api/v1/invoices/render/AbCdEf…token",
  "expires_at": "2026-11-03T10:25:00.000Z",
  "persisted": false,
  "currency": "USD",
  "filename": "invoice-EXT-1001.pdf",
  "content_type": "application/pdf",
  "note": "Short-lived download link (~10 min, process-local cache). Open in a browser or GET without Bearer. For a permanent file, omit return_url and save the application/pdf response yourself (or persist an invoice)."
}
GET token URL (no Bearer)
curl -L "https://surveai.com/api/v1/invoices/render/TOKEN" \
  -o draft-invoice.pdf

Recommended for permanent files — raw PDF bytes

Omit return_url (and prefer Accept: application/pdf or */*) to receive application/pdf directly. Save and host the file on your side — Surveai does not store render PDFs. Response headers include X-Surveai-Invoice-Persisted: false.

curl (application/pdf)
curl -X POST https://surveai.com/api/v1/invoices/render \
  -H "Authorization: Bearer sai_YOUR_PREFIX_YOUR_SECRET" \
  -H "Content-Type: application/json" \
  -o draft-invoice.pdf \
  -d '{
    "customer_name": "John Doe",
    "customer_phone": "+1-555-0100",
    "invoice_number": "EXT-1001",
    "currency": "USD",
    "items": [
      { "description": "Consulting session", "quantity": 1, "rate": 2500 }
    ],
    "subtotal": 2500,
    "tax_rate": 18,
    "tax": 450,
    "grand_total": 2950,
    "amount_paid": 0,
    "outstanding_payment": 2950
  }'

Get invoice metadata

GET/api/v1/invoices/:id
scope invoices:read→ 200

Returns the same public invoice shape as create (no ciphertext), plus absolute pdf_url. Only invoices owned by the API key's business account are visible.

curl
curl https://surveai.com/api/v1/invoices/INVOICE_ID \
  -H "Authorization: Bearer sai_YOUR_PREFIX_YOUR_SECRET"

No list endpoint

GET /api/v1/invoices (without an id) returns 405 Method Not Allowed with Allow: POST. Clients cannot list or audit invoices through a collection API — persist the create response (or call GET /api/v1/invoices/:id when you already know the id). A future list endpoint is not implemented.

Download PDF

GET/api/v1/invoices/:id/pdf
scope invoices:read→ 200 application/pdf

Durable download for a persisted invoice (same URL as create/get pdf_url). Requires Bearer API key. Returns a PDF attachment (Content-Disposition: attachment). Filename is typically invoice-{invoice_number}.pdf. Rendering uses the same buildInvoiceHtml path as the in-app preview (Standard / Cash Bill / professional / tax layouts, logo, template fields), converted to PDF with Chromium.

Download pdf_url
curl -L "https://surveai.com/api/v1/invoices/INVOICE_ID/pdf" \
  -H "Authorization: Bearer sai_YOUR_PREFIX_YOUR_SECRET" \
  -o invoice.pdf

Generate PDF only also exposes GET /api/v1/invoices/render/:token for short-lived return_url links only (no Bearer; ~10 min in-memory — see Generate PDF only). For a permanent file, save the raw application/pdf from POST …/render.

Templates & PDF fidelity

  • Omit template_id to attach the account's default invoice template (or the first available template).
  • Pass an explicit template_id owned by the API key's business account to select Standard, Cash Bill, professional, tax layouts, etc.
  • PDFs are HTML→PDF (puppeteer-core). Locally, Chrome/Edge must be installed (or set PUPPETEER_EXECUTABLE_PATH). On Vercel/Lambda, use @sparticuz/chromium-min with CHROMIUM_REMOTE_EXEC_PATH pointing at a hosted Chromium pack (bundle size limits).

Errors

StatusWhenBody
401Missing, invalid, or revoked Bearer key{ "error": "…" }
402Account is not on Pro / premium access{ "error": "Active Pro subscription required", "code": "SUBSCRIPTION_REQUIRED" }
403API key missing required scope{ "error": "Missing required scope: …" }
404Invoice id not found for this account{ "error": "Invoice not found" }
429Rate limit (default 60 requests / minute per key). Includes Retry-After header.{ "error": "Rate limit exceeded", "retry_after": <seconds> }
400 / 409Validation / business rules — missing customer_name, negative amounts (NEGATIVE_AMOUNT), totals mismatch (TOTALS_MISMATCH), unknown fields (UNKNOWN_FIELDS), stock, duplicate number{ "error": "…", "code"?: "…", "details"?: … }
405GET /api/v1/invoices — no list endpoint{ "error": "…", "code": "METHOD_NOT_ALLOWED" }

Scopes & account scoping

  • Default key scopes: invoices:read, invoices:write
  • Create + render require invoices:write; get + persisted PDF require invoices:read
  • Every key is bound to the business account that created it. Invoices are always created and looked up under that account's ID (returned as account_id). Clients cannot impersonate another account by sending a different ownership id in the body.

Ready to integrate?

Create a Pro account, generate a key in Profile, then POST your first invoice with customer_name.