Qaynaq LABS · TOOLS

CURL → CODE · DELETE · BASIC

cURL → 10 languages

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

Source cURL
curl -X DELETE https://api.twilio.com/2010-04-01/Accounts/AC1234567890/IncomingPhoneNumbers/PN1234567890.json \
  -u "AC1234567890:your_auth_token"

Python · requests

import os
import requests

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

url = f"https://api.twilio.com/2010-04-01/Accounts/{account_sid}/IncomingPhoneNumbers/{phone_number_sid}.json"

response = requests.delete(url, auth=(account_sid, auth_token))

if response.status_code >= 400:
    print(f"Error: {response.status_code} - {response.text}")
else:
    print("Success")

Python · httpx

import os
import httpx

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

url = f"https://api.twilio.com/2010-04-01/Accounts/{account_sid}/IncomingPhoneNumbers/{phone_number_sid}.json"

with httpx.Client() as client:
    response = client.delete(url, auth=(account_sid, auth_token))

    if response.status_code >= 400:
        print(f"Error: {response.status_code} - {response.text}")
    else:
        print("Success")

Node.js · fetch

import { Buffer } from 'buffer';
import fetch from 'node-fetch';

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

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

const credentials = Buffer.from(`${accountSid}:${authToken}`).toString('base64');

fetch(url, {
  method: 'DELETE',
  headers: {
    'Authorization': `Basic ${credentials}`
  }
})
  .then(response => {
    if (response.status >= 400) {
      return response.text().then(text => { throw new Error(`${response.status} - ${text}`); });
    }
    return response.text();
  })
  .then(() => console.log('Success'))
  .catch(err => console.error('Error:', err.message));

Node.js · axios

import axios from 'axios';

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

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

axios.delete(url, {
  auth: {
    username: accountSid,
    password: authToken
  }
})
  .then(response => {
    if (response.status >= 400) {
      throw new Error(`${response.status} - ${response.data}`);
    }
    console.log('Success');
  })
  .catch(err => console.error('Error:', err.message));

Go · net/http

package main

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

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

	url := fmt.Sprintf("https://api.twilio.com/2010-04-01/Accounts/%s/IncomingPhoneNumbers/%s.json", accountSid, phoneNumberSid)

	req, err := http.NewRequest("DELETE", url, nil)
	if err != nil {
		fmt.Println("Error creating request:", err)
		return
	}

	req.SetBasicAuth(accountSid, authToken)

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		fmt.Println("Error making request:", err)
		return
	}
	defer resp.Body.Close()

	if resp.StatusCode >= 400 {
		fmt.Printf("Error: %d - %s\n", resp.StatusCode, resp.Status)
	} else {
		fmt.Println("Success")
	}
}

PHP · cURL

<?php
$accountSid = getenv('TWILIO_ACCOUNT_SID');
$authToken = getenv('TWILIO_AUTH_TOKEN');
$phoneNumberSid = getenv('TWILIO_PHONE_NUMBER_SID');

$url = "https://api.twilio.com/2010-04-01/Accounts/{$accountSid}/IncomingPhoneNumbers/{$phoneNumberSid}.json";

$context = stream_context_create([
    'http' => [
        'method' => 'DELETE',
        'header' => "Authorization: Basic " . base64_encode("{$accountSid}:{$authToken}")
    ]
]);

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

if ($http_response_header[0] === 'HTTP/1.1 200 OK') {
    echo "Success\n";
} else {
    echo "Error: " . $http_response_header[0] . " - " . $response . "\n";
}
?>

Ruby · net/http

require 'net/http'
require 'uri'

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

uri = URI.parse("https://api.twilio.com/2010-04-01/Accounts/#{account_sid}/IncomingPhoneNumbers/#{phone_number_sid}.json")

http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true

request = Net::HTTP::Delete.new(uri.request_uri)
request.basic_auth(account_sid, auth_token)

