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

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',
    auth=(account_sid, auth_token),
    data={'PhoneNumber': '+1234567890'}
)

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']

with httpx.Client() as client:
    response = client.post(
        f'https://api.twilio.com/2010-04-01/Accounts/{account_sid}/IncomingPhoneNumbers.json',
        auth=(account_sid, auth_token),
        data={'PhoneNumber': '+1234567890'}
    )
    response.raise_for_status()
    data = response.json()

Node.js · fetch

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

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

(async () => {
  const response = await fetch(
    `https://api.twilio.com/2010-04-01/Accounts/${accountSid}/IncomingPhoneNumbers.json`,
    {
      method: 'POST',
      headers: {
        'Authorization': 'Basic ' + Buffer.from(`${accountSid}:${authToken}`).toString('base64')
      },
      body: new URLSearchParams({'PhoneNumber': '+1234567890'})
    }
  );
  if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
  const data = await response.json();
})();

Node.js · axios

const axios = require('axios');

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

(async () => {
  const response = await axios.post(
    `https://api.twilio.com/2010-04-01/Accounts/${accountSid}/IncomingPhoneNumbers.json`,
    new URLSearchParams({'PhoneNumber': '+1234567890'}),
    {
      auth: {
        username: accountSid,
        password: authToken
      }
    }
  );
  const data = 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.Set("PhoneNumber", "+1234567890")

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

	// Process response body as needed
}

PHP · cURL

<?php

$accountSid = getenv('TWILIO_ACCOUNT_SID');
$authToken = getenv('TWILIO_AUTH_TOKEN');

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.twilio.com/2010-04-01/Accounts/{$accountSid}/IncomingPhoneNumbers.json");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(['PhoneNumber' => '+1234567890']));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, "{$accountSid}:{$authToken}");

$response = curl_exec($ch);
if (curl_errno($ch)) {
    throw new Exception(curl_error($ch));
}
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($httpCode !== 200) {
    throw new Exception("HTTP error! status: {$httpCode}");
}
$data = json_decode($response, true);
curl_close($ch);

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

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

data = JSON.parse(response.body)

Swift · URLSession

import Foundation

guard let accountSid = ProcessInfo.processInfo.environment["TWILIO_ACCOUNT_SID"],
      let authToken = ProcessInfo.processInfo.environment["TWILIO_AUTH_TOKEN"] else {
    fatalError("Missing environment variables TWILIO_ACCOUNT_SID or 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("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")

let body = "PhoneNumber=+1234567890"
request.httpBody = body.data(using: .utf8)

let authString = "\(accountSid):\(authToken)"
let authData = authString.data(using: .utf8)!.base64EncodedString()
request.setValue("Basic \(authData)", 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,
          (200...299).contains(httpResponse.statusCode) 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 ?? "No data")
    }
}
task.resume()
RunLoop.main.run()

Rust · reqwest

use reqwest::blocking::Client;
use std::collections::HashMap;
use std::env;

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

    let response = client
        .post(&format!(
            "https://api.twilio.com/2010-04-01/Accounts/{}/IncomingPhoneNumbers.json",
            account_sid
        ))
        .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 _data: 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();
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

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

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

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

Translation notes

  • All implementations use environment variables for credentials (TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN)
  • Basic auth is handled via the library's auth helpers where available
  • Form data is sent as application/x-www-form-urlencoded
  • Error handling checks HTTP status and raises/throws on failure
  • Response body is parsed as JSON where applicable

Common pitfalls when porting

  • Forgetting to set TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN environment variables
  • Using incorrect URL encoding for form data in languages without built-in helpers
  • Ignoring SSL/TLS verification in Go or other low-level clients
  • Not handling basic auth correctly in languages where it's not auto-applied
  • Assuming response body is always JSON (some APIs may return XML or other formats)

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 prevent credentials from being committed to version control and allow different configurations across environments without code changes.

Can I use bearer token auth instead of basic auth?

Twilio's API requires basic auth with Account SID as username and Auth Token as password. Bearer token auth is not supported for this endpoint.

What if I need to send JSON instead of form data?

Change the Content-Type header to application/json and send a JSON body. The current cURL uses form data (-d), so the implementations match that.