JavaScript/Node.js SDK
The official Audian SDK for JavaScript and Node.js.
Installation​
npm install @audian/sdk
Or with Yarn:
yarn add @audian/sdk
Quick Start​
const { AudianClient } = require('@audian/sdk');
const client = new AudianClient({
apiKey: 'YOUR_API_KEY'
});
// Search for phone numbers
const numbers = await client.numbers.search({
location: 'US-CA-415',
limit: 10
});
console.log(numbers);
Configuration​
Initialize Client​
const client = new AudianClient({
apiKey: 'sk_live_...',
baseURL: 'https://api.audian.com:8443/v2', // Optional
timeout: 30000, // Optional, milliseconds
maxRetries: 3, // Optional
backoffFactor: 2 // Optional
});
Environment Variables​
export AUDIAN_API_KEY='sk_live_...'
const client = new AudianClient({
apiKey: process.env.AUDIAN_API_KEY
});
Phone Numbers API​
Search Numbers​
const numbers = await client.numbers.search({
location: 'US-CA-415',
pattern: '415*',
features: ['sms', 'mms'],
limit: 20,
offset: 0
});
console.log(numbers.data.numbers);
List Your Numbers​
const response = await client.numbers.list({
limit: 20,
offset: 0,
status: 'active'
});
console.log(response.data.numbers);
Get Number Details​
const number = await client.numbers.get('num_abc123');
console.log(number.data);
Purchase a Number​
const purchased = await client.numbers.purchase({
number: '+14155551234',
friendly_name: 'Support Line'
});
console.log(purchased.data.id);
Update Number Configuration​
const updated = await client.numbers.updateConfig('num_abc123', {
friendly_name: 'Support Line',
callForwarding: {
enabled: true,
forwardTo: '+14155559999',
ringsBeforeForward: 4
},
voicemail: {
enabled: true,
transcription: true
}
});
Set Caller ID​
const callerId = await client.numbers.setCallerId('num_abc123', {
callerIdNumber: '+14155551234',
callerIdName: 'Support'
});
Configure E911​
const e911 = await client.numbers.setE911('num_abc123', {
addressLine1: '123 Main Street',
addressLine2: 'Suite 100',
city: 'San Francisco',
state: 'CA',
postalCode: '94102',
country: 'US',
customerName: 'Acme Corp'
});
SMS API​
Send SMS​
const response = await client.sms.send({
to: '+14155551234',
from: '+14155559999',
message: 'Hello, World!'
});
console.log(response.data.id);
Send Batch SMS​
const response = await client.sms.sendBatch({
messages: [
{ to: '+14155551234', message: 'Hello 1' },
{ to: '+14155551235', message: 'Hello 2' },
{ to: '+14155551236', message: 'Hello 3' }
]
});
Get SMS Details​
const sms = await client.sms.get('sms_abc123');
console.log(sms.data.status);
List SMS Messages​
const messages = await client.sms.list({
limit: 20,
offset: 0,
status: 'delivered'
});
Voice API​
Make a Call​
const call = await client.voice.makeCall({
to: '+14155551234',
from: '+14155559999',
action: 'connect',
connectTo: '+14155559999'
});
console.log(call.data.id);
Get Call Details​
const callDetails = await client.voice.getCall('call_abc123');
console.log(callDetails.data.status);
List Calls​
const calls = await client.voice.listCalls({
limit: 20,
status: 'completed'
});
Billing API​
Get Usage​
const usage = await client.billing.usage.get();
console.log(usage.data.usage.smsMessages.cost);
console.log(usage.data.usage.voiceMinutes.cost);
Get Usage Breakdown​
const breakdown = await client.billing.usage.getBreakdown({
metric: 'sms',
granularity: 'day'
});
List Invoices​
const invoices = await client.billing.invoices.list({
status: 'paid',
limit: 20
});
Get Invoice​
const invoice = await client.billing.invoices.get('inv_abc123');
console.log(invoice.data.total);
Get Invoice PDF​
const pdf = await client.billing.invoices.getPdf('inv_abc123');
// Save pdf to file
fs.writeFileSync('invoice.pdf', pdf);
Error Handling​
const { AudianError } = require('@audian/sdk');
try {
await client.numbers.purchase({ number: '+14155551234' });
} catch (error) {
if (error instanceof AudianError) {
console.log(`Error: ${error.message}`);
console.log(`Code: ${error.code}`);
console.log(`Status: ${error.status}`);
} else {
console.error('Unexpected error:', error);
}
}
Rate Limiting​
The SDK automatically handles rate limiting:
// Automatically retries with exponential backoff
const numbers = await client.numbers.search({
location: 'US-CA-415'
});
Custom Retry Configuration​
const client = new AudianClient({
apiKey: 'YOUR_API_KEY',
maxRetries: 5,
backoffFactor: 2,
initialRetryDelay: 100 // milliseconds
});
Monitor Rate Limit Headers​
const response = await client.numbers.list();
console.log(response.headers['ratelimit-limit']);
console.log(response.headers['ratelimit-remaining']);
console.log(response.headers['ratelimit-reset']);
Async/Await​
All SDK methods are async and work with Promises:
// Using async/await
async function sendSMS() {
const result = await client.sms.send({
to: '+14155551234',
message: 'Hello!'
});
return result.data;
}
// Using Promises
client.sms.send({
to: '+14155551234',
message: 'Hello!'
})
.then(result => console.log(result.data))
.catch(error => console.error(error));
Webhooks​
Verify Webhook Signature​
const { WebhookVerifier } = require('@audian/sdk');
const verifier = new WebhookVerifier({
signingSecret: 'whsec_...'
});
app.post('/webhook', (req, res) => {
try {
const event = verifier.verify(req.body, req.headers['x-audian-signature']);
console.log(`Event: ${event.type}`);
res.json({ success: true });
} catch (error) {
res.status(401).json({ error: 'Unauthorized' });
}
});
Handle Webhook Events​
app.post('/webhook', async (req, res) => {
const event = verifier.verify(req.body, req.headers['x-audian-signature']);
switch (event.type) {
case 'sms.received':
console.log(`SMS from ${event.data.from}: ${event.data.message}`);
break;
case 'call.completed':
console.log(`Call duration: ${event.data.duration}s`);
break;
case 'number.ported':
console.log(`Number ${event.data.number} ported successfully`);
break;
}
res.json({ success: true });
});
TypeScript Support​
The SDK includes full TypeScript definitions:
import { AudianClient, ISearchNumbersRequest } from '@audian/sdk';
const client = new AudianClient({
apiKey: 'YOUR_API_KEY'
});
const request: ISearchNumbersRequest = {
location: 'US-CA-415',
limit: 10
};
const numbers = await client.numbers.search(request);
Testing​
The SDK provides mocking utilities:
const { MockAudianClient } = require('@audian/sdk');
// Mock responses
const mockClient = new MockAudianClient();
mockClient.setMockResponse('numbers.search', {
success: true,
data: {
numbers: [
{
number: '+14155551234',
available: true
}
]
}
});
const numbers = await mockClient.numbers.search({
location: 'US-CA-415'
});
Examples​
Complete Example​
const { AudianClient } = require('@audian/sdk');
async function main() {
const client = new AudianClient({
apiKey: process.env.AUDIAN_API_KEY
});
// Search for available numbers
const available = await client.numbers.search({
location: 'US-CA-415',
limit: 5
});
console.log('Available numbers:', available.data.numbers);
// Purchase the first number
if (available.data.numbers.length > 0) {
const number = available.data.numbers[0].number;
const purchased = await client.numbers.purchase({
number: number,
friendly_name: 'Demo Number'
});
console.log('Purchased:', purchased.data.number);
// Send SMS from the number
const sms = await client.sms.send({
from: purchased.data.number,
to: '+14155559999',
message: 'Hello from Audian!'
});
console.log('SMS sent:', sms.data.id);
}
}
main().catch(console.error);
Troubleshooting​
API Key Not Found​
// Make sure to set the API key
const client = new AudianClient({
apiKey: process.env.AUDIAN_API_KEY
});
if (!client.apiKey) {
throw new Error('AUDIAN_API_KEY environment variable not set');
}
Timeout Issues​
const client = new AudianClient({
apiKey: 'YOUR_API_KEY',
timeout: 60000 // Increase to 60 seconds
});
Debugging​
const client = new AudianClient({
apiKey: 'YOUR_API_KEY',
debug: true // Enable debug logging
});
Support​
Version History​
See changelog