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 $(echo -n 'AC1234567890:auth_token' | base64)" \
  -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,
    auth=(account_sid, auth_token),
    data=payload
)

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,
        auth=(account_sid, auth_token),
        data=payload
    )

    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 url = `https://api.twilio.com/2010-04-01/Accounts/${accountSid}/Messages.json`;

const payload = new URLSearchParams({
    To: '+1234567890',
    From: '+1987654321',
    Body: 'Hello from Twilio'
});

const response = await fetch(url, {
    method: 'POST',
    headers: {
        'Authorization': `Basic ${Buffer.from(`${accountSid}:${authToken}`).toString('base64')}`
    },
    body: payload
});

if (response.status >= 400) {
    console.log(await response.text());
} else {
    console.log(await response.json());
}

Node.js · axios

import axios from '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({
    To: '+1234567890',
    From: '+1987654321',
    Body: 'Hello from Twilio'
});

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

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";

$payload = [
    '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($payload)
    ]
];

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

if ($http_response_header[0] >= 400) {
    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' => '+1987654321',
  '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 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"
request.setValue("Basic " + Data("\\(accountSid):\\(authToken)".utf8).base64EncodedString(), forHTTPHeaderField: "Authorization")

let body = "To=+1234567890&From=+1987654321&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)
        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()
sleep(1)

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 form_data = HashMap::new();
    form_data.insert("To", "+1234567890");
    form_data.insert("From", "+1987654321");
    form_data.insert("Body", "Hello from Twilio");

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

    if response.status().as_u16() >= 400 {
        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 client = new HttpClient();
        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"}
        };

        var content = new FormUrlEncodedContent(formData);

        var request = new HttpRequestMessage(HttpMethod.Post, url)
        {
            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 account SID and auth token
  • Form data is used for the request body as in the original cURL
  • Error handling checks for HTTP status codes >= 400
  • All implementations use idiomatic HTTP clients for their respective languages
  • Python implementations use requests and httpx, both popular libraries

Common pitfalls when porting

  • Forgetting to set environment variables before running the code
  • Not handling HTTP errors properly (e.g., ignoring status codes)
  • Incorrectly encoding form data in languages that require manual encoding
  • Using raw strings for JSON bodies when form data is expected
  • 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 is Basic auth used instead of Bearer token?

Twilio's API uses Basic auth with the Account SID as the username and the Auth Token as the password, encoded in Base64 in the Authorization header.

Can I use a different HTTP client library?

Yes, but ensure it supports Basic auth and form data encoding. The examples use idiomatic libraries for each language.

How do I set the environment variables?

Set TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN in your shell or environment before running the code. Example: export TWILIO_ACCOUNT_SID=AC1234567890; export TWILIO_AUTH_TOKEN=your_auth_token