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:
    raise Exception(f"Request failed with status {response.status_code}: {response.text}")

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:
    raise Exception(f"Request failed with status {response.status_code}: {response.text}")

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 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.ok) {
    throw new Error(`Request failed with status ${response.status}: ${response.statusText}`);
  }
  return response.text();
})
.then(data => console.log(data))
.catch(error => console.error('Error:', error));

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(`Request failed with status ${response.status}: ${response.statusText}`);
  }
  console.log(response.data);
})
.catch(error => {
  console.error('Error:', error.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)

	client := &http.Client{}
	req, err := http.NewRequest("DELETE", url, nil)
	if err != nil {
		panic(err)
	}

	req.SetBasicAuth(accountSid, authToken)

	resp, err := client.Do(req)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()

	if resp.StatusCode >= 400 {
		panic(fmt.Sprintf("Request failed with status %d: %s", resp.StatusCode, resp.Status))
	}

	fmt.Println("Request successful")
}

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' && $http_response_header[0] !== 'HTTP/2 200') {
    throw new Exception("Request failed with status: " . $http_response_header[0]);
}

echo $response;

Ruby · net/http

require 'net/http'
require 'uri'
require 'base64'

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
  raise "Request failed with status #{response.code}: #{response.body}"
end

puts response.body

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"
let url = URL(string: urlString)!

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 {
        fatalError("Request failed: \(error)")
    }
    guard let httpResponse = response as? HTTPURLResponse else {
        fatalError("Invalid response")
    }
    if httpResponse.statusCode >= 400 {
        fatalError("Request failed with status \(httpResponse.statusCode)")
    }
    if let data = data, let responseString = String(data: data, encoding: .utf8) {
        print(responseString)
    }
}
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 phone_number_sid = env::var("TWILIO_PHONE_NUMBER_SID")?;

    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 = client
        .delete(&url)
        .basic_auth(account_sid, Some(auth_token))
        .send()?;

    if !response.status().is_success() {
        return Err(format!("Request failed with status: {}", response.status()).into());
    }

    println!("{}", response.text()?);
    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");
        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)
        {
            throw new Exception($"Request failed with status {response.StatusCode}: {await response.Content.ReadAsStringAsync()}");
        }

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

Translation notes

  • Basic auth is used via environment variables for security
  • All implementations use the idiomatic HTTP client for each language
  • Error handling checks status codes >= 400 for failure
  • URLs are constructed with environment variables for sensitive values
  • No raw strings are used for JSON bodies (none in this request)

Common pitfalls when porting

  • Forgetting to set environment variables before running the code
  • Not handling basic auth correctly (e.g., missing base64 encoding in some languages)
  • Ignoring SSL/TLS verification (not shown here but important in production)
  • Assuming the response body is always JSON (it may be empty for DELETE)
  • Not properly closing resources (e.g., response bodies in Go, Swift, etc.)

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 (e.g., in version control). They also allow different configurations across environments (dev, staging, prod).

How do I handle rate limits or retries in these examples?

The examples focus on minimal error handling. For production, consider adding retry logic (e.g., with exponential backoff) and checking rate limit headers (e.g., `Retry-After`).

Can I use bearer token auth instead of basic auth?

Yes, but Twilio's API primarily uses basic auth with account SID and auth token. Bearer token auth would require API key generation in Twilio's console and adjusting the auth header accordingly.