Archive via the API
Archiving copies flagged Knack records into CSV files and then deletes them from Knack or resets their flag. The API runs the archive settings you’ve created in the app. Read the archive overview first if you haven’t set one up.
The usual sequence:
- Find the archive setting.
- Dry run: see how many records are flagged and how many Knack API calls a run would use. Nothing starts.
- Test run: write the files but change nothing in Knack.
- Real run.
- Wait for the run, then download its files.
- Later, look up where a given record went.
| Step | Endpoint | Scope |
|---|---|---|
| List settings | GET /apps/<appId>/archive-configs |
read |
| Dry run, test run | POST /apps/<appId>/archive-configs/<configId>/run |
write |
| Real run (setting not in test mode) | POST /apps/<appId>/archive-configs/<configId>/run |
write and archive:run |
| Check a run | GET /archive-runs/<runId> |
read |
| Download a file | GET /archive-runs/<runId>/files/<fileId>/download |
data:query |
| Look up a record | GET /apps/<appId>/archive/lookup?key=... |
read |
In HIPAA workspaces, downloading files and looking up records also need phi:read. See HIPAA workspaces. Archive runs also need a plan that includes Archive; otherwise you get 402 PLAN_REQUIRED.
1. Find the archive setting
GET /apps/<appId>/archive-configs lists the app’s archive settings:
{
"data": [
{
"id": "cfg_7Qm2",
"name": "Closed orders",
"tables": [
{ "objectKey": "object_4", "flagField": "field_31", "keyField": "field_12", "fields": [] }
],
"afterArchive": "delete",
"schedule": "manual",
"testMode": true,
"enabled": true,
"destination": { "type": "knack" },
"nextRunAt": null,
"lastRunAt": "2026-11-28T09:00:00.000Z",
"lastJobId": "Jb3k2LxQ9",
"createdAt": "2026-11-20T15:10:00.000Z"
}
],
"nextCursor": null
}
The fields to look at before running:
testMode:truemeans a run writes files but changes nothing in Knack.afterArchive:deleteremoves archived records from Knack;reset_flagkeeps them and clears the flag field.destination.type: where files go (knack,gcs,s3,azure,gdriveoronedrive).nullmeans none is chosen yet, and runs will fail until one is.
You can also create settings with POST /apps/<appId>/archive-configs and change them with PATCH /apps/<appId>/archive-configs/<configId> (fields you leave out keep their values). They’re validated like the app’s wizard. Turning on deletion outside test mode for the first time needs "confirmDeletion": true, and tables with file or image fields need "acknowledgeFiles": true; without them you get 400 CONFIRMATION_REQUIRED. Bucket and drive destinations have to be connected in the app first. The API reference has the full request body.
2. Dry run
Send {"dryRun": true} to the run endpoint. It counts today’s flagged records in Knack and estimates the run. It starts nothing, and it uses one Knack API call per table to count. It answers 202 like a real run, but with an estimate instead of a job id:
{
"dryRun": true,
"tables": [{ "objectKey": "object_4", "flagged": 1840, "calls": 1868 }],
"calls": 1868,
"seconds": 234,
"assets": false,
"budget": {
"limit": 2000,
"used": 340,
"share": 1800,
"left": 1460,
"knackRemaining": 4100,
"knackPlanLimit": 25000,
"knackReserve": null,
"resetAt": "2026-12-02T00:00:00.000Z"
}
}
tables[].flagged: records flagged for archive now;tables[].callsandcalls: Knack API calls the run would use.seconds: a rough duration at Knack’s request rate.assets:trueif a deleting run includes records with files or images (keeping those adds calls not counted here).budget: today’s Knack API budget for archive. Ifcallsis more thanbudget.left, the run pauses (paused_budget) when the budget runs out and carries on afterresetAt. See Knack API budget.
3. Test run
A run of a setting with testMode: true writes the CSV files but doesn’t delete or change anything in Knack. It needs only the write scope. Send an empty body (or {"dryRun": false}):
{ "jobId": "Jb3k2LxQ9" }
If the setting isn’t in test mode, switch it with PATCH /apps/<appId>/archive-configs/<configId> and {"testMode": true}, run it, check the files, then switch it back with {"testMode": false}.
4. Real run
Running a setting with testMode: false removes records from Knack (or resets their flag), so the key needs archive:run as well as write. Without it you get 403 PERMISSION_DENIED. The response is the same { "jobId": ... }.
Only one run per setting at a time: a second request while one runs, or while a restore of that setting runs, returns 409 JOB_ACTIVE. Send an Idempotency-Key so a retried request can’t start a second run (see errors and rate limits).
curl
BASE=https://api.vaultlens.studio/v1
# Dry run: what would a run do?
curl -s -X POST "$BASE/apps/<appId>/archive-configs/<configId>/run" \
-H "Authorization: Bearer $VAULTLENS_API_KEY" \
-H "Content-Type: application/json" \
-d '{"dryRun": true}'
# Start the run (a test run if the setting is in test mode).
curl -s -X POST "$BASE/apps/<appId>/archive-configs/<configId>/run" \
-H "Authorization: Bearer $VAULTLENS_API_KEY" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: archive-closed-orders-$(date -u +%F)" \
-d '{}'
Node
const BASE = 'https://api.vaultlens.studio/v1';
const auth = { Authorization: `Bearer ${process.env.VAULTLENS_API_KEY}` };
const appId = '<appId>';
const configId = '<configId>';
async function run(body, idempotencyKey) {
const res = await fetch(`${BASE}/apps/${appId}/archive-configs/${configId}/run`, {
method: 'POST',
headers: {
...auth,
'Content-Type': 'application/json',
...(idempotencyKey ? { 'Idempotency-Key': idempotencyKey } : {}),
},
body: JSON.stringify(body),
});
const json = await res.json();
if (!res.ok) throw new Error(`${json.error.code}: ${json.error.message}`);
return json;
}
const estimate = await run({ dryRun: true });
console.log(
`flagged: ${estimate.tables.map((t) => t.flagged)}, calls: ${estimate.calls}, left: ${estimate.budget.left}`,
);
if (estimate.calls <= estimate.budget.left) {
const { jobId } = await run({}, `archive-${configId}-${new Date().toISOString().slice(0, 10)}`);
console.log('started', jobId);
}
Python
import datetime
import os
import requests
BASE = "https://api.vaultlens.studio/v1"
AUTH = {"Authorization": f"Bearer {os.environ['VAULTLENS_API_KEY']}"}
app_id, config_id = "<appId>", "<configId>"
def run(body, idempotency_key=None):
headers = dict(AUTH)
if idempotency_key:
headers["Idempotency-Key"] = idempotency_key
res = requests.post(
f"{BASE}/apps/{app_id}/archive-configs/{config_id}/run",
json=body,
headers=headers,
timeout=60,
)
data = res.json()
if not res.ok:
raise RuntimeError(f"{data['error']['code']}: {data['error']['message']}")
return data
estimate = run({"dryRun": True})
print("calls:", estimate["calls"], "left:", estimate["budget"]["left"])
if estimate["calls"] <= estimate["budget"]["left"]:
started = run({}, f"archive-{config_id}-{datetime.date.today().isoformat()}")
print("started", started["jobId"])
5. Wait for the run and download its files
The run’s jobId is also its runId. Poll GET /archive-runs/<runId> (every 15 to 30 seconds) until state is completed, completed_with_errors, failed or cancelled; the states are the same as for syncs (see run a sync). Or subscribe to the archive.run.completed and job.failed webhooks (job.failed carries jobType: "archive"). archive.run.completed is sent for test runs too.
A finished run, with its files:
{
"id": "Jb3k2LxQ9",
"appId": "6b05a32b031b09796ccc7d52",
"type": "archive",
"state": "completed",
"finishedAt": "2026-12-01T18:06:40.000Z",
"apiCalls": 1870,
"error": null,
"archive": {
"configId": "cfg_7Qm2",
"testMode": false,
"afterArchive": "delete",
"selected": 1840,
"archived": 1840,
"removed": 1840,
"files": 1
},
"files": [
{
"fileId": "0",
"objectKey": "object_4",
"rows": 1840,
"sha256": "9f2c4e0b7d...",
"location": "Archive Runs › Orders 2026-12-01.csv",
"format": "vls-archive/2",
"downloadable": true
}
]
}
archive.selected, archived and removed count records picked, written to files and removed (or un-flagged) in Knack; in a test run removed stays 0. To list runs, use GET /archive-runs?appId=<appId> (newest first, paged with cursor).
GET /archive-runs/<runId>/files/<fileId>/download returns the file as text/csv, with a Content-Disposition filename and an X-Content-SHA256 header. VaultLens fetches it from where the run wrote it and checks it against the SHA-256 recorded at run time before sending it. Every download is recorded in the workspace’s audit log.
- Files in your own bucket (
gcs,s3,azure) showdownloadable: false: VaultLens can write there but not read back. Downloading them returns409 UPLOAD_REQUIREDwith the file’s location; get them from the bucket. - If the stored file no longer matches the run’s SHA-256, you get
400 FILE_MISMATCH.
curl
BASE=https://api.vaultlens.studio/v1
curl -s "$BASE/archive-runs/<runId>" -H "Authorization: Bearer $VAULTLENS_API_KEY" \
| jq '{state, archive, files: [.files[] | {fileId, rows, downloadable}]}'
# -OJ saves under the filename from Content-Disposition; -D - prints the headers.
curl -s -OJ -D - "$BASE/archive-runs/<runId>/files/0/download" \
-H "Authorization: Bearer $VAULTLENS_API_KEY"
Node
import { createHash } from 'node:crypto';
import { writeFile } from 'node:fs/promises';
const BASE = 'https://api.vaultlens.studio/v1';
const auth = { Authorization: `Bearer ${process.env.VAULTLENS_API_KEY}` };
const runId = '<runId>';
const run = await (await fetch(`${BASE}/archive-runs/${runId}`, { headers: auth })).json();
for (const file of run.files.filter((f) => f.downloadable)) {
const res = await fetch(`${BASE}/archive-runs/${runId}/files/${file.fileId}/download`, {
headers: auth,
});
if (!res.ok) throw new Error(`HTTP ${res.status}: ${await res.text()}`);
const csv = Buffer.from(await res.arrayBuffer());
const sha = createHash('sha256').update(csv).digest('hex');
if (sha !== res.headers.get('x-content-sha256')) throw new Error('checksum mismatch');
await writeFile(`archive-${runId}-${file.fileId}.csv`, csv);
console.log(`saved ${file.rows} rows from ${file.objectKey}`);
}
Python
import hashlib
import os
import requests
BASE = "https://api.vaultlens.studio/v1"
AUTH = {"Authorization": f"Bearer {os.environ['VAULTLENS_API_KEY']}"}
run_id = "<runId>"
run = requests.get(f"{BASE}/archive-runs/{run_id}", headers=AUTH, timeout=30).json()
for f in run["files"]:
if not f["downloadable"]:
print("in your bucket:", f["location"])
continue
res = requests.get(
f"{BASE}/archive-runs/{run_id}/files/{f['fileId']}/download", headers=AUTH, timeout=120
)
res.raise_for_status()
if hashlib.sha256(res.content).hexdigest() != res.headers["X-Content-SHA256"]:
raise RuntimeError("checksum mismatch")
with open(f"archive-{run_id}-{f['fileId']}.csv", "wb") as out:
out.write(res.content)
print("saved", f["rows"], "rows from", f["objectKey"])
6. Look up an archived record
GET /apps/<appId>/archive/lookup?key=<value> finds which run and file a record went to, and whether it was restored since. key is the value of the setting’s archive key field (exact match, ignoring case and surrounding spaces) or a Knack record ID. It needs read and makes no Knack API calls.
{
"matches": [
{
"jobId": "Jb3k2LxQ9",
"chunk": 0,
"recordId": "5f1c0e9a2b3c4d5e6f708192",
"objectKey": "object_4",
"tableName": "Orders",
"runAt": "2026-12-01T18:00:00.000Z",
"settingName": "Closed orders",
"testMode": false,
"file": "Archive Runs › Orders 2026-12-01.csv",
"restored": null
}
]
}
jobId is the run’s id and chunk is the fileId to pass to the download endpoint. restored is null, or { "at", "newId", "restoreJobId" } when the record was put back in Knack (newId is its new Knack record ID). Matches are newest first, up to 50. An empty matches array means nothing was found.
curl
curl -s -G "https://api.vaultlens.studio/v1/apps/<appId>/archive/lookup" \
--data-urlencode "key=ORD-10442" \
-H "Authorization: Bearer $VAULTLENS_API_KEY"
Node
const url = new URL('https://api.vaultlens.studio/v1/apps/<appId>/archive/lookup');
url.searchParams.set('key', 'ORD-10442');
const res = await fetch(url, {
headers: { Authorization: `Bearer ${process.env.VAULTLENS_API_KEY}` },
});
const { matches } = await res.json();
for (const m of matches) console.log(m.jobId, m.chunk, m.restored ? 'restored' : 'archived');
Python
import os
import requests
res = requests.get(
"https://api.vaultlens.studio/v1/apps/<appId>/archive/lookup",
params={"key": "ORD-10442"},
headers={"Authorization": f"Bearer {os.environ['VAULTLENS_API_KEY']}"},
timeout=30,
)
res.raise_for_status()
for m in res.json()["matches"]:
print(m["jobId"], m["chunk"], "restored" if m["restored"] else "archived")
Restoring records isn’t part of the public API; do that from the app.