Skip to content

Documents

The Documents resource provides full CRUD operations for managing documents in Sonar.

List Documents

Retrieves a paginated list of documents with optional filters.

Endpoint: GET /api/sdk/v1/documents

Parameters (ListDocumentsParams)

ParameterTypeRequiredDefaultDescription
pagenumberNo1Page number (minimum: 1)
limitnumberNo20Items per page (minimum: 1, maximum: 100)
classificationDocumentClassificationNoFilter by: 'generated', 'uploaded', or 'signed'
isSignedbooleanNoFilter by signature status
typestringNoFilter by MIME type (e.g., 'application/pdf')
uploadFromDocumentUploadSourceNoFilter by upload source
sessionIdstringNoFilter by session ID (MongoDB ObjectId)
fromDatestring | DateNoFilter documents from this date (ISO 8601)
toDatestring | DateNoFilter documents up to this date (ISO 8601)

Response (ListDocumentsResponse)

FieldTypeDescription
docsDocument[]Array of document objects
totalDocsnumberTotal number of matching documents
limitnumberItems per page
totalPagesnumberTotal number of pages
pagenumberCurrent page number
pagingCounternumberSerial number of the first document on this page
hasPrevPagebooleanWhether a previous page exists
hasNextPagebooleanWhether a next page exists
prevPagenumber | nullPrevious page number or null
nextPagenumber | nullNext page number or null

Example

// Basic listing
const response = await sdk.documents.list();
console.log(response.docs); // Document[]
console.log(response.totalDocs); // total count
// With filters
const signedPDFs = await sdk.documents.list({
page: 1,
limit: 50,
classification: 'signed',
isSigned: true,
type: 'application/pdf',
fromDate: '2025-01-01T00:00:00Z',
toDate: new Date(),
});
// Pagination loop
let page = 1;
let hasMore = true;
while (hasMore) {
const result = await sdk.documents.list({ page, limit: 100 });
console.log(`Page ${page}: ${result.docs.length} documents`);
hasMore = result.hasNextPage;
page++;
}

Get a Document

Retrieves a single document by its ID.

Endpoint: GET /api/sdk/v1/documents/:id

ParameterTypeRequiredDescription
documentIdstringYesThe document identifier

Returns: Document object Throws: DocumentNotFoundError if the document does not exist.

try {
const doc = await sdk.documents.get('doc_abc123');
console.log(doc.name); // "contract.pdf"
console.log(doc.isSigned); // true
console.log(doc.extension); // "pdf"
console.log(doc.size); // "245632"
} catch (err) {
if (err instanceof DocumentNotFoundError) {
console.log(`Document ${err.documentId} not found`);
}
}

Download a Document

Downloads the binary file content of a document.

Endpoint: GET /api/sdk/v1/documents/:id/download

ParameterTypeRequiredDescription
documentIdstringYesThe document identifier

Response (DownloadResponse)

FieldTypeDescription
dataArrayBufferThe raw file data
contentTypestringMIME type (e.g., 'application/pdf')
filenamestringOriginal filename from server
sizenumberSize in bytes
import { writeFileSync } from 'fs';
const { data, filename, contentType, size } = await sdk.documents.download('doc_abc123');
// Save to disk
writeFileSync(`./${filename}`, Buffer.from(data));
console.log(`Downloaded ${filename} (${size} bytes, ${contentType})`);

Upload a Document

Uploads a new document to Sonar. The SDK handles multipart/form-data encoding automatically.

Endpoint: POST /api/sdk/v1/documents/upload

Parameters (UploadDocumentParams)

ParameterTypeRequiredDefaultDescription
fileBuffer | Blob | NodeJS.ReadableStreamYesThe file data to upload
filenamestringNoOriginal filename
contentTypestringNoapplication/octet-streamMIME type of the file
namestringNoDisplay name for the document
uploadFromDocumentUploadSourceNo'user-documents'Source/context of the upload
identitystringNoIdentity string for the uploader
classificationDocumentClassificationNo'uploaded'Document classification category

Upload Source Values (DocumentUploadSource)

ValueDescription
'session-chat'Uploaded during a chat session
'session-call'Uploaded during a call session
'user-documents'Uploaded from user document management
'session-recording'From a session recording
'queue-documents'From a queue/processing pipeline
'application-settings-appearance'Application settings upload

File Input Types

