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/Messages/SM1234567890.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']
message_sid = os.environ['TWILIO_MESSAGE_SID']

url = f"https://api.twilio.com/2010-04-01/Accounts/{account_sid}/Messages/{message_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']
message_sid = os.environ['TWILIO_MESSAGE_SID']

url = f"https://api.twilio.com/2010-04-01/Accounts/{account_sid}/Messages/{message_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 { env } from 'process';

const accountSid = env.TWILIO_ACCOUNT_SID;
const authToken = env.TWILIO_AUTH_TOKEN;
const messageSid = env.TWILIO_MESSAGE_SID;

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

const response = await fetch(url, {
  method: 'DELETE',
  headers: {
    'Authorization': 'Basic ' + Buffer.from(`${accountSid}:${authToken}`).toString('base64')
  }
});

if (response.status >= 400) {
  throw new Error(`Request failed with status ${response.status}: ${await response.text()}`);
}

Node.js · axios

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

const accountSid = env.TWILIO_ACCOUNT_SID;
const authToken = env.TWILIO_AUTH_TOKEN;
const messageSid = env.TWILIO_MESSAGE_SID;

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

try {
  const response = await axios.delete(url, {
    auth: {
      username: accountSid,
      password: authToken
    }
  });
  
  if (response.status >= 400) {
    throw new Error(`Request failed with status ${response.status}: ${response.data}`);
  }
} catch (error) {
  if (error.response) {
    throw new Error(`Request failed with status ${error.response.status}: ${error.response.data}`);
  }
  throw error;
}

Go · net/http

package main

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

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

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

	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("Request failed with status %d: %s", resp.StatusCode, resp.Status))
	}
}

PHP · cURL

<?php

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

$url = "https://api.twilio.com/2010-04-01/Accounts/{$accountSid}/Messages/{$messageSid}.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("Request failed: " . $http_response_header[0]);
}

Ruby · net/http

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

account_sid = ENV['TWILIO_ACCOUNT_SID']
auth_token = ENV['TWILIO_AUTH_TOKEN']
message_sid = ENV['TWILIO_MESSAGE_SID']

uri = URI.parse("https://api.twilio.com/2010-04-01/Accounts/#{account_sid}/Messages/#{message_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 "Request failed with status #{response.code}: #{response.body}"
end

Swift · URLSession

import Foundation

let accountSid = ProcessInfo.processInfo.environment["TWILIO_ACCOUNT_SID"] ?? ""
let authToken = ProcessInfo.processInfo.environment["TWILIO_AUTH_TOKEN"] ?? ""
let messageSid = ProcessInfo.processInfo.environment["TWILIO_MESSAGE_SID"] ?? ""

let url = URL(string: "https://api.twilio.com/2010-04-01/Accounts/" + accountSid + "/Messages/" + messageSid + ".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("Request failed: \(error)")
    }
    guard let httpResponse = response as? HTTPURLResponse else {
        fatalError("Invalid response")
    }
    if httpResponse.statusCode >= 400 {
        fatalError("Request failed with status \(httpResponse.statusCode)")
    }
}

task.resume()
sleep(1)

Rust · reqwest

use std::env;
use reqwest;

#[tokio::main]
async 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 message_sid = env::var("TWILIO_MESSAGE_SID")?;

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

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

    if !response.status().is_success() {
        let status = response.status();
        let body = response.text().await?;
        return Err(format!("Request failed with status {}: {}", status, body).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 authToken = Environment.GetEnvironmentVariable("TWILIO_AUTH_TOKEN");
        var messageSid = Environment.GetEnvironmentVariable("TWILIO_MESSAGE_SID");

        var url = $"https://api.twilio.com/2010-04-01/Accounts/{accountSid}/Messages/{messageSid}.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 content = await response.Content.ReadAsStringAsync();
            throw new Exception($"Request failed with status {response.StatusCode}: {content}");
        }
    }
}

Translation notes

  • All implementations use environment variables for credentials (TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN, TWILIO_MESSAGE_SID)
  • Basic auth is handled via library-specific mechanisms (auth parameter, headers, or built-in methods)
  • Error handling checks status codes >= 400 and raises/throws exceptions
  • URLs are constructed with environment variable placeholders for portability

Common pitfalls when porting

  • Forgetting to set environment variables before running the code
  • Not handling async/await properly in languages that require it (e.g., Swift, Rust, Go)
  • Incorrectly encoding credentials in Basic auth (e.g., missing base64 encoding in PHP)
  • Ignoring SSL/TLS verification (not shown here but important in production)
  • Assuming synchronous HTTP clients are always available (e.g., Python's requests vs httpx)

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, reducing the risk of credential leaks in version control. They also allow different configurations across environments (dev, staging, prod).

How do I handle pagination or rate limits in the response?

The basic implementation does not include pagination or rate limit handling. You would need to inspect response headers (e.g., Link header for pagination) or implement retry logic with exponential backoff for rate limits.

Can I use OAuth or API keys instead of Basic Auth?

Twilio primarily uses Basic Auth for API access. If you need OAuth or API keys, you would need to use a different authentication method and adjust the headers accordingly.