Qaynaq LABS · TOOLS

CURL → CODE · POST · BASIC

cURL → 10 languages

POST api.twilio.com · body: form · secrets replaced with env vars.

Source cURL
curl -X POST https://api.twilio.com/2010-04-01/Accounts/AC1234567890/Calls.json \
  -u "AC1234567890:your_auth_token" \
  -d "To=+1234567890" \
  -d "From=+1234567890" \
  -d "Url=https://handler.twilio.com/twiml/EHf3b1234567890"

Python · requests

import os
import requests

account_sid = os.environ["TWILIO_ACCOUNT_SID"]
auth_token = os.environ["TWILIO_AUTH_TOKEN"]

response = requests.post(
    f"https://api.twilio.com/2010-04-01/Accounts/{account_sid}/Calls.json",
    auth=(account_sid, auth_token),
    data={
        "To": "+1234567890",
        "From": "+1234567890",
        "Url": "https://handler.twilio.com/twiml/EHf3b1234567890"
    }
)

response.raise_for_status()
print(response.json())

Python · httpx

import os
import httpx

account_sid = os.environ["TWILIO_ACCOUNT_SID"]
auth_token = os.environ["TWILIO_AUTH_TOKEN"]

async def make_call():
    async with httpx.AsyncClient() as client:
        response = await client.post(
            f"https://api.twilio.com/2010-04-01/Accounts/{account_sid}/Calls.json",
            auth=(account_sid, auth_token),
            data={
                "To": "+1234567890",
                "From": "+1234567890",
                "Url": "https://handler.twilio.com/twiml/EHf3b1234567890"
            }
        )
        response.raise_for_status()
        return response.json()

# For synchronous usage:
# with httpx.Client() as client:
#     response = client.post(...)
#     response.raise_for_status()
#     print(response.json())

Node.js · fetch

import 'dotenv/config';
import fetch from 'node-fetch';

const accountSid = process.env.TWILIO_ACCOUNT_SID;
const authToken = process.env.TWILIO_AUTH_TOKEN;

const response = await fetch(
  `https://api.twilio.com/2010-04-01/Accounts/${accountSid}/Calls.json`,
  {
    method: 'POST',
    headers: {
      'Authorization': 'Basic ' + Buffer.from(`${accountSid}:${authToken}`).toString('base64')
    },
    body: new URLSearchParams({
      To: '+1234567890',
      From: '+1234567890',
      Url: 'https://handler.twilio.com/twiml/EHf3b1234567890'
    })
  }
);

if (!response.ok) {
  throw new Error(`HTTP error! status: ${response.status}`);
}

const data = await response.json();
console.log(data);

Node.js · axios

import 'dotenv/config';
import axios from 'axios';

const accountSid = process.env.TWILIO_ACCOUNT_SID;
const authToken = process.env.TWILIO_AUTH_TOKEN;

try {
  const response = await axios.post(
    `https://api.twilio.com/2010-04-01/Accounts/${accountSid}/Calls.json`,
    new URLSearchParams({
      To: '+1234567890',
      From: '+1234567890',
      Url: 'https://handler.twilio.com/twiml/EHf3b1234567890'
    }),
    {
      auth: {
        username: accountSid,
        password: authToken
      }
    }
  );
  console.log(response.data);
} catch (error) {
  if (error.response) {
    console.error('Error:', error.response.status, error.response.data);
  } else {
    console.error('Error:', error.message);
  }
}

Go · net/http

package main

import (
	"fmt"
	"log"
	"net/http"
	"net/url"
	"os"
)

func main() {
	accountSid := os.Getenv("TWILIO_ACCOUNT_SID")
	authToken := os.Getenv("TWILIO_AUTH_TOKEN")

	formData := url.Values{}
	formData.Add("To", "+1234567890")
	formData.Add("From", "+1234567890")
	formData.Add("Url", "https://handler.twilio.com/twiml/EHf3b1234567890")

	req, err := http.NewRequest(
		"POST",
		fmt.Sprintf("https://api.twilio.com/2010-04-01/Accounts/%s/Calls.json", accountSid),
		strings.NewReader(formData.Encode()),
	)
	if err != nil {
		log.Fatal(err)
	}

	req.SetBasicAuth(accountSid, authToken)
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		log.Fatalf("unexpected status code: %d", resp.StatusCode)
	}

	// Process response body as needed
}

PHP · cURL

<?php

$accountSid = getenv('TWILIO_ACCOUNT_SID');
$authToken = getenv('TWILIO_AUTH_TOKEN');

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://api.twilio.com/2010-04-01/Accounts/{$accountSid}/Calls.json");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
    'To' => '+1234567890',
    'From' => '+1234567890',
    'Url' => 'https://handler.twilio.com/twiml/EHf3b1234567890'
]));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, "{$accountSid}:{$authToken}");

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($httpCode !== 200) {
    throw new Exception("HTTP error: {$httpCode}");
}

$data = json_decode($response, true);
print_r($data);

Ruby · net/http

require 'net/http'
require 'uri'
require 'json'

account_sid = ENV['TWILIO_ACCOUNT_SID']
auth_token = ENV['TWILIO_AUTH_TOKEN']

uri = URI.parse("https://api.twilio.com/2010-04-01/Accounts/#{account_sid}/Calls.json")

http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true

request = Net::HTTP::Post.new(uri.request_uri)
request.basic_auth(account_sid, auth_token)
request.set_form_data({
  'To' => '+1234567890',
  'From' => '+1234567890',
  'Url' => 'https://handler.twilio.com/twiml/EHf3b1234567890'
})

