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/Call.json \
  -H "Authorization: Basic $(echo -n 'AC1234567890:auth_token' | base64)" \
  -d "To=+1234567890&From=+1987654321&Url=https://example.com/twiml"

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}/Call.json",
    auth=(account_sid, auth_token),
    data={
        "To": "+1234567890",
        "From": "+1987654321",
        "Url": "https://example.com/twiml"
    }
)

if response.status_code >= 400:
    raise Exception(f"Request failed: {response.text}")
print(response.json())

Python · httpx

import os
import httpx

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

with httpx.Client() as client:
    response = client.post(
        f"https://api.twilio.com/2010-04-01/Accounts/{account_sid}/Call.json",
        auth=(account_sid, auth_token),
        data={
            "To": "+1234567890",
            "From": "+1987654321",
            "Url": "https://example.com/twiml"
        }
    )

    if response.status_code >= 400:
        raise Exception(f"Request failed: {response.text}")
    print(response.json())

Node.js · fetch

import fetch from 'node-fetch';
import * as process from 'process';

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}/Call.json`,
  {
    method: 'POST',
    headers: {
      'Authorization': 'Basic ' + Buffer.from(`${accountSid}:${authToken}`).toString('base64')
    },
    body: new URLSearchParams({
      To: '+1234567890',
      From: '+1987654321',
      Url: 'https://example.com/twiml'
    })
  }
);

if (!response.ok) {
  throw new Error(`Request failed: ${await response.text()}`);
}
console.log(await response.json());

Node.js · axios

import axios from 'axios';
import * as process from 'process';

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}/Call.json`,
    new URLSearchParams({
      To: '+1234567890',
      From: '+1987654321',
      Url: 'https://example.com/twiml'
    }),
    {
      auth: {
        username: accountSid,
        password: authToken
      }
    }
  );

  if (response.status >= 400) {
    throw new Error(`Request failed: ${response.statusText}`);
  }
  console.log(response.data);
} catch (error) {
  console.error(error.message);
}

Go · net/http

package main

import (
	"encoding/base64"
	"fmt"
	"io"
	"net/http"
	"net/url"
	"os"
)

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

	formData := url.Values{}
	formData.Set("To", "+1234567890")
	formData.Set("From", "+1987654321")
	formData.Set("Url", "https://example.com/twiml")

	req, err := http.NewRequest(
		"POST",
		fmt.Sprintf("https://api.twilio.com/2010-04-01/Accounts/%s/Call.json", accountSid),
		strings.NewReader(formData.Encode()),
	)
	if err != nil {
		panic(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 {
		panic(err)
	}
	defer resp.Body.Close()

	if resp.StatusCode >= 400 {
		body, _ := io.ReadAll(resp.Body)
		panic(fmt.Sprintf("Request failed: %s", string(body)))
	}

	body, _ := io.ReadAll(resp.Body)
	fmt.Println(string(body))
}

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}/Call.json");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
    'To' => '+1234567890',
    'From' => '+1987654321',
    'Url' => 'https://example.com/twiml'
]));
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 >= 400) {
    throw new Exception("Request failed: " . $response);
}

echo $response;

Ruby · net/http

require 'net/http'
require 'uri'
require 'base64'

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}/Call.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' => '+1987654321',
  'Url' => 'https://example.com/twiml'
})

response = http.request(request)

if response.code.to_i >= 400
  raise "Request failed: #{response.body}"
end

puts 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 + "/Call.json")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")

let body = "To=+1234567890&From=+1987654321&Url=https://example.com/twiml"
request.httpBody = body.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 {
        fatalError("Request failed: \(error)")
    }
    guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode < 400 else {
        fatalError("Request failed with status: \((response as? HTTPURLResponse)?.statusCode ?? 0)")
    }
    if let data = data, let json = try? JSONSerialization.jsonObject(with: data) {
        print(json)
    }
}
task.resume()
RunLoop.main.run()

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 form = HashMap::new();
    form.insert("To", "+1234567890");
    form.insert("From", "+1987654321");
    form.insert("Url", "https://example.com/twiml");

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

    if !response.status().is_success() {
        return Err(format!("Request failed: {}", response.text()?).into());
    }

    println!("{:?}", response.json::<serde_json::Value>()?);
    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 formData = new Dictionary<string, string>
        {
            {"To", "+1234567890"},
            {"From", "+1987654321"},
            {"Url", "https://example.com/twiml"}
        };

        var content = new FormUrlEncodedContent(formData);
        var request = new HttpRequestMessage(HttpMethod.Post, 
            $"https://api.twilio.com/2010-04-01/Accounts/{accountSid}/Call.json")
        {
            Content = content
        };
        request.Headers.Authorization = new AuthenticationHeaderValue(
            "Basic", Convert.ToBase64String(
                System.Text.Encoding.ASCII.GetBytes($"{accountSid}:{authToken}")));

        var response = await client.SendAsync(request);
        if (!response.IsSuccessStatusCode)
        {
            throw new Exception($"Request failed: {await response.Content.ReadAsStringAsync()}");
        }
        var responseBody = await response.Content.ReadAsStringAsync();
        Console.WriteLine(responseBody);
    }
}

Translation notes

  • Basic auth is handled via library-specific auth helpers where available (e.g., requests' auth param, axios' auth config)
  • Form data is sent as application/x-www-form-urlencoded in all implementations
  • Environment variables are used for sensitive credentials (TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN)
  • Error handling checks HTTP status codes and raises exceptions on failure
  • Python implementations use both requests and httpx for completeness

Common pitfalls when porting

  • Forgetting to URL-encode form data in languages that don't handle it automatically
  • Incorrectly setting the Authorization header (e.g., not using Basic auth with base64-encoded credentials)
  • Not properly handling SSL/TLS in Go or Swift
  • Assuming JSON response without checking Content-Type header
  • Using hardcoded credentials instead of environment variables

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 prevent credentials from being committed to version control and allow different configurations across environments without code changes.

How do I handle pagination or large responses?

Use streaming or chunked responses where supported by the library (e.g., httpx.stream, axios responseType: 'stream').

Can I use bearer token auth instead of basic auth?

Twilio requires Basic auth with Account SID and Auth Token. Bearer tokens are not supported for this endpoint.