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 --header "Authorization: Basic QUxDMTIzNDU2Nzg5MDo=" --data """}, {

Python · requests

import os
import requests

account_sid = os.environ["TWILIO_ACCOUNT_SID"]
phone_number_sid = os.environ["TWILIO_PHONE_NUMBER_SID"]
auth = (account_sid, os.environ["TWILIO_AUTH_TOKEN"])

response = requests.delete(
    f"https://api.twilio.com/2010-04-01/Accounts/{account_sid}/IncomingPhoneNumbers/{phone_number_sid}.json",
    auth=auth
)

response.raise_for_status()

Python · httpx

import os
import httpx

account_sid = os.environ["TWILIO_ACCOUNT_SID"]
phone_number_sid = os.environ["TWILIO_PHONE_NUMBER_SID"]
auth = (account_sid, os.environ["TWILIO_AUTH_TOKEN"])

with httpx.Client() as client:
    response = client.delete(
        f"https://api.twilio.com/2010-04-01/Accounts/{account_sid}/IncomingPhoneNumbers/{phone_number_sid}.json",
        auth=auth
    )
    response.raise_for_status()

Node.js · fetch

import fetch from 'node-fetch';
import { env } from 'process';

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

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

fetch(url.toString(), {
    method: 'DELETE',
    headers: {
        'Authorization': 'Basic ' + Buffer.from(`${accountSid}:${authToken}`).toString('base64')
    }
}).then(response => {
    if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
});

Node.js · axios

import axios from 'axios';
import { env } from 'process';

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

axios.delete(
    `https://api.twilio.com/2010-04-01/Accounts/${accountSid}/IncomingPhoneNumbers/${phoneNumberSid}.json`,
    {
        auth: {
            username: accountSid,
            password: authToken
        }
    }
).then(response => {
    if (response.status >= 400) throw new Error(`HTTP error! status: ${response.status}`);
});

Go · net/http

package main

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

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

	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 {
		panic(err)
	}

	req.SetBasicAuth(accountSid, authToken)

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

	if resp.StatusCode >= 400 {
		panic(fmt.Sprintf("HTTP error! status: %d", resp.StatusCode))
	}
}

PHP · cURL

<?php

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

$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/1.1 204 No Content') {
    throw new Exception("HTTP error! status: " . $http_response_header[0]);
}

Ruby · net/http

require 'net/http'
require 'uri'

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

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)

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

Swift · URLSession

import Foundation

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

let url = URL(string: "https://api.twilio.com/2010-04-01/Accounts/" + accountSid + "/IncomingPhoneNumbers/" + phoneNumberSid + ".json")!

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("Error: \(error)")
    }
    guard let httpResponse = response as? HTTPURLResponse else {
        fatalError("Invalid response")
    }
    if httpResponse.statusCode >= 400 {
        fatalError("HTTP error! status: \(httpResponse.statusCode)")
    }
}

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

Rust · reqwest

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

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let account_sid = env::var("TWILIO_ACCOUNT_SID")?;
    let phone_number_sid = env::var("TWILIO_PHONE_NUMBER_SID")?;
    let auth_token = env::var("TWILIO_AUTH_TOKEN")?;

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

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

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

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

        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($"HTTP error! status: {response.StatusCode}");
        }
    }
}

Translation notes

  • All implementations use environment variables for sensitive data (TWILIO_ACCOUNT_SID, TWILIO_PHONE_NUMBER_SID, TWILIO_AUTH_TOKEN).
  • Basic auth is implemented via the standard library mechanisms in each language.
  • Error handling checks for non-success HTTP status codes.
  • The original cURL command had an empty body, so all implementations omit a request body.
  • Python implementations use requests and httpx, the two most common HTTP libraries.

Common pitfalls when porting

  • Forgetting to set environment variables before running the code will cause runtime errors.
  • In Go, forgetting to close the response body can lead to resource leaks.
  • In Swift, the URLSession task must be started with `resume()` and the run loop must be kept alive for the request to complete.
  • In Rust, using `reqwest::blocking` is synchronous; for async, use `reqwest` with `tokio` or `async-std`.
  • In PHP, `file_get_contents` with stream context does not throw exceptions by default; check `$http_response_header`.

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 is the body empty in the cURL command but the JSON body is mentioned in the rules?

The original cURL command had `--data ""` which sends an empty body. The rules mention JSON bodies for cases where the body is non-empty, but this specific command has no body.

Can I use bearer token instead of basic auth for Twilio?

Twilio's API uses Basic Auth with Account SID as username and Auth Token as password. Bearer tokens are not supported for this endpoint.

How do I handle pagination or large responses in these examples?

These examples focus on the basic request. For pagination or large responses, you would need to implement additional logic to handle the response data or stream it.