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). Usereturn_url: truefor a ~10 min link, or omit it to receive rawapplication/pdfbytes to host yourselfGET /api/v1/invoices/:id— fetch invoice metadataGET /api/v1/invoices/:id/pdf— download PDF for a persisted invoice (same HTML templates as the app)GET /api/v1/invoices(no id) returns405— there is no list/audit endpoint. Keep create responses or your own records; a future list API is not available today.
Prerequisites
- An active Pro subscription (or trial/complimentary Pro access) on the business account.
- Create an API key in Profile → External Invoice API keys. Keys are shown once as
sai_…. - 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:
Authorization: Bearer sai_<prefix>_<secret>-H "Authorization: Bearer sai_YOUR_PREFIX_YOUR_SECRET"- Missing token →
401withMissing Bearer token - Invalid or revoked key →
401withInvalid or revoked API key
Base URL
https://surveai.comAll 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.
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).
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)
/api/v1/invoicesinvoices:write→ 201Saves 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
| Field | Type | Required | Notes |
|---|---|---|---|
| customer_name | string | Yes | Customer display name (also customerName) |
| customer_phone | string | No | Customer phone; stored hashed/encrypted for search & display (also customerPhone) |
| customer_email | string | No | Optional customer email (also customerEmail). Shown on the PDF billed-to block and mapped into template_field_values.email when templates show email. |
| items | array | object | string | No | Line 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_date | string | No | Invoice date (YYYY-MM-DD). When omitted, defaults to today (Asia/Kolkata calendar date). PDFs format dates by currency locale (INR → DD/MM/YYYY). |
| subtotal | number | No | Optional. Must match Σ quantity × rate (±0.05) when provided; otherwise omitted and computed. |
| tax_rate | number | No | Tax rate percentage (≥ 0). Default 0. Used to compute tax. |
| tax | number | No | Optional. Must match server-computed tax (±0.05) when provided. |
| tax_breakdown | object | No | Optional structured tax breakdown (also taxBreakdown). Component amounts must sum to tax when provided. |
| grand_total | number | No | Optional. Must match subtotal + tax (±0.05) when provided; PDF/DB use the recomputed total. |
| amount_paid | number | No | Amount already paid (≥ 0); sets paid_at when > 0. Default 0. |
| outstanding_payment | number | No | Optional. Must match max(0, grand_total − amount_paid) (±0.05) when provided. |
| notes | string | No | Internal / invoice notes |
| staff_name | string | No | Optional staff or provider name shown on the invoice (also staffName) |
| business_name | string | No | Optional business name on the PDF header (also businessName). Overrides account profile name when set. |
| business_address | string | No | Optional street / address line for the PDF header (also businessAddress, address_line1). Overrides account profile address when set. |
| business_city | string | No | Optional city for the PDF header (also businessCity, city) |
| business_state | string | No | Optional state / region for the PDF header (also businessState, state) |
| business_country | string | No | Optional country for the PDF header (also businessCountry, country) |
| business_phone | string | No | Optional business phone on the PDF header (also businessPhone). Overrides account profile phone when set. |
| branch_id | string (UUID) | No | Branch scope (also branchId) |
| currency | string | No | ISO currency code for PDF amounts: INR, AED, USD, SGD, EUR, or GBP. Symbol is derived (₹, $, …). When omitted: branch currency → business profile currency → INR. |
| payment_type | string | No | e.g. Cash, UPI, Card |
| project_id | string (UUID) | No | Link to a project (also projectId) |
| purchase_order_id | string (UUID) | No | Link to a PO (also purchaseOrderId) |
| age | number | No | Optional age field |
| template_id | string (UUID) | No | Optional invoice template id (must belong to this business account). When omitted, the account default template is attached (same as the vendor UI). |
| template_field_values | object | No | Custom template field values. When omitted with a resolved template, defaults from the template schema are applied. |
| public_order_id | string | No | Optional public shop order enrichment (also publicOrderId) |
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"
}'{
"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
/api/v1/invoices/renderinvoices:writeSame 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.
| Field | Type | Required | Notes |
|---|---|---|---|
| (shared fields) | — | No | Same body as POST /api/v1/invoices (customer_name, items, totals, template_id, …) |
| invoice_number | string | No | Optional display-only number on the PDF. Not allocated or stored. |
| template_id | string (UUID) | No | Optional; falls back to account default template when omitted. |
| currency | string | No | Same as create: INR, AED, USD, SGD, EUR, GBP. Controls PDF symbols via getCurrencySymbol. Default: branch → business profile → INR. |
| return_url | boolean | No | When 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.
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
}'{
"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)."
}curl -L "https://surveai.com/api/v1/invoices/render/TOKEN" \
-o draft-invoice.pdfRecommended 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 -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
/api/v1/invoices/:idinvoices:read→ 200Returns 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 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
/api/v1/invoices/:id/pdfinvoices:read→ 200 application/pdfDurable 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.
curl -L "https://surveai.com/api/v1/invoices/INVOICE_ID/pdf" \
-H "Authorization: Bearer sai_YOUR_PREFIX_YOUR_SECRET" \
-o invoice.pdfGenerate 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_idto attach the account's default invoice template (or the first available template). - Pass an explicit
template_idowned 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-minwithCHROMIUM_REMOTE_EXEC_PATHpointing at a hosted Chromium pack (bundle size limits).
Errors
| Status | When | Body |
|---|---|---|
| 401 | Missing, invalid, or revoked Bearer key | { "error": "…" } |
| 402 | Account is not on Pro / premium access | { "error": "Active Pro subscription required", "code": "SUBSCRIPTION_REQUIRED" } |
| 403 | API key missing required scope | { "error": "Missing required scope: …" } |
| 404 | Invoice id not found for this account | { "error": "Invoice not found" } |
| 429 | Rate limit (default 60 requests / minute per key). Includes Retry-After header. | { "error": "Rate limit exceeded", "retry_after": <seconds> } |
| 400 / 409 | Validation / business rules — missing customer_name, negative amounts (NEGATIVE_AMOUNT), totals mismatch (TOTALS_MISMATCH), unknown fields (UNKNOWN_FIELDS), stock, duplicate number | { "error": "…", "code"?: "…", "details"?: … } |
| 405 | GET /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 requireinvoices: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.