response = http.request(request)

unless response.is_a?(Net::HTTPSuccess)
  raise "HTTP error: #{response.code}"
end

puts JSON.parse(response.body)

Swift · URLSession

import Foundation

let accountSid = ProcessInfo.processInfo.environment["TWILIO_ACCOUNT_SID"] ?? ""
let authToken = ProcessInfo.processInfo.environment["TWILIO_AUTH_TOKEN"] ?? ""

let url = URL(string: "https://api.twilio.com/2010-04-01/Accounts/" + accountSid + "/Calls.json")!
var request = URLRequest(url: url)
request.httpMethod = "POST"

let bodyString = "To=+1234567890&From=+1234567890&Url=https://handler.twilio.com/twiml/EHf3b1234567890"
request.httpBody = bodyString.data(using: .utf8)

let authString = "\(accountSid):\(authToken)"
let authData = authString.data(using: .utf8)?.base64EncodedString()
request.setValue("Basic \(authData ?? "")", forHTTPHeaderField: "Authorization")

let task = URLSession.shared.dataTask(with: request) { data, response, error in
    if let error = error {
        print("Error: \(error)")
        return
    }
    guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else {
        print("HTTP error")
        return
    }
    if let data = data, let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] {
        print(json)
    }
}
task.resume()

// For synchronous execution in a playground or test:
// let (data, response) = try await URLSession.shared.data(for: request)
// guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else { throw URLError(.badServerResponse) }
// let json = try JSONSerialization.jsonObject(with: data) as? [String: Any]
// print(json)

Rust · reqwest

use std::collections::HashMap;
use std::env;
use reqwest::blocking::Client;
use reqwest::blocking::Response;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let account_sid = env::var("TWILIO_ACCOUNT_SID")?;
    let auth_token = env::var("TWILIO_AUTH_TOKEN")?;

    let client = Client::new();
    let mut params = HashMap::new();
    params.insert("To", "+1234567890");
    params.insert("From", "+1234567890");
    params.insert("Url", "https://handler.twilio.com/twiml/EHf3b1234567890");

    let response: Response = client
        .post(&format!("https://api.twilio.com/2010-04-01/Accounts/{}/Calls.json", account_sid))
        .basic_auth(&account_sid, Some(&auth_token))
        .form(&params)
        .send()?;

    if !response.status().is_success() {
        return Err(format!("HTTP error: {}", response.status()).into());
    }

    let body = response.json::<serde_json::Value>()?;
    println!("{:?}", body);
    Ok(())
}

C# · HttpClient

using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        var accountSid = Environment.GetEnvironmentVariable("TWILIO_ACCOUNT_SID");
        var authToken = Environment.GetEnvironmentVariable("TWILIO_AUTH_TOKEN");

        using var client = new HttpClient();
        var request = new HttpRequestMessage(HttpMethod.Post, 
            $"https://api.twilio.com/2010-04-01/Accounts/{accountSid}/Calls.json");

        request.Headers.Authorization = new AuthenticationHeaderValue(
            "Basic", Convert.ToBase64String(
                System.Text.Encoding.ASCII.GetBytes($"{accountSid}:{authToken}")));

        var formData = new Dictionary<string, string>
        {
            {"To", "+1234567890"},
            {"From", "+1234567890"},
            {"Url", "https://handler.twilio.com/twiml/EHf3b1234567890"}
        };

        request.Content = new FormUrlEncodedContent(formData);

        var response = await client.SendAsync(request);
        response.EnsureSuccessStatusCode();

        var responseBody = await response.Content.ReadAsStringAsync();
        Console.WriteLine(responseBody);
    }
}

Translation notes

  • All implementations use environment variables for credentials (TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN)
  • Basic auth is used in all cases, matching the cURL -u flag
  • Form data is used for the body in all implementations
  • Error handling checks HTTP status and raises/throws on non-2xx responses
  • Python httpx example includes both async and sync usage patterns
  • Go example uses net/http with URL encoding for form data
  • Swift example includes both async (modern) and synchronous (for playgrounds/tests) patterns
  • Rust example uses reqwest blocking client for simplicity

Common pitfalls when porting

  • Forgetting to set environment variables before running the code
  • Using hardcoded credentials instead of environment variables
  • Not URL-encoding form data properly in languages that don't handle it automatically
  • Ignoring SSL certificate verification (not shown here but important in production)
  • Assuming synchronous code will work in async contexts without proper handling
  • Not setting the Content-Type header for form data in some languages

About cURL → code translation

cURL is the lingua franca of API documentation: every vendor docs page ships a cURL snippet you can paste into a terminal and immediately see the API working. Translating that into your actual application code shouldn't be a 20-minute Stack-Overflow safari, but without a good translator it usually is.

Qaynaq Labs' cURL → code tool reads the full command — method, URL, headers, query params, body type, and auth — and emits idiomatic client code in 10 languages. Authentication goes through environment variables by default, request bodies become language-native data structures (not raw JSON strings), and minimal error handling is included.

Frequently asked

Why use environment variables instead of hardcoding credentials?

Environment variables separate secrets from code, reducing the risk of accidental exposure in version control or logs. They also allow different configurations across environments without code changes.

How do I handle pagination or large responses?

Most HTTP libraries provide streaming or pagination helpers. For example, in Python requests you can use response.iter_content() for large responses, and in Go you can read the response body in chunks.

Can I use bearer token auth instead of basic auth?

Twilio's API requires basic auth with your Account SID as the username and Auth Token as the password. Bearer token auth is not supported for this endpoint.