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=+1234567890&Body=Hello"

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

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

const response = await fetch(url, {
  method: 'POST',
  headers: {
    'Authorization': `Basic ${credentials}`
  },
  body: new URLSearchParams({
    'To': '+1234567890',
    'From': '+1234567890',
    'Body': 'Hello'
  })
});

if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
const data = await response.json();
console.log(data);

Node.js · axios

import axios from 'axios';

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

const response = await 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
    }
  }
);

console.log(response.data);

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

	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 != http.StatusOK {
		panic(fmt.Sprintf("HTTP error! status: %s", resp.Status))
	}

	// Handle response body as needed
}

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 ($result === FALSE) {
    throw new Exception("Request failed");
}

$response = json_decode($result, true);
print_r($response);

Ruby · net/http

require 'net/http'
require 'uri'
require 'json'

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)

unless response.is_a?(Net::HTTPSuccess)
  raise "HTTP error! status: #{response.code}"
end

puts JSON.parse(response.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 + "/Messages.json")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("Basic " + Data((accountSid + ":" + authToken).utf8).base64EncodedString(), 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 {
        fatalError("Request failed: \(error)")
    }
    guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else {
        fatalError("HTTP error! status: \((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::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 url = format!(
        "https://api.twilio.com/2010-04-01/Accounts/{}/Messages.json",
        account_sid
    );

    let form = [
        ("To", "+1234567890"),
        ("From", "+1234567890"),
        ("Body", "Hello"),
    ];

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

    if !response.status().is_success() {
        return Err(format!("HTTP error! status: {}", response.status()).into());
    }

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

    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 formData = new FormUrlEncodedContent(new[]
        {
            new KeyValuePair<string, string>("To", "+1234567890"),
            new KeyValuePair<string, string>("From", "+1234567890"),
            new KeyValuePair<string, string>("Body", "Hello")
        });

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

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

Translation notes

  • Basic auth is handled via the `auth` parameter in Python requests/httpx, `auth` in axios, and `SetBasicAuth` in Go.
  • Form data is sent as `data` in Python libraries, `URLSearchParams` in JavaScript, `http_build_query` in PHP, `set_form_data` in Ruby, and `FormUrlEncodedContent` in C#.
  • Environment variables are used for credentials in all implementations to avoid hardcoding secrets.
  • Error handling includes status code checks and response body reading where applicable.

Common pitfalls when porting

  • Forgetting to set the Content-Type header for form data in Go or Swift may cause the server to reject the request.
  • In Node.js, using `fetch` requires polyfills or Node 18+ for native support; otherwise, a library like `node-fetch` is needed.
  • In Rust, the `reqwest` blocking client is used for simplicity; async variants require additional setup.
  • In PHP, `file_get_contents` with stream context is used for simplicity, but may not be suitable for production environments with complex needs.

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 for credentials?

Environment variables separate secrets from code, reducing the risk of accidental exposure in version control or logs. They also allow easy configuration across different environments (dev, staging, prod).

How do I handle pagination or large responses?

Most HTTP libraries provide methods to stream or paginate responses. For example, in Python requests, use `response.iter_content` for streaming, and in Go, use `io.Copy` to handle large bodies.