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=%2B1234567890" -d "From=%2B1234567890" -d "Body=Hello from Twilio"

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}/Messages.json",
    auth=(account_sid, auth_token),
    data={
        "To": "+1234567890",
        "From": "+1234567890",
        "Body": "Hello from Twilio"
    }
)

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']

with httpx.Client() as client:
    response = 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 from Twilio"
        }
    )

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

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 credentials = Buffer.from(`${accountSid}:${authToken}`).toString('base64');

fetch(`https://api.twilio.com/2010-04-01/Accounts/${accountSid}/Messages.json`, {
    method: 'POST',
    headers: {
        'Authorization': `Basic ${credentials}`
    },
    body: new URLSearchParams({
        'To': '+1234567890',
        'From': '+1234567890',
        'Body': 'Hello from Twilio'
    })
})
.then(res => res.json())
.then(json => console.log(json))
.catch(err => console.error(err));

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 from Twilio'
    }),
    {
        auth: {
            username: accountSid,
            password: authToken
        }
    }
)
.then(response => 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")

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

	req, err := http.NewRequest(
		"POST",
		fmt.Sprintf("https://api.twilio.com/2010-04-01/Accounts/%s/Messages.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 {
		fmt.Println("Error:", resp.Status)
	} else {
		// Simple body read for demo; use json.Decoder in production
		fmt.Println(resp.Status)
	}
}

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";
$fields = [
    'To' => '+1234567890',
    'From' => '+1234567890',
    'Body' => 'Hello from Twilio'
];

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

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

if ($result === FALSE) {
    echo "Error fetching data\n";
} else {
    echo $result;
}
?>

Ruby · net/http

require 'net/http'
require 'uri'
require 'cgi'

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 from Twilio'
})

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=%2B1234567890&From=%2B1234567890&Body=Hello%20from%20Twilio"
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: \(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("Error: \(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 client = Client::new();
    let mut form = HashMap::new();
    form.insert("To", "+1234567890");
    form.insert("From", "+1234567890");
    form.insert("Body", "Hello from Twilio");

    let response: 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.json::<serde_json::Value>()?);
    } 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 formData = new Dictionary<string, string>
        {
            {"To", "+1234567890"},
            {"From", "+1234567890"},
            {"Body", "Hello from Twilio"}
        };

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

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

        var response = await client.SendAsync(request);
        var responseBody = await response.Content.ReadAsStringAsync();

        if (response.IsSuccessStatusCode)
        {
            Console.WriteLine(responseBody);
        }
        else
        {
            Console.WriteLine(responseBody);
        }
    }
}

Translation notes

  • All implementations use environment variables for credentials (TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN)
  • Basic auth is handled via the library's built-in mechanisms where possible
  • Form data is sent as application/x-www-form-urlencoded
  • Error handling checks status code and prints response body
  • Python implementations use requests/httpx, Node uses fetch/axios, Go uses net/http, PHP uses file_get_contents with stream context, Ruby uses Net::HTTP, Swift uses URLSession, Rust uses reqwest blocking client, C# uses HttpClient

Common pitfalls when porting

  • Forgetting to set environment variables before running the code
  • Not handling basic auth correctly (e.g., missing username/password in auth header)
  • Sending JSON instead of form data (Twilio expects form-encoded for this endpoint)
  • Ignoring SSL/TLS verification in Go or other low-level clients
  • Not properly encoding form data in languages without built-in helpers
  • Assuming the response is always JSON (some errors may return plain text)

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 is the body sent as form data instead of JSON?

Twilio's Messages endpoint expects form-encoded data for sending SMS, even though the response is JSON. Using JSON would result in a 400 Bad Request.

Can I use async/await in Python or Node?

Yes, but the examples use synchronous code for simplicity. Both requests and httpx support async, and Node fetch/axios are inherently async.

How do I handle pagination or large responses?

Use streaming or chunked reading in the client library. Most libraries provide methods like .iter_content() in Python or .ReadAsStreamAsync() in C#.

Is there a rate limit I should be aware of?

Yes, Twilio has rate limits. Check their documentation for current limits and implement retry logic with exponential backoff if needed.