Qaynaq LABS · TOOLS

CURL → CODE · GET · BASIC

cURL → 10 languages

GET api.twilio.com · secrets replaced with env vars.

Source cURL
curl -X GET https://api.twilio.com/2010-04-01/Accounts/AC1234567890/SMS/Messages.json \
  -H "Authorization: Basic $(echo -n 'AC1234567890:a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6q7r8s9t0u' | base64)"

Python · requests

import os
import requests

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

response = requests.get(
    f"https://api.twilio.com/2010-04-01/Accounts/{account_sid}/SMS/Messages.json",
    auth=(account_sid, auth_token)
)

if response.status_code >= 400:
    raise Exception(f"Request failed: {response.status_code} - {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.get(
        f"https://api.twilio.com/2010-04-01/Accounts/{account_sid}/SMS/Messages.json",
        auth=(account_sid, auth_token)
    )

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

    print(response.json())

Node.js · fetch

import fetch from 'node-fetch';

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}/SMS/Messages.json`,
  {
    method: 'GET',
    headers: {
      'Authorization': `Basic ${Buffer.from(`${accountSid}:${authToken}`).toString('base64')}`
    }
  }
);

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

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;

try {
  const response = await axios.get(
    `https://api.twilio.com/2010-04-01/Accounts/${accountSid}/SMS/Messages.json`,
    {
      auth: {
        username: accountSid,
        password: authToken
      }
    }
  );

  console.log(response.data);
} catch (error) {
  if (error.response) {
    throw new Error(`Request failed: ${error.response.status} - ${error.response.data}`);
  }
  throw error;
}

Go · net/http

package main

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

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

	url := fmt.Sprintf("https://api.twilio.com/2010-04-01/Accounts/%s/SMS/Messages.json", accountSid)
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		panic(err)
	}

	auth := accountSid + ":" + authToken
	req.SetBasicAuth(accountSid, authToken)

	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: %d - %s", resp.StatusCode, string(body)))
	}

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

$context = stream_context_create([
    'http' => [
        'header' => "Authorization: Basic " . base64_encode("{$accountSid}:{$authToken}") . "\r\n"
    ]
]);

$response = file_get_contents($url, false, $context);

if ($http_response_header[0] !== 'HTTP/1.1 200 OK') {
    throw new Exception("Request failed: " . $http_response_header[0] . " - " . $response);
}

print($response);

Ruby · net/http

require 'net/http'
require 'json'
require 'base64'

account_sid = ENV['TWILIO_ACCOUNT_SID']
auth_token = ENV['TWILIO_AUTH_TOKEN']

uri = URI("https://api.twilio.com/2010-04-01/Accounts/#{account_sid}/SMS/Messages.json")
req = Net::HTTP::Get.new(uri)

req.basic_auth(account_sid, auth_token)

res = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http|
  http.request(req)
end

unless res.is_a?(Net::HTTPSuccess)
  raise "Request failed: #{res.code} - #{res.body}"
end

puts JSON.parse(res.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 + "/SMS/Messages.json")!
var request = URLRequest(url: url)
request.httpMethod = "GET"
request.setValue("Basic " + Data("\\(accountSid):\\(authToken)".utf8).base64EncodedString(), 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: \\((response as? HTTPURLResponse)?.statusCode ?? 0)")
    }

    if let data = data, let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] {
        print(json)
    }
}

task.resume()
RunLoop.main.run()

Rust · reqwest

use std::env;
use reqwest::blocking::Client;
use reqwest::Error;

fn main() -> Result<(), Error> {
    let account_sid = env::var("TWILIO_ACCOUNT_SID").expect("TWILIO_ACCOUNT_SID must be set");
    let auth_token = env::var("TWILIO_AUTH_TOKEN").expect("TWILIO_AUTH_TOKEN must be set");

    let client = Client::new();
    let url = format!(
        "https://api.twilio.com/2010-04-01/Accounts/{}/SMS/Messages.json",
        account_sid
    );

    let response = client
        .get(&url)
        .basic_auth(account_sid, Some(auth_token))
        .send()?;

    if !response.status().is_success() {
        panic!("Request failed: {} - {}", response.status(), response.text()?);
    }

    println!("{:?}", response.json::<serde_json::Value>()?);
    Ok(())
}

C# · HttpClient

using System;
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.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
            "Basic",
            Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes($"{accountSid}:{authToken}"))
        );

        var response = await client.GetAsync(
            $"https://api.twilio.com/2010-04-01/Accounts/{accountSid}/SMS/Messages.json"
        );

        if (!response.IsSuccessStatusCode)
        {
            throw new Exception($"Request failed: {(int)response.StatusCode} - {await response.Content.ReadAsStringAsync()}");
        }

        var content = await response.Content.ReadAsStringAsync();
        Console.WriteLine(content);
    }
}

Translation notes

  • All implementations use environment variables for credentials (TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN)
  • Basic auth is handled idiomatically in each language (e.g., requests uses auth tuple, axios uses auth config)
  • Error handling checks status code >= 400 and raises/throws an exception
  • JSON responses are parsed where applicable (e.g., Python, Ruby, Swift)
  • Go and Rust use blocking clients for simplicity; async variants would require more boilerplate

Common pitfalls when porting

  • Forgetting to set environment variables before running the code
  • Using incorrect environment variable names (e.g., TWILIO_SID instead of TWILIO_ACCOUNT_SID)
  • Not handling HTTP errors properly (e.g., ignoring status code checks)
  • In languages like Go or Rust, blocking vs. async clients can cause confusion in production code
  • In PHP, using file_get_contents without proper error handling for HTTP status codes

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 are more secure as they avoid exposing secrets in source code or version control. They also allow for different configurations across environments (dev, staging, prod).

Can I use bearer token authentication instead of basic auth?

Twilio's API primarily uses basic auth with Account SID and Auth Token. Bearer token auth is not supported for this endpoint.