View Categories

Code Examples

3 min read

Code Examples #

Complete working examples in popular programming languages.

JavaScript / Node.js #

Complete Integration Example #

const axios = require('axios');

const API_KEY = process.env.VOXPRIA_API_KEY;
const BASE_URL = 'https://app.voxpria.com/api/v1';

// Trigger a call
async function triggerCall(agentId, phoneNumber, variables = {}) {
  try {
    const response = await axios.post(
      `${BASE_URL}/calls`,
      {
        agentId: agentId,
        toNumber: phoneNumber,
        variables: variables
      },
      {
        headers: {
          'Authorization': `Bearer ${API_KEY}`,
          'Content-Type': 'application/json'
        }
      }
    );
    return response.data;
  } catch (error) {
    console.error('Error:', error.response?.data || error.message);
    throw error;
  }
}

// Get call details
async function getCallDetails(callId) {
  const response = await axios.get(
    `${BASE_URL}/calls/${callId}`,
    {
      headers: {
        'Authorization': `Bearer ${API_KEY}`
      }
    }
  );
  return response.data;
}

// Usage
async function main() {
  // Trigger call
  const result = await triggerCall(
    'agent_abc123',
    '+14155551234',
    { customerName: 'John Doe' }
  );
  console.log('Call ID:', result.data.callId);
  
  // Wait and check status
  setTimeout(async () => {
    const details = await getCallDetails(result.data.callId);
    console.log('Status:', details.data.status);
  }, 5000);
}

main();

Python #

Complete Integration Example #

import requests
import os
import time

API_KEY = os.getenv('VOXPRIA_API_KEY')
BASE_URL = 'https://app.voxpria.com/api/v1'

def trigger_call(agent_id, phone_number, variables=None):
    """Trigger a new voice call"""
    try:
        response = requests.post(
            f'{BASE_URL}/calls',
            json={
                'agentId': agent_id,
                'toNumber': phone_number,
                'variables': variables or {}
            },
            headers={
                'Authorization': f'Bearer {API_KEY}',
                'Content-Type': 'application/json'
            }
        )
        response.raise_for_status()
        return response.json()
    except requests.exceptions.RequestException as e:
        print(f'Error: {e}')
        raise

def get_call_details(call_id):
    """Get details of a specific call"""
    response = requests.get(
        f'{BASE_URL}/calls/{call_id}',
        headers={'Authorization': f'Bearer {API_KEY}'}
    )
    response.raise_for_status()
    return response.json()

# Usage
if __name__ == '__main__':
    # Trigger call
    result = trigger_call(
        'agent_abc123',
        '+14155551234',
        {'customerName': 'John Doe'}
    )
    print(f"Call ID: {result['data']['callId']}")
    
    # Wait and check status
    time.sleep(5)
    details = get_call_details(result['data']['callId'])
    print(f"Status: {details['data']['status']}")

PHP #

Complete Integration Example #

<?php

$apiKey = getenv('VOXPRIA_API_KEY');
$baseUrl = 'https://app.voxpria.com/api/v1';

function triggerCall($agentId, $phoneNumber, $variables = []) {
    global $apiKey, $baseUrl;
    
    $ch = curl_init("$baseUrl/calls");
    
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
        'agentId' => $agentId,
        'toNumber' => $phoneNumber,
        'variables' => $variables
    ]));
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        "Authorization: Bearer $apiKey",
        'Content-Type: application/json'
    ]);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    if ($httpCode !== 200) {
        throw new Exception("API Error: $response");
    }
    
    return json_decode($response, true);
}

function getCallDetails($callId) {
    global $apiKey, $baseUrl;
    
    $ch = curl_init("$baseUrl/calls/$callId");
    
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        "Authorization: Bearer $apiKey"
    ]);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    
    $response = curl_exec($ch);
    curl_close($ch);
    
    return json_decode($response, true);
}

// Usage
try {
    $result = triggerCall(
        'agent_abc123',
        '+14155551234',
        ['customerName' => 'John Doe']
    );
    echo "Call ID: " . $result['data']['callId'] . "\n";
    
    // Wait and check
    sleep(5);
    $details = getCallDetails($result['data']['callId']);
    echo "Status: " . $details['data']['status'] . "\n";
    
} catch (Exception $e) {
    echo "Error: " . $e->getMessage() . "\n";
}

?>

C# #

Complete Integration Example #

using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

public class VoxPriaClient
{
    private readonly string _apiKey;
    private readonly string _baseUrl;
    private readonly HttpClient _httpClient;

    public VoxPriaClient(string apiKey)
    {
        _apiKey = apiKey;
        _baseUrl = "https://app.voxpria.com/api/v1";
        _httpClient = new HttpClient();
        _httpClient.DefaultRequestHeaders.Authorization = 
            new AuthenticationHeaderValue("Bearer", _apiKey);
    }

    public async Task TriggerCall(
        string agentId, 
        string phoneNumber, 
        object variables = null)
    {
        var payload = new
        {
            agentId = agentId,
            toNumber = phoneNumber,
            variables = variables ?? new { }
        };

        var content = new StringContent(
            JsonSerializer.Serialize(payload),
            Encoding.UTF8,
            "application/json"
        );

        var response = await _httpClient.PostAsync(
            $"{_baseUrl}/calls",
            content
        );

        response.EnsureSuccessStatusCode();

        var responseBody = await response.Content.ReadAsStringAsync();
        return JsonDocument.Parse(responseBody);
    }

    public async Task GetCallDetails(string callId)
    {
        var response = await _httpClient.GetAsync(
            $"{_baseUrl}/calls/{callId}"
        );

        response.EnsureSuccessStatusCode();

        var responseBody = await response.Content.ReadAsStringAsync();
        return JsonDocument.Parse(responseBody);
    }
}

// Usage
class Program
{
    static async Task Main(string[] args)
    {
        var apiKey = Environment.GetEnvironmentVariable("VOXPRIA_API_KEY");
        var client = new VoxPriaClient(apiKey);

        try
        {
            // Trigger call
            var result = await client.TriggerCall(
                "agent_abc123",
                "+14155551234",
                new { customerName = "John Doe" }
            );

            var callId = result.RootElement
                .GetProperty("data")
                .GetProperty("callId")
                .GetString();

            Console.WriteLine($"Call ID: {callId}");

            // Wait and check status
            await Task.Delay(5000);
            var details = await client.GetCallDetails(callId);

            var status = details.RootElement
                .GetProperty("data")
                .GetProperty("status")
                .GetString();

            Console.WriteLine($"Status: {status}");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error: {ex.Message}");
        }
    }
}

Error Handling Example #

Robust error handling across languages:

JavaScript #

async function makeApiCall() {
  try {
    const response = await axios.get(url, config);
    return response.data;
  } catch (error) {
    if (error.response) {
      // Server responded with error
      switch (error.response.status) {
        case 401:
          throw new Error('Invalid API key');
        case 429:
          throw new Error('Rate limited - retry later');
        case 500:
          throw new Error('Server error');
        default:
          throw new Error(error.response.data.error.message);
      }
    }
    throw error;
  }
}
✅ Best Practices:

  • Store API keys in environment variables
  • Implement exponential backoff for rate limits
  • Log errors for debugging
  • Use try-catch for error handling
  • Validate phone numbers before calling API

Leave A Comment

Go to Top