Integration guide
Add CAS reading to your app
Build your import screen with an invented statement. Then connect the hosted API from your backend, or keep statements on the device with the browser SDK.
1. Render an invented statement
Download the sample JSON and serve it from your app at /samples/dev-sample.json. You can build the UI with the same fields the hosted API returns, without an API key, account or credits.
Add this output to your page and use the script in your frontend module. Serve both files from the same origin.
<p id="cas-preview" role="status">Loading the sample…</p>
<script type="module" src="/cas-preview.js"></script>
// cas-preview.js
const preview = document.querySelector("#cas-preview");
try {
const response = await fetch("/samples/dev-sample.json");
if (!response.ok) throw new Error("Sample unavailable");
const result = await response.json();
if (result.api !== "sachfolio.v1" ||
result.document.schemaVersion !== "1" ||
result.analytics.analyticsVersion !== "2") {
throw new Error("Unexpected response format");
}
const { included, excluded } = result.analytics.portfolio.holdings;
preview.textContent = `${included} holdings included. ${excluded} left out.`;
} catch {
preview.textContent = "The example statement could not be loaded.";
}
Expect four holdings included and one left out. The invented PDF has a value that fails the units × NAV check on purpose. You can trace it in the sample PDF or see the public API sample.
2. Choose where the PDF is read
Connect the hosted API from your backend, or let the SDK read the PDF on the device.
Hosted API
Use this route when your users agree to send their PDF to your server for processing by Sachfolio. Start the Business trial, copy your API key from the dashboard, and set SACHFOLIO_API_KEY in your server's secrets. The trial includes five statement reads for 30 days.
On Node 22, save this as read-cas.mjs. Call it from an authenticated upload route that limits request size before buffering the file. The server sends raw PDF bytes with application/pdf.
// read-cas.mjs (server only)
export async function readCas(pdfBytes, { password, sample = false } = {}) {
const key = process.env.SACHFOLIO_API_KEY;
if (!key) throw new Error("Missing server API key");
if (pdfBytes.byteLength > 4 * 1024 * 1024) {
return { ok: false, code: "TOO_LARGE" };
}
const url = new URL("https://api.sachfolio.com/v1/parse");
url.searchParams.set("include", "analytics,gains");
url.searchParams.set("redact", "true");
if (sample) url.searchParams.set("sample", "true");
const headers = {
"content-type": "application/pdf",
"x-api-key": key,
};
if (password) headers["x-pdf-password"] = password;
const response = await fetch(url, {
method: "POST",
headers,
body: pdfBytes,
cache: "no-store",
signal: AbortSignal.timeout(30_000),
});
const result = await response.json().catch(() => null);
if (!response.ok || !result) {
return {
ok: false,
code: result?.error?.code ?? "UPSTREAM_ERROR",
requestId: result?.request_id,
};
}
return { ok: true, result };
}
Save the original sample PDF as dev-sample.pdf. Exercise the authenticated upload with these exact bytes. Sample mode accepts the published sample PDFs and uses no credits.
import { readFile } from "node:fs/promises";
import { readCas } from "./read-cas.mjs";
const check = await readCas(await readFile("dev-sample.pdf"), { sample: true });
For a permitted real statement, call readCas(pdfBytes, { password }) without the sample option. Supply the password only for a protected PDF. A read that returns a result uses one statement credit. See the OpenAPI reference for the full transport, limits and error codes.
Browser SDK
This route keeps the statement and its password in the user's browser. Try the invented PDF locally with no account, key or credits.
npm install @sachfolio/cas-reader
npx sachfolio-cas dev-sample.pdf
npx sachfolio-cas copy-assets public/pdfjs
Serve public/pdfjs at /pdfjs/ on your app's origin. Pass the selected File to the browser SDK from your file picker.
import { createCasReader, analyze, gains, fmv2018FromPack } from "@sachfolio/cas-reader/browser";
import nav2018 from "@sachfolio/cas-reader/refdata/nav-2018-01-31.json";
const reader = createCasReader({ assetsUrl: "/pdfjs/" });
const cas = await reader.readCas(
new Uint8Array(await file.arrayBuffer()), { password },
);
const result = {
document: cas,
analytics: analyze(cas),
gains: gains(cas, { fmv2018: fmv2018FromPack(nav2018) }),
};
The 31 Jan 2018 NAVs give grandfathered equity lots their value. In Node, readGains(cas) from @sachfolio/cas-reader/node loads them for you.
For a commercial app, reserve SDK reads in the Business dashboard using your organisation and app identifier. SDK 0.3.0 and later support Business codes with checkAppLicence(code). Use the verified app identifier and credit count to track usage in your app.
What the SDK does
@sachfolio/cas-reader on npm. Each line links to its section of the package README.
- Browser and Node readers for CAMS, KFintech, NSDL and CDSL statements, with progress, limits and cancelling.
- Returns: XIRR per scheme and for the portfolio, with the reason where it can't be worked out.
- Capital gains lot by lot, and the Schedule 112A CSV for the e-filing portal (ITR-2 or ITR-3).
- Dividends, TDS, STT and stamp duty by financial year, as printed.
- AIS match: the statement's sales against those the Annual Information Statement lists.
- Two statements compared by holding, or one holding against another app's value.
- CSV of holdings and transactions, and casparser's JSON shape.
- Scheme category from the printed name, and the registrars' request forms and password rules.
- Redaction and a privacy class for every field, plus a JSON Schema for the output.
- Command line
sachfolio-cas: PDF to JSON, browser assets, licence check and upgrade review. - Python and AI assistants: a Python wrapper over the command line, and a local MCP server.
3. Handle partial results and protect real statements
- Read
document.coverageanddocument.warnings. Show the user if the parser skipped rows or could not read part of the statement. - Use
analytics.schemes[].holdings.eligiblefor totals and show the accompanying reasons for exclusions. Check returns and gains eligibility separately. Keep amounts as decimal strings and retain page references for review. - For API errors, branch on
error.code. Ask for the password again onNEED_PASSWORDorINCORRECT_PASSWORD. Keeprequest_idfor support and handle timeouts and network failures in your backend. - Keep your API key server-side. For a hosted read, use the PDF password only for that request. Keep uploads, passwords and full results out of logs, analytics and shared caches. The hosted API reads the PDF in memory in Mumbai.
redact=trueremoves identifying fields from its response, which still contains financial data.
See Business allowances · Read how Business handles statements