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 \
  --data-urlencode "PhoneNumber=+1234567890" \
  --data-urlencode "FriendlyName=My+Number" \
  --user "AC1234567890:your_auth_token"

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}/IncomingPhoneNumbers.json",
    data={
        "PhoneNumber": "+1234567890",
        "FriendlyName": "My Number"
    },
    auth=(account_sid, auth_token)
)

response.raise_for_status()
data = response.json()

Python · httpx

import os
import httpx

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

async def main():
    async with httpx.AsyncClient() as client:
        response = await client.post(
            f"https://api.twilio.com/2010-04-01/Accounts/{account_sid}/IncomingPhoneNumbers.json",
            data={
                "PhoneNumber": "+1234567890",
                "FriendlyName": "My Number"
            },
            auth=(account_sid, auth_token)
        )
        response.raise_for_status()
        data = response.json()

# For synchronous usage:
# with httpx.Client() as client:
#     response = client.post(...)
#     response.raise_for_status()
#     data = response.json()

Node.js · fetch

import { Buffer } from 'node:buffer';
import process from 'node:process';

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

const url = new URL(`https://api.twilio.com/2010-04-01/Accounts/${accountSid}/IncomingPhoneNumbers.json`);

const response = await fetch(url, {
  method: 'POST',
  headers: {
    'Authorization': 'Basic ' + Buffer.from(`${accountSid}:${authToken}`).toString('base64')
  },
  body: new URLSearchParams({
    'PhoneNumber': '+1234567890',
    'FriendlyName': 'My Number'
  })
});

if (!response.ok) {
  throw new Error(`HTTP error! status: ${response.status}`);
}

const data = await response.json();

Node.js · axios

import axios from 'axios';
import process from 'node:process';

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}/IncomingPhoneNumbers.json`,
  new URLSearchParams({
    'PhoneNumber': '+1234567890',
    'FriendlyName': 'My Number'
  }),
  {
    auth: {
      username: accountSid,
      password: authToken
    }
  }
);

if (response.status >= 400) {
  throw new Error(`HTTP error! status: ${response.status}`);
}

const data = response.data;

Go · net/http

package main

import (
	"fmt"
	"log"
	"net/http"
	"net/url"
	"os"
)

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

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

	req, err := http.NewRequest(
		"POST",
		fmt.Sprintf("https://api.twilio.com/2010-04-01/Accounts/%s/IncomingPhoneNumbers.json", accountSid),
		strings.NewReader(data.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()

	if resp.StatusCode >= 400 {
		log.Fatalf("HTTP error! status: %s", resp.Status)
	}

	// Parse response body as JSON
	var result map[string]interface{}
	if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
		log.Fatal(err)
	}
}

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";
$data = [
    'PhoneNumber' => '+1234567890',
    'FriendlyName' => 'My Number'
];

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

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

if ($http_response_header[0] !== 'HTTP/1.1 200 OK' && $http_response_header[0] !== 'HTTP/1.1 201 Created') {
    throw new Exception("HTTP error! status: " . $http_response_header[0]);
}

$data = json_decode($result, true);

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)

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

# Parse response body as JSON
data = 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 + "/IncomingPhoneNumbers.json")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("Basic " + Data((accountSid + ":" + authToken).utf8).base64EncodedString(), forHTTPHeaderField: "Authorization")

let body = "PhoneNumber=+1234567890&FriendlyName=My+Number"
request.httpBody = body.data(using: .utf8)
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")

let (data, response, error) = URLSession.shared.synchronousDataTask(with: request)

if let error = error {
    fatalError("Error: \(error)")
}

if let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode >= 400 {
    fatalError("HTTP error! status: \(httpResponse.statusCode)")
}

let json = try JSONSerialization.jsonObject(with: data!, options: []) as? [String: Any]

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 params = HashMap::new();
    params.insert("PhoneNumber", "+1234567890");
    params.insert("FriendlyName", "My Number");

    let response: Response = client
        .post(&format!(
            "https://api.twilio.com/2010-04-01/Accounts/{}/IncomingPhoneNumbers.json",
            account_sid
        ))
        .basic_auth(&account_sid, Some(&auth_token))
        .form(&params)
        .send()?;

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

    let _: serde_json::Value = response.json()?;
    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();
        var request = new HttpRequestMessage(HttpMethod.Post, 
            $"https://api.twilio.com/2010-04-01/Accounts/{accountSid}/IncomingPhoneNumbers.json");

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

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

        request.Content = new FormUrlEncodedContent(formData);

        var response = await client.SendAsync(request);
        if (!response.IsSuccessStatusCode)
        {
            throw new Exception($"HTTP error! status: {response.StatusCode}");
        }

        var content = await response.Content.ReadAsStringAsync();
        var data = System.Text.Json.JsonSerializer.Deserialize<object>(content);
    }
}

Translation notes

  • All implementations use environment variables for credentials (TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN)
  • Basic auth is used in all cases, matching the --user flag in cURL
  • Form data is sent as application/x-www-form-urlencoded in all implementations
  • Error handling checks HTTP status codes and raises/throws on failure
  • Python httpx example includes both async and sync usage patterns
  • Go example uses url.Values for form data encoding
  • Swift example uses synchronous URLSession for simplicity (not recommended for production)
  • Rust example uses reqwest blocking client for simplicity (async version would be more idiomatic)

Common pitfalls when porting

  • Forgetting to set Content-Type header for form data (some libraries do this automatically)
  • Not properly URL-encoding form data (especially in languages with manual string building)
  • Ignoring SSL certificate verification (important for production)
  • Not handling HTTP redirects (some libraries follow redirects by default)
  • Assuming synchronous HTTP calls are acceptable in all contexts (especially in Swift example)
  • Not properly escaping environment variable values that might contain special characters

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 separate configuration from code, making it easier to manage secrets and avoid accidental commits to version control. They also allow different configurations across environments (dev, staging, prod).

How do I handle pagination or large responses?

Most HTTP libraries provide streaming or pagination helpers. For example, in Python requests you can use response.iter_content() for large files, and in Go you can use io.LimitReader to control memory usage.

Why does the Swift example use synchronous URLSession?

The synchronous example is provided for simplicity and matches the structure of other examples. In production Swift code, you should use async/await with URLSession.data(for:) for better performance and to avoid blocking the main thread.

How do I add query parameters to the URL?

Most libraries provide URL builder utilities. For example, in Python requests you can pass params={'key': 'value'} to the request method, and in Go you can use url.Values to construct the query string.