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/IncomingPhoneNumbers.json \
  -u "AC1234567890:your_auth_token" \
  -d "PhoneNumber=%2B1234567890" -d "FriendlyName=My+Number"

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}/IncomingPhoneNumbers.json"

payload = {
    "PhoneNumber": "+1234567890",
    "FriendlyName": "My Number"
}

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}/IncomingPhoneNumbers.json"

payload = {
    "PhoneNumber": "+1234567890",
    "FriendlyName": "My Number"
}

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

const fetch = require('node-fetch');

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}/IncomingPhoneNumbers.json`;

const payload = new URLSearchParams();
payload.append('PhoneNumber', '+1234567890');
payload.append('FriendlyName', 'My Number');

fetch(url, {
    method: 'POST',
    headers: {
        'Authorization': 'Basic ' + Buffer.from(`${accountSid}:${authToken}`).toString('base64')
    },
    body: payload
})
.then(response => {
    if (response.status >= 400) {
        return response.text().then(text => { throw new Error(text); });
    }
    return response.json();
})
.then(data => console.log(data))
.catch(err => console.error(err));

Node.js · axios

const axios = require('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}/IncomingPhoneNumbers.json`;

const payload = new URLSearchParams();
payload.append('PhoneNumber', '+1234567890');
payload.append('FriendlyName', 'My Number');

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

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/"
	path := fmt.Sprintf("%s/IncomingPhoneNumbers.json", accountSid)
	fullURL := baseURL + path

	formData := url.Values{}
	formData.Add("PhoneNumber", "+1234567890")
	formData.Add("FriendlyName", "My Number")

	req, err := http.NewRequest("POST", fullURL, 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}/IncomingPhoneNumbers.json";

$postData = [
    'PhoneNumber' => '+1234567890',
    'FriendlyName' => 'My Number'
];

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

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

if ($http_response_header[0] >= 400) {
    echo $response;
} else {
    echo $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}/IncomingPhoneNumbers.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({
  'PhoneNumber' => '+1234567890',
  'FriendlyName' => 'My Number'
})

response = http.request(request)

if response.code.to_i >= 400
  puts response.body
else
  puts JSON.parse(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 + "/IncomingPhoneNumbers.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 bodyString = "PhoneNumber=%2B1234567890&FriendlyName=My+Number"
request.httpBody = bodyString.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 json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] {
            print(json)
        }
    }
}

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 url = format!(
        "https://api.twilio.com/2010-04-01/Accounts/{}/IncomingPhoneNumbers.json",
        account_sid
    );

    let mut form = HashMap::new();
    form.insert("PhoneNumber", "+1234567890");
    form.insert("FriendlyName", "My Number");

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

    if response.status().as_u16() >= 400 {
        println!("{}", response.text()?);
    } else {
        println!("{:?}", response.json::<serde_json::Value>()?);
    }

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

        var formData = new Dictionary<string, string>
        {
            {"PhoneNumber", "+1234567890"},
            {"FriendlyName", "My Number"}
        };

        using var client = new HttpClient();
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
            "Basic",
            Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes($"{accountSid}:{authToken}"))
        );

        var response = await client.PostAsync(url, new FormUrlEncodedContent(formData));

        if (response.IsSuccessStatusCode)
        {
            var content = await response.Content.ReadAsStringAsync();
            Console.WriteLine(content);
        }
        else
        {
            var errorContent = await response.Content.ReadAsStringAsync();
            Console.WriteLine(errorContent);
        }
    }
}

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 in all cases
  • Error handling checks status code >= 400 and prints the response body
  • Python implementations use requests and httpx, Node.js uses fetch and axios, Go uses net/http, PHP uses file_get_contents with stream context, Ruby uses Net::HTTP, Swift uses URLSession, Rust uses reqwest, C# uses HttpClient

Common pitfalls when porting

  • Forgetting to set environment variables before running the code
  • Not handling basic auth correctly (e.g., using wrong encoding or missing auth header)
  • Sending JSON body instead of form data (the cURL uses -d for form data)
  • Ignoring SSL/TLS verification (most libraries handle this by default, but it's worth noting)
  • Assuming the response is always JSON (some APIs may return XML or plain text on error)

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 don't expose sensitive data in source code or version control systems. They also allow for easy configuration changes without modifying the code.

How do I handle pagination or large responses?

Most HTTP libraries provide streaming or chunked response handling. For example, in Python's requests you can use response.iter_content(), in Node.js you can use response.body.pipe(), and in Go you can use io.Copy().

What if the API returns a non-JSON response?

Check the Content-Type header of the response. If it's not application/json, parse the response body accordingly (e.g., as XML or plain text).

How do I add custom headers to the request?

In most libraries, you can add custom headers using the headers parameter or by setting them directly on the request object. For example, in Python requests: requests.post(url, headers={'X-Custom': 'value'}, ...).