The SDK supports three input types for the file parameter:

  1. Buffer (Node.js) — Converted to Blob with the provided contentType
  2. Blob (Browser/Node.js 18+) — Used directly
  3. ReadableStream (Node.js) — Chunks are collected, concatenated, and wrapped as a Blob

Returns: Document object (the newly created document)

import { readFileSync, createReadStream } from 'fs';
// Upload from Buffer
const buffer = readFileSync('./contract.pdf');
const doc = await sdk.documents.upload({
file: buffer,
filename: 'contract.pdf',
contentType: 'application/pdf',
name: 'Q1 Contract',
uploadFrom: 'user-documents',
classification: 'uploaded',
});
console.log(`Uploaded: ${doc.id}${doc.name}`);
// Upload from ReadableStream
const stream = createReadStream('./report.xlsx');
const doc2 = await sdk.documents.upload({
file: stream,
filename: 'report.xlsx',
contentType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
classification: 'generated',
});
// Upload from Blob (browser environment)
const blob = new Blob([arrayBuffer], { type: 'application/pdf' });
const doc3 = await sdk.documents.upload({
file: blob,
filename: 'scan.pdf',
});

Delete a Document

Permanently deletes a document by its ID. This action cannot be undone.

Endpoint: DELETE /api/sdk/v1/documents/:id

ParameterTypeRequiredDescription
documentIdstringYesThe document identifier

Returns: DeleteDocumentResponse with { documentId: string } Throws: ValidationError if documentId is empty. DocumentNotFoundError if the document does not exist. Required Scope: documents:{classification}:delete

// Delete a single document
const { documentId } = await sdk.documents.delete('doc_abc123');
console.log(`Deleted: ${documentId}`);
// With error handling
try {
await sdk.documents.delete('doc_abc123');
} catch (err) {
if (err instanceof DocumentNotFoundError) {
console.log(`Document ${err.documentId} not found`);
}
}

Batch Delete Documents

Deletes multiple documents in a single request.

Endpoint: POST /api/sdk/v1/documents/delete

Parameters (BatchDeleteParams)

ParameterTypeRequiredDescription
documentIdsstring[]YesArray of document IDs to delete (min: 1, max: 500)

Client-Side Validation:

Response (BatchDeleteResponse)

FieldTypeDescription
deletednumberNumber of documents successfully deleted
failednumberNumber of documents that failed to delete
totalnumberTotal number of documents in the request
const result = await sdk.documents.batchDelete({
documentIds: ['doc_001', 'doc_002', 'doc_003'],
});
console.log(`Deleted ${result.deleted} of ${result.total}`);
if (result.failed > 0) {
console.warn(`${result.failed} documents failed to delete`);
}

Get Presigned Download URL

Generates a temporary presigned URL for downloading a document.

Endpoint: GET /api/sdk/v1/documents/:id/download-url

ParameterTypeRequiredDescription
documentIdstringYesThe document identifier

Query Parameters (DownloadUrlParams)

ParameterTypeRequiredDefaultDescription
expiresInnumberNo300URL expiry in seconds (min: 60, max: 3600)

Response (DownloadUrlResponse)

FieldTypeDescription
documentIdstringThe document identifier
namestringDocument name
urlstringPresigned download URL
expiresInnumberURL expiry time in seconds
// Get a download URL with default expiry (300s)
const { url, expiresIn } = await sdk.documents.getDownloadUrl('doc_abc123');
console.log(`Download at: ${url} (expires in ${expiresIn}s)`);
// Get a URL with custom expiry (10 minutes)
const { url: longUrl } = await sdk.documents.getDownloadUrl('doc_abc123', {
expiresIn: 600,
});
// Redirect a client to the download URL (Express)
app.get('/download/:id', async (req, res) => {
const { url } = await sdk.documents.getDownloadUrl(req.params.id, {
expiresIn: 120,
});
res.redirect(url);
});

Export Documents as ZIP

Exports multiple documents bundled into a single ZIP archive.

Endpoint: POST /api/sdk/v1/documents/export

Parameters (ExportDocumentsParams)

ParameterTypeRequiredDescription
documentIdsstring[]YesArray of document IDs to export (min: 1, max: 500)

Client-Side Validation:

Returns: DownloadResponse with data (ArrayBuffer), contentType ('application/zip'), filename, and size.

import { writeFileSync } from 'fs';
const { data, filename, size } = await sdk.documents.export({
documentIds: ['doc_001', 'doc_002', 'doc_003'],
});
writeFileSync(`./${filename}`, Buffer.from(data));
console.log(`Exported ${filename} (${size} bytes)`);