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/Messages.json -u "AC1234567890:your_auth_token" -d "To=+1234567890&From=+1987654321&Body=Hello%20from%20Twilio"

Python · requests

import os
import requests

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

url = f"https://api.twilio.com/2010-04-01/Accounts/{account_sid}/Messages.json"

payload = {
    'To': '+1234567890',
    'From': '+1987654321',
    'Body': 'Hello from Twilio'
}

response = requests.post(url, data=payload, auth=(account_sid, auth_token))

if response.status_code >= 400:
    print(response.text)
else:
    print(response.json())

Python · httpx

import os
import httpx

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

url = f"https://api.twilio.com/2010-04-01/Accounts/{account_sid}/Messages.json"

payload = {
    'To': '+1234567890',
    'From': '+1987654321',
    'Body': 'Hello from Twilio'
}

with httpx.Client() as client:
    response = client.post(url, data=payload, auth=(account_sid, auth_token))

    if response.status_code >= 400:
        print(response.text)
    else:
        print(response.json())

Node.js · fetch

const fetch = require('node-fetch');

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

const url = `https://api.twilio.com/2010-04-01/Accounts/${accountSid}/Messages.json`;

const payload = new URLSearchParams();
payload.append('To', '+1234567890');
payload.append('From', '+1987654321');
payload.append('Body', 'Hello from Twilio');

fetch(url, {
    method: 'POST',
    headers: {
        'Authorization': 'Basic ' + Buffer.from(`${accountSid}:${authToken}`).toString('base64')
    },
    body: payload
})
.then(response => {
    if (response.status >= 400) {
        return response.text();
    }
    return response.json();
})
.then(data => console.log(data))
.catch(err => console.error(err));

Node.js · axios

const axios = require('axios');

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

const url = `https://api.twilio.com/2010-04-01/Accounts/${accountSid}/Messages.json`;

const payload = new URLSearchParams();
payload.append('To', '+1234567890');
payload.append('From', '+1987654321');
payload.append('Body', 'Hello from Twilio');

axios.post(url, payload, {
    auth: {
        username: accountSid,
        password: authToken
    }
})
.then(response => {
    if (response.status >= 400) {
        console.log(response.data);
    } else {
        console.log(response.data);
    }
})
.catch(err => console.error(err));

Go · net/http

package main

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

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

	baseURL := "https://api.twilio.com/2010-04-01/Accounts/"
	requestURL := baseURL + accountSid + "/Messages.json"

	formData := url.Values{}
	formData.Set("To", "+1234567890")
	formData.Set("From", "+1987654321")
	formData.Set("Body", "Hello from Twilio")

	req, err := http.NewRequest("POST", requestURL, 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()

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		log.Fatal(err)
	}

	if resp.StatusCode >= 400 {
		fmt.Println(string(body))
	} else {
		fmt.Println(string(body))
	}
}

PHP · cURL

<?php

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

$url = "https://api.twilio.com/2010-04-01/Accounts/{$accountSid}/Messages.json";

$postData = [
    'To' => '+1234567890',
    'From' => '+1987654321',
    'Body' => 'Hello from Twilio'
];

$options = [
    'http' => [
        'header' => "Authorization: Basic " . base64_encode("{$accountSid}:{$authToken}") . "\r\n",
        'method' => 'POST',
        'content' => http_build_query($postData)
    ]
];

$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);

if ($http_response_header[0] === 'HTTP/1.1 400 Bad Request' || strpos($http_response_header[0], '40') === 0) {
    echo $result;
} else {
    echo $result;
}

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}/Messages.json")

params = {
  'To' => '+1234567890',
  'From' => '+1987654321',
  'Body' => 'Hello from Twilio'
}

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

request = Net::HTTP::Post.new(uri.request_uri)
request.set_form_data(params)
request.basic_auth(account_sid, auth_token)

response = http.request(request)

if response.code.to_i >= 400
  puts response.body
else
  puts response.body
end

Swift · URLSession

import Foundation

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

let urlString = "https://api.twilio.com/2010-04-01/Accounts/" + accountSid + "/Messages.json"
let url = URL(string: urlString)!

var request = URLRequest(url: url)
request.httpMethod = "POST"

let params = [
    "To": "+1234567890",
    "From": "+1987654321",
    "Body": "Hello from Twilio"
]

request.httpBody = params.map { "\($0)=\($1)" }.joined(separator: "&").data(using: .utf8)
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")

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)
        return
    }

    guard let httpResponse = response as? HTTPURLResponse else {
        print("Invalid response")
        return
    }

    if httpResponse.statusCode >= 400 {
        if let data = data, let responseBody = String(data: data, encoding: .utf8) {
            print(responseBody)
        }
    } else {
        if let data = data, let responseBody = String(data: data, encoding: .utf8) {
            print(responseBody)
        }
    }
}

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 url = format!(
        "https://api.twilio.com/2010-04-01/Accounts/{}/Messages.json",
        account_sid
    );

    let mut params = HashMap::new();
    params.insert("To", "+1234567890");
    params.insert("From", "+1987654321");
    params.insert("Body", "Hello from Twilio");

    let client = Client::new();
    let response: Response = client
        .post(&url)
        .basic_auth(account_sid, Some(auth_token))
        .form(&params)
        .send()?;

    if response.status().is_client_error() || response.status().is_server_error() {
        println!("{}", response.text()?);
    } else {
        println!("{}", response.text()?);
    }

    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(string[] args)
    {
        var accountSid = Environment.GetEnvironmentVariable("TWILIO_ACCOUNT_SID");
        var authToken = Environment.GetEnvironmentVariable("TWILIO_AUTH_TOKEN");

        var url = $"https://api.twilio.com/2010-04-01/Accounts/{accountSid}/Messages.json";

        var formData = new Dictionary<string, string>
        {
            {"To", "+1234567890"},
            {"From", "+1987654321"},
            {"Body", "Hello from Twilio"}
        };

        using var client = new HttpClient();
        using var content = new FormUrlEncodedContent(formData);

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

        var response = await client.PostAsync(url, content);

        if (!response.IsSuccessStatusCode)
        {
            var responseBody = await response.Content.ReadAsStringAsync();
            Console.WriteLine(responseBody);
        }
        else
        {
            var responseBody = await response.Content.ReadAsStringAsync();
            Console.WriteLine(responseBody);
        }
    }
}

Translation notes

  • Basic auth is used via environment variables for credentials
  • Form data is sent as application/x-www-form-urlencoded
  • Error handling checks for 4xx/5xx status codes
  • All implementations use idiomatic HTTP clients for their language
  • Secrets are read from environment variables, never hardcoded

Common pitfalls when porting

  • Forgetting to URL-encode form data in languages that don't handle it automatically
  • Not setting the Content-Type header for form data in some libraries
  • Ignoring SSL/TLS verification in Go or Rust (not shown here but common)
  • Assuming JSON response when the API returns form-encoded or XML
  • Not handling basic auth encoding correctly in languages with strict auth helpers

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 basic auth instead of a bearer token?

Twilio's API uses HTTP Basic Auth with the Account SID as the username and the Auth Token as the password. This is Twilio's standard authentication method.

Can I use JSON instead of form data?

No, the Twilio Messages API requires form-encoded data for sending messages. JSON is not supported for this endpoint.

How do I handle pagination or large responses?

The Twilio API uses standard HTTP pagination. For large responses, implement streaming or chunked reading in your HTTP client.