response = http.request(request)

if response.code.to_i >= 400
  puts "Error: #{response.code} - #{response.body}"
else
  puts "Success"
end

Swift · URLSession

import Foundation

let accountSid = ProcessInfo.processInfo.environment["TWILIO_ACCOUNT_SID"] ?? ""
let authToken = ProcessInfo.processInfo.environment["TWILIO_AUTH_TOKEN"] ?? ""
let phoneNumberSid = ProcessInfo.processInfo.environment["TWILIO_PHONE_NUMBER_SID"] ?? ""

let urlString = "https://api.twilio.com/2010-04-01/Accounts/" + accountSid + "/IncomingPhoneNumbers/" + phoneNumberSid + ".json"

guard let url = URL(string: urlString) else {
    fatalError("Invalid URL")
}

var request = URLRequest(url: url)
request.httpMethod = "DELETE"
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 {
        print("Error: \(error)")
        return
    }

    guard let httpResponse = response as? HTTPURLResponse else {
        print("Invalid response")
        return
    }

    if httpResponse.statusCode >= 400 {
        print("Error: \(httpResponse.statusCode) - \(String(data: data ?? Data(), encoding: .utf8) ?? "")")
    } else {
        print("Success")
    }
}

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

Rust · reqwest

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

fn main() {
    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 phone_number_sid = env::var("TWILIO_PHONE_NUMBER_SID").expect("TWILIO_PHONE_NUMBER_SID must be set");

    let url = format!(
        "https://api.twilio.com/2010-04-01/Accounts/{}/IncomingPhoneNumbers/{}.json",
        account_sid, phone_number_sid
    );

    let client = Client::new();
    let response: Response = match client
        .delete(&url)
        .basic_auth(account_sid, Some(auth_token))
        .send()
    {
        Ok(res) => res,
        Err(e) => {
            eprintln!("Error making request: {}", e);
            return;
        }
    };

    if response.status().as_u16() >= 400 {
        eprintln!(
            "Error: {} - {}",
            response.status(),
            response.text().unwrap_or_default()
        );
    } else {
        println!("Success");
    }
}

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");
        var phoneNumberSid = Environment.GetEnvironmentVariable("TWILIO_PHONE_NUMBER_SID");

        var url = $"https://api.twilio.com/2010-04-01/Accounts/{accountSid}/IncomingPhoneNumbers/{phoneNumberSid}.json";

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

        var response = await client.DeleteAsync(url);

        if (!response.IsSuccessStatusCode)
        {
            var errorContent = await response.Content.ReadAsStringAsync();
            Console.WriteLine($"Error: {response.StatusCode} - {errorContent}");
        }
        else
        {
            Console.WriteLine("Success");
        }
    }
}

Translation notes

  • All implementations use environment variables for credentials (TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN, TWILIO_PHONE_NUMBER_SID)
  • Basic auth is handled via the library's built-in mechanisms where available
  • Error handling checks status code >= 400 and prints the response body
  • URLs are constructed with environment variable placeholders for clarity
  • Python implementations use requests and httpx, both popular HTTP libraries

Common pitfalls when porting

  • Forgetting to set environment variables before running the code
  • Using hardcoded credentials in the code (security risk)
  • Not handling SSL/TLS properly in languages like Go or Ruby
  • Ignoring HTTP status codes and assuming success
  • Not properly encoding credentials for Basic Auth in some languages

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 secrets from code, reducing the risk of accidental exposure in version control or logs. They also allow easy configuration across different environments.

How do I set the environment variables before running the code?

For example in bash: `export TWILIO_ACCOUNT_SID=AC1234567890; export TWILIO_AUTH_TOKEN=your_auth_token; export TWILIO_PHONE_NUMBER_SID=PN1234567890`

What if I need to use a proxy?

Most libraries allow configuring a proxy via environment variables (e.g., HTTP_PROXY) or directly in the client configuration.