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

print(response.json())

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

    print(response.json())

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 messageSid = process.env.TWILIO_MESSAGE_SID;

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

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

fetch(url, {
  method: 'DELETE',
  headers: {
    'Authorization': `Basic ${credentials}`
  }
})
  .then(async response => {
    if (response.status >= 400) {
      throw new Error(`Request failed with status ${response.status}: ${await response.text()}`);
    }
    return response.json();
  })
  .then(console.log)
  .catch(console.error);

Node.js · axios

import axios from 'axios';

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

const url = `https://api.twilio.com/2010-04-01/Accounts/${accountSid}/Messages/${messageSid}.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.data}`);
    }
    console.log(response.data);
  })
  .catch(console.error);

Go · net/http

package main

import (
	"fmt"
	"io"
	"log"
	"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 {
		log.Fatal(err)
	}

	req.SetBasicAuth(accountSid, authToken)

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

	if resp.StatusCode >= 400 {
		body, _ := io.ReadAll(resp.Body)
		log.Fatalf("Request failed with status %d: %s", resp.StatusCode, string(body))
	}

	body, _ := io.ReadAll(resp.Body)
	fmt.Println(string(body))
}

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}") . "\r\n"
    ]
]);

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

if ($http_response_header[0] === 'HTTP/1.1 400' || strpos($http_response_header[0], '400') !== false) {
    throw new Exception("Request failed: " . $response);
}

print($response);

Ruby · net/http

require 'net/http'
require 'json'

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

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

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

response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http|
  http.request(req)
end

if response.code.to_i >= 400
  raise "Request failed with status #{response.code}: #{response.body}"
end

puts JSON.parse(response.body)

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, httpResponse.statusCode < 400 else {
        fatalError("Request failed with status \((response as? HTTPURLResponse)?.statusCode ?? 0)")
    }

    if let data = data, let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] {
        print(json)
    }
}

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

Rust · reqwest

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

fn main() -> Result<(), Error> {
    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 message_sid = env::var("TWILIO_MESSAGE_SID").expect("TWILIO_MESSAGE_SID must be set");

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

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

    if !response.status().is_success() {
        eprintln!("Request failed with status: {}", response.status());
        return Err(response.error_for_status().unwrap_err());
    }

    let body = response.text()?;
    println!("{}", body);
    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}");
        }

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

Translation notes

  • All implementations use environment variables for credentials (TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN, TWILIO_MESSAGE_SID)
  • Basic auth is implemented via the library's built-in auth helpers where available
  • Error handling checks status codes >= 400 and raises/throws exceptions
  • JSON responses are parsed where applicable (Python, Ruby, Swift, Rust, C#)
  • Go and PHP use raw responses due to simplicity in examples
  • Node.js examples use both fetch and axios for completeness

Common pitfalls when porting

  • Forgetting to set environment variables before running the code
  • Using incorrect environment variable names (case-sensitive in some languages)
  • Not handling HTTP errors properly (e.g., ignoring status codes)
  • Assuming the response body is always JSON (some APIs may return XML or plain text)
  • In Go, not closing the response body can lead to resource leaks
  • In PHP, using file_get_contents without proper error handling for HTTP errors

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, preventing accidental exposure of secrets in version control or logs. They also allow different configurations across environments (dev, staging, prod).

How do I set the environment variables for these examples?

For local development, use `export TWILIO_ACCOUNT_SID=your_account_sid` in your shell. For production, use your deployment platform's secret management (e.g., Kubernetes secrets, AWS Secrets Manager).

Why does the Go example use blocking HTTP client?

The example uses the blocking client for simplicity. In production Go code, you'd typically use the non-blocking `http.Client` with proper context handling for cancellation and timeouts.

Can I use bearer token auth instead of basic auth?

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