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 \
  -H "Authorization: Basic YWN0aXZlOnNlY3JldA==" \
  -d "To=+1234567890&From=+1234567890&Body=Hello" --data-urlencode

Python · requests

import os
import requests

account_sid = os.environ.get('TWILIO_ACCOUNT_SID')
auth_token = os.environ.get('TWILIO_AUTH_TOKEN')

response = requests.post(
    f'https://api.twilio.com/2010-04-01/Accounts/{account_sid}/Messages.json',
    auth=(account_sid, auth_token),
    data={
        'To': '+1234567890',
        'From': '+1234567890',
        'Body': 'Hello'
    }
)

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

Python · httpx

import os
import httpx

account_sid = os.environ.get('TWILIO_ACCOUNT_SID')
auth_token = os.environ.get('TWILIO_AUTH_TOKEN')

async def send_message():
    async with httpx.AsyncClient() as client:
        response = await client.post(
            f'https://api.twilio.com/2010-04-01/Accounts/{account_sid}/Messages.json',
            auth=(account_sid, auth_token),
            data={
                'To': '+1234567890',
                'From': '+1234567890',
                'Body': 'Hello'
            }
        )
        if response.status_code >= 400:
            print(response.text)
        else:
            print(response.json())

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

Node.js · fetch

import fetch from 'node-fetch';
import { Buffer } from 'buffer';

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

const auth = Buffer.from(`${accountSid}:${authToken}`).toString('base64');

fetch(`https://api.twilio.com/2010-04-01/Accounts/${accountSid}/Messages.json`, {
    method: 'POST',
    headers: {
        'Authorization': `Basic ${auth}`
    },
    body: new URLSearchParams({
        'To': '+1234567890',
        'From': '+1234567890',
        'Body': 'Hello'
    })
})
.then(response => {
    if (response.ok) {
        return response.json();
    }
    return response.text().then(text => { throw new Error(text); });
})
.then(data => console.log(data))
.catch(error => console.error(error));

Node.js · axios

import axios from 'axios';

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

axios.post(
    `https://api.twilio.com/2010-04-01/Accounts/${accountSid}/Messages.json`,
    new URLSearchParams({
        'To': '+1234567890',
        'From': '+1234567890',
        'Body': 'Hello'
    }),
    {
        auth: {
            username: accountSid,
            password: authToken
        }
    }
)
.then(response => {
    if (response.status >= 400) {
        console.error(response.data);
    } else {
        console.log(response.data);
    }
})
.catch(error => {
    console.error(error.response?.data || error.message);
});

Go · net/http

package main

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

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

    form := url.Values{}
    form.Add("To", "+1234567890")
    form.Add("From", "+1234567890")
    form.Add("Body", "Hello")

    req, err := http.NewRequest(
        "POST",
        fmt.Sprintf("https://api.twilio.com/2010-04-01/Accounts/%s/Messages.json", accountSid),
        strings.NewReader(form.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)
        fmt.Println(string(body))
    } else {
        body, _ := io.ReadAll(resp.Body)
        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";
$data = [
    'To' => '+1234567890',
    'From' => '+1234567890',
    'Body' => 'Hello'
];

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

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

if ($http_response_header[0] === 'HTTP/1.1 200 OK') {
    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")

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',
  'Body' => 'Hello'
})

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 url = URL(string: "https://api.twilio.com/2010-04-01/Accounts/" + accountSid + "/Messages.json")!
var request = URLRequest(url: url)
request.httpMethod = "POST"

let credentials = "\(accountSid):\(authToken)"
let base64Credentials = Data(credentials.utf8).base64EncodedString()
request.setValue("Basic \(base64Credentials)", forHTTPHeaderField: "Authorization")

let body = "To=+1234567890&From=+1234567890&Body=Hello"
request.httpBody = body.data(using: .utf8)
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")

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()

// Note: In a real app, you'd need to run the event loop (e.g., RunLoop.main.run() in a CLI app)

Rust · reqwest

use std::collections::HashMap;
use std::env;
use reqwest::blocking;
use reqwest::header;

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 = blocking::Client::new();
    let mut form = HashMap::new();
    form.insert("To", "+1234567890");
    form.insert("From", "+1234567890");
    form.insert("Body", "Hello");

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

    if response.status().is_success() {
        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()
    {
        var accountSid = Environment.GetEnvironmentVariable("TWILIO_ACCOUNT_SID");
        var authToken = Environment.GetEnvironmentVariable("TWILIO_AUTH_TOKEN");

        using var client = new HttpClient();
        client.BaseAddress = new Uri("https://api.twilio.com/");

        var form = new Dictionary<string, string>
        {
            {"To", "+1234567890"},
            {"From", "+1234567890"},
            {"Body", "Hello"}
        };

        var content = new FormUrlEncodedContent(form);

        var request = new HttpRequestMessage(HttpMethod.Post, 
            $"2010-04-01/Accounts/{accountSid}/Messages.json")
        {
            Content = content
        };

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

        var response = await client.SendAsync(request);

        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 handled via environment variables for accountSid and authToken
  • Form data is sent as application/x-www-form-urlencoded
  • Error handling checks status code >= 400 for failure
  • All implementations use idiomatic HTTP clients for their language
  • Python httpx example is async; synchronous version is commented
  • Go example uses net/http directly (no third-party libs)
  • Swift example requires manual event loop handling in CLI apps

Common pitfalls when porting

  • Forgetting to set Content-Type to application/x-www-form-urlencoded in non-library code
  • Not URL-encoding form data properly in languages without built-in helpers
  • Ignoring SSL/TLS verification in Go or Rust examples
  • Hardcoding credentials instead of using environment variables
  • Assuming synchronous HTTP calls will work in async contexts (e.g., Swift, Python httpx)

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 with Twilio instead of Bearer tokens?

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

How do I handle rate limits in these examples?

Add retry logic with exponential backoff. Most HTTP libraries have retry middleware or you can implement it manually.

Can I send JSON instead of form data?

Yes, but Twilio's Messages API expects form data. For JSON APIs, you'd use a different endpoint and content-type.