Resources
Code Examples
Ready-to-use code examples for common Flametalk API operations. Copy, paste, and customize for your use case.
Authentication
Making Authenticated Requests
Include your API key in the Authorization header:
curl
curl -X GET "https://dev.flametalk.ai/v1/agents" \ -H "Authorization: Bearer YOUR_API_KEY"Verify API Key
Test that your API key is working:
bash
curl https://dev.flametalk.ai/v1/agents \ -H "Authorization: Bearer sk_xxx_xxx" \ -w "\nHTTP Status: %{http_code}\n" # Success: HTTP Status: 200# Invalid key: HTTP Status: 401Agents
List All Agents
curl
curl -X GET "https://dev.flametalk.ai/v1/agents?status=deployed" \ -H "Authorization: Bearer YOUR_API_KEY"Get Agent Details
curl
curl -X GET "https://dev.flametalk.ai/v1/agents/agent_abc123" \ -H "Authorization: Bearer YOUR_API_KEY"Create an Agent
curl
curl -X POST "https://dev.flametalk.ai/v1/agents" \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "name": "Support Agent", "instructions": "You are a helpful customer support agent for TechCo. Answer questions about our products and services. Be friendly and professional.", "language": "en", "voice_id": "rachel"}'Update Agent Instructions
curl
curl -X PATCH "https://dev.flametalk.ai/v1/agents/agent_abc123" \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "instructions": "Updated instructions here..."}'Contacts
Create a Contact
curl
curl -X POST "https://dev.flametalk.ai/v1/contacts" \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "phone": "+15551234567", "name": "John Smith", "email": "john@example.com", "company": "Acme Corp", "tags": [ "lead", "enterprise" ], "metadata": { "source": "website", "plan_interest": "pro" }}'Bulk Create Contacts (Node.js)
bulk-import.js
const API_KEY = "sk_xxx_xxx";const BASE_URL = "https://dev.flametalk.ai/v1"; const contacts = [ { phone: "+15551234567", name: "John Smith", tags: ["lead"] }, { phone: "+15559876543", name: "Jane Doe", tags: ["lead"] }, { phone: "+15555555555", name: "Bob Wilson", tags: ["lead"] },]; async function importContacts() { const results = await Promise.all( contacts.map(async (contact) => { const response = await fetch(`${BASE_URL}/contacts`, { method: "POST", headers: { "Authorization": `Bearer ${API_KEY}`, "Content-Type": "application/json", }, body: JSON.stringify(contact), }); return response.json(); }) ); console.log(`Imported ${results.length} contacts`); return results;} importContacts();Search Contacts by Tag
curl
curl -X GET "https://dev.flametalk.ai/v1/contacts?tags=enterprise&limit=50" \ -H "Authorization: Bearer YOUR_API_KEY"Update Contact Metadata
curl
curl -X PATCH "https://dev.flametalk.ai/v1/contacts/contact_xyz789" \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "metadata": { "last_call_outcome": "interested", "follow_up_date": "2024-02-01" }}'Campaigns
Create a Campaign
curl
curl -X POST "https://dev.flametalk.ai/v1/campaigns" \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "name": "Q1 Lead Follow-up", "description": "Follow up with Q1 leads for demo scheduling", "outbound_channel_id": "ch_abc123", "business_hours": { "timezone": "America/New_York", "days": { "monday": { "start": "09:00", "end": "17:00" }, "tuesday": { "start": "09:00", "end": "17:00" }, "wednesday": { "start": "09:00", "end": "17:00" }, "thursday": { "start": "09:00", "end": "17:00" }, "friday": { "start": "09:00", "end": "17:00" } } }, "rate_limits": { "max_concurrent_calls": 5, "calls_per_minute": 10 }}'Start a Campaign
curl
curl -X POST "https://dev.flametalk.ai/v1/campaigns/camp_xyz123/start" \ -H "Authorization: Bearer YOUR_API_KEY"Pause a Campaign
curl
curl -X POST "https://dev.flametalk.ai/v1/campaigns/camp_xyz123/pause" \ -H "Authorization: Bearer YOUR_API_KEY"Get Campaign Progress
curl
curl -X GET "https://dev.flametalk.ai/v1/campaigns/camp_xyz123" \ -H "Authorization: Bearer YOUR_API_KEY"Calls
List Recent Calls
curl
curl -X GET "https://dev.flametalk.ai/v1/calls?limit=20&status=completed" \ -H "Authorization: Bearer YOUR_API_KEY"Get Call with Transcript
curl
curl -X GET "https://dev.flametalk.ai/v1/calls/call_abc123" \ -H "Authorization: Bearer YOUR_API_KEY"Export Calls to CSV (Node.js)
export-calls.js
const fs = require("fs"); const API_KEY = "sk_xxx_xxx";const BASE_URL = "https://dev.flametalk.ai/v1"; async function exportCalls(campaignId) { const response = await fetch( `${BASE_URL}/calls?campaign_id=${campaignId}&limit=100`, { headers: { "Authorization": `Bearer ${API_KEY}` }, } ); const { data } = await response.json(); // Convert to CSV const headers = "id,contact_name,phone,status,duration,outcome,created_at\n"; const rows = data.map(call => `${call.id},${call.contact_name},${call.contact_phone},${call.status},${call.duration},${call.outcome},${call.created_at}` ).join("\n"); fs.writeFileSync("calls-export.csv", headers + rows); console.log(`Exported ${data.length} calls to calls-export.csv`);} exportCalls("camp_xyz123");Webhook Handlers
Express.js Webhook Handler
webhook-handler.js
const express = require("express");const crypto = require("crypto"); const app = express();const WEBHOOK_SECRET = process.env.FLAMETALK_WEBHOOK_SECRET; // Verify webhook signaturefunction verifySignature(payload, signature) { const expected = crypto .createHmac("sha256", WEBHOOK_SECRET) .update(payload) .digest("hex"); return crypto.timingSafeEqual( Buffer.from(signature), Buffer.from(expected) );} app.post("/webhooks/flametalk", express.raw({ type: "application/json" }), (req, res) => { const signature = req.headers["x-flametalk-signature"]; if (!verifySignature(req.body, signature)) { return res.status(401).send("Invalid signature"); } const event = JSON.parse(req.body); switch (event.event) { case "call.completed": console.log("Call completed:", event.data.call_id); // Handle completed call break; case "call.goal_reached": console.log("Goal reached:", event.data.goal); // Handle goal reached - maybe notify sales team break; case "campaign.completed": console.log("Campaign finished:", event.data.campaign_id); // Handle campaign completion break; } res.status(200).send("OK");}); app.listen(3000);Python (Flask) Webhook Handler
webhook_handler.py
from flask import Flask, request, jsonifyimport hmacimport hashlibimport os app = Flask(__name__)WEBHOOK_SECRET = os.environ.get("FLAMETALK_WEBHOOK_SECRET") def verify_signature(payload, signature): expected = hmac.new( WEBHOOK_SECRET.encode(), payload, hashlib.sha256 ).hexdigest() return hmac.compare_digest(signature, expected) @app.route("/webhooks/flametalk", methods=["POST"])def handle_webhook(): signature = request.headers.get("X-Flametalk-Signature") if not verify_signature(request.data, signature): return jsonify({"error": "Invalid signature"}), 401 event = request.json event_type = event.get("event") data = event.get("data") if event_type == "call.completed": print(f"Call completed: {data['call_id']}") # Handle completed call elif event_type == "call.goal_reached": print(f"Goal reached: {data['goal']}") # Handle goal reached elif event_type == "campaign.completed": print(f"Campaign finished: {data['campaign_id']}") # Handle campaign completion return jsonify({"status": "ok"}), 200 if __name__ == "__main__": app.run(port=3000)Complete Integration Example
Here's a complete example that creates contacts, runs a campaign, and handles results:
full-integration.js
const API_KEY = process.env.FLAMETALK_API_KEY;const BASE_URL = "https://dev.flametalk.ai/v1"; async function api(method, endpoint, body = null) { const response = await fetch(`${BASE_URL}${endpoint}`, { method, headers: { "Authorization": `Bearer ${API_KEY}`, "Content-Type": "application/json", }, body: body ? JSON.stringify(body) : null, }); if (!response.ok) { const error = await response.json(); throw new Error(`API error: ${error.error?.message || response.statusText}`); } return response.json();} async function runLeadCampaign(leads, channelId) { console.log(`Starting campaign for ${leads.length} leads...`); // 1. Create contacts const contacts = await Promise.all( leads.map(lead => api("POST", "/contacts", { phone: lead.phone, name: lead.name, email: lead.email, tags: ["campaign-q1"], metadata: { source: lead.source }, })) ); console.log(`Created ${contacts.length} contacts`); // 2. Create campaign const { data: campaign } = await api("POST", "/campaigns", { name: `Lead Campaign - ${new Date().toISOString().split("T")[0]}`, outbound_channel_id: channelId, business_hours: { timezone: "America/New_York", days: { monday: { start: "09:00", end: "17:00" }, tuesday: { start: "09:00", end: "17:00" }, wednesday: { start: "09:00", end: "17:00" }, thursday: { start: "09:00", end: "17:00" }, friday: { start: "09:00", end: "17:00" }, }, }, rate_limits: { max_concurrent_calls: 3, calls_per_minute: 5, }, }); console.log(`Created campaign: ${campaign.id}`); // 3. Start campaign await api("POST", `/campaigns/${campaign.id}/start`); console.log("Campaign started!"); // 4. Poll for completion let status = "active"; while (status === "active") { await new Promise(resolve => setTimeout(resolve, 60000)); // Wait 1 minute const { data: updated } = await api("GET", `/campaigns/${campaign.id}`); status = updated.status; console.log(`Progress: ${updated.completed_enrollments}/${updated.total_enrollments} completed`); } // 5. Get final results const { data: final } = await api("GET", `/campaigns/${campaign.id}`); console.log("Campaign complete!"); console.log(`Results: ${final.goal_reached_count} goals reached out of ${final.total_enrollments} contacts`); return final;} // Usageconst leads = [ { phone: "+15551234567", name: "John Smith", email: "john@example.com", source: "website" }, { phone: "+15559876543", name: "Jane Doe", email: "jane@example.com", source: "webinar" },]; runLeadCampaign(leads, "ch_abc123").catch(console.error);Need More Examples?
Check out our GitHub examples repository for more complete integrations in various languages.