TypeScript
We have created a TypeScript SDK to ease the integration of CarbonAPI into your Node.js application.
Other SDKs will be created soon. If you are using another programming language, you can use our API verbatim. Check out the API reference for more information and code examples.
PrerequisitesCopied!
You need an API key to access CarbonAPI. Head to the Developer Portal to aquire one.
InstallationCopied!
npm install @carbonapi/typescript-sdk
# or
yarn add @carbonapi/typescript-sdk
# or
pnpm add @carbonapi/typescript-sdk
Basic UsageCopied!
import { CarbonAPIClient } from "@carbonapi/typescript-sdk";
async function main() {
// Initialize the client with your API key
const client = new CarbonAPIClient({
apiKey: "your-api-key-here",
});
try {
// Example: Upload a batch of documents
const batchResponse = await client.uploadBatch({
type: "url",
documents: [
{
fileUrl: "https://example.com/document.pdf",
categoryHint: "TRAVEL_AIR_TICKET",
meta: {
source: "example",
},
},
],
});
console.log("Batch ID:", batchResponse.batchId);
// Example: Get batch status and documents
const batchId = batchResponse.batchId;
if (batchId) {
const batchStatus = await client.getBatch(batchId);
console.log("Batch Status:", batchStatus.status);
console.log("Documents:", batchStatus.documents);
}
} catch (error) {
console.error("Error:", error);
}
}
main().catch(console.error);
WebhooksCopied!
Also see our Webhooks documentation.
import { CarbonAPIClient } from "../src";
import express from "express";
const app = express();
app.use(express.raw({ type: "application/json" }));
// Initialize the client with your API key and webhook secret
const client = new CarbonAPIClient({
apiKey: "your-api-key-here",
webhookSecret: "your-webhook-secret-here",
});
// Example webhook handler using Express
app.post("/webhook", async (req, res) => {
try {
// Verify and parse the webhook payload
const event = await client.verifyWebhookRequest(req);
// Handle different webhook event types
switch (event.type) {
case "batch.completed":
console.log("Batch completed:", event.data);
// Handle batch completion
break;
case "batch.failed":
console.log("Batch failed:", event.data);
// Handle batch failure
break;
case "document.completed":
console.log("Document processed:", event.data);
// Handle document processing completion
break;
case "document.failed":
console.log("Document processing failed:", event.data);
// Handle document processing failure
break;
default:
console.log("Unknown event type:", event.type);
}
res.status(200).json({ received: true });
} catch (error) {
console.error("Webhook verification failed:", error);
res.status(400).json({ error: "Webhook verification failed" });
}
});
// Start the server
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`Webhook server listening on port ${port}`);
});