Generate documents from API data

Fetch JSON from an API and merge it into a DocStudio template, validate the shape, choose a missing-data policy, and handle diagnostics and limits.

DocStudio does not care where the data comes from. Any JSON-compatible value works.

Fetch, then render

statement.ts
import { renderDocument } from 'docstudio';

export async function renderStatement(template: unknown, accountId: string): Promise<string> {
  const response = await fetch(`https://api.example.com/accounts/${encodeURIComponent(accountId)}`);
  if (!response.ok) throw new Error(`account request failed with ${String(response.status)}`);
  const data: unknown = await response.json();
  const result = renderDocument(template, data, {
    target: 'print',
    compile: { config: { missingData: 'warn' } },
  });
  if (!result.ok) throw new Error(result.diagnostics.map((item) => item.message).join('; '));
  return result.html;
}

Choose a missing-data policy

APIs return incomplete data. The default policy, placeholder, shows a dash. For production output set warn to be told, or error to fail the render when a value is missing. See data binding.

Check the shape you depend on

Templates read paths, so a renamed API field becomes a missing value. Two defences:

  • Set missingData to warn or error and surface the diagnostics in your monitoring.
  • Validate the response with your own validator before rendering.

Large responses

Data and templates are bounded before use, and repeaters have a maximum row count. A response over the limits returns a LIMIT_EXCEEDED diagnostic. Raise limits deliberately with normalizeLimits, and keep documents bounded by paging your data.

Do not trust the data

Data is rendered as escaped text, never as HTML. Still, authenticate and authorize the request that fetches it, and avoid putting secrets in documents.

JSON data, diagnostics and the business report example.

Last updated 2026-12-03