Node.js SDK Examples
Basic Workflow
Extract data from invoices:
import { Structurify } from '@structurify/sdk';
import * as fs from 'fs';
const client = new Structurify({
apiKey: process.env.STRUCTURIFY_API_KEY!,
});
async function extractInvoice() {
// Create project with invoice template
const project = await client.projects.create({
name: 'Invoice Processing',
templateId: 'tpl_invoice',
});
// Upload document
const doc = await client.documents.upload({
projectId: project.id,
file: new Blob([fs.readFileSync('invoice.pdf')]),
name: 'invoice.pdf',
});
console.log(`Uploaded: ${doc.name}`);
// Run extraction
const job = await client.extraction.run({ projectId: project.id });
const completed = await client.extraction.waitForCompletion(job.id);
console.log(`Completed: ${completed.completedTasks} tasks`);
// Export to CSV
const exportResult = await client.exports.create({
projectId: project.id,
format: 'csv',
});
const csvData = await client.exports.download(exportResult.export.id);
// Save to file
fs.writeFileSync('results.csv', csvData);
}
extractInvoice();
Batch Processing
Process multiple documents:
import { Structurify } from '@structurify/sdk';
import * as fs from 'fs';
import * as path from 'path';
const client = new Structurify({
apiKey: process.env.STRUCTURIFY_API_KEY!,
});
async function batchProcess(folder: string) {
// Create project
const project = await client.projects.create({
name: 'Batch Processing',
templateId: 'tpl_invoice',
});
// Upload all PDFs
const files = fs.readdirSync(folder).filter(f => f.endsWith('.pdf'));
for (const file of files) {
const filePath = path.join(folder, file);
const doc = await client.documents.upload({
projectId: project.id,
file: new Blob([fs.readFileSync(filePath)]),
name: file,
});
console.log(`Uploaded: ${doc.name}`);
}
// Run extraction on all
const job = await client.extraction.run({ projectId: project.id });
const completed = await client.extraction.waitForCompletion(job.id);
console.log(`Processed ${completed.completedTasks} documents`);
console.log(`Failed: ${completed.failedTasks}`);
// Export all results
const exportResult = await client.exports.create({
projectId: project.id,
format: 'csv',
});
return client.exports.download(exportResult.export.id);
}
batchProcess('./invoices');
Error Handling with Retry
import {
Structurify,
RateLimitError,
InsufficientCreditsError,
} from '@structurify/sdk';
const client = new Structurify({
apiKey: process.env.STRUCTURIFY_API_KEY!,
});
async function processWithRetry(projectId: string, maxRetries = 3) {
for (let attempt = 0; attempt < maxRetries; attempt++) {
try {
const job = await client.extraction.run({ projectId });
return client.extraction.waitForCompletion(job.id);
} catch (error) {
if (error instanceof RateLimitError && attempt < maxRetries - 1) {
console.log(`Rate limited. Waiting ${error.retryAfter}s...`);
await new Promise(r => setTimeout(r, error.retryAfter * 1000));
} else if (error instanceof InsufficientCreditsError) {
console.log('Not enough credits. Please top up.');
throw error;
} else {
throw error;
}
}
}
}
Webhook Handler (Express)
import express from 'express';
import { verifyWebhookSignature } from '@structurify/sdk';
const app = express();
const WEBHOOK_SECRET = process.env.WEBHOOK_SECRET!;
// Important: use raw body for signature verification
app.use('/webhook', express.raw({ type: 'application/json' }));
app.post('/webhook', (req, res) => {
const signature = req.headers['x-structurify-signature'] as string;
const isValid = verifyWebhookSignature({
payload: req.body.toString(),
signature,
secret: WEBHOOK_SECRET,
});
if (!isValid) {
return res.status(401).json({ error: 'Invalid signature' });
}
const event = JSON.parse(req.body.toString());
switch (event.event) {
case 'extraction.completed':
console.log(`Extraction completed: ${event.data.job_id}`);
// Process results...
break;
case 'extraction.failed':
console.log(`Extraction failed: ${event.data.job_id}`);
break;
}
res.json({ status: 'ok' });
});
app.listen(3000, () => {
console.log('Webhook server running on port 3000');
});
TypeScript Examples
We provide 169 ready-to-use TypeScript examples for different document types.
Try them:
# Clone the repo
git clone https://github.com/DscvryAI/structurify-sdk.git
cd structurify-sdk
# Install dependencies
cd examples/nodejs
npm install
# Run an example
export STRUCTURIFY_API_KEY=sk_live_xxx
npx ts-node invoice-processing.ts ./invoice.pdf
Interactive Playground
Try the SDK in your browser: