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/Applications/AP12345678.json \
  -H "Authorization: Basic YWN0aXZlOnNlY3JldA=="

Python · requests

import os
import requests

account_sid = os.environ['TWILIO_ACCOUNT_SID']
application_sid = os.environ['TWILIO_APPLICATION_SID']
auth = (account_sid, os.environ['TWILIO_AUTH_TOKEN'])

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

if response.status_code >= 400:
    raise Exception(f"Request failed: {response.status_code} {response.text}")

Python · httpx

import os
import httpx

account_sid = os.environ['TWILIO_ACCOUNT_SID']
application_sid = os.environ['TWILIO_APPLICATION_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}/Applications/{application_sid}.json',
        auth=auth
    )

if response.status_code >= 400:
    raise Exception(f"Request failed: {response.status_code} {response.text}")

Node.js · fetch

import fetch from 'node-fetch';

const accountSid = process.env.TWILIO_ACCOUNT_SID;
const applicationSid = process.env.TWILIO_APPLICATION_SID;
const authToken = process.env.TWILIO_AUTH_TOKEN;

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

fetch(url, {
    method: 'DELETE',
    headers: {
        'Authorization': 'Basic ' + Buffer.from(`${accountSid}:${authToken}`).toString('base64')
    }
})
.then(response => {
    if (!response.ok) {
        throw new Error(`Request failed: ${response.status} ${response.statusText}`);
    }
    return response.json();
})
.then(data => console.log(data))
.catch(error => console.error(error));

Node.js · axios

import axios from 'axios';

const accountSid = process.env.TWILIO_ACCOUNT_SID;
const applicationSid = process.env.TWILIO_APPLICATION_SID;
const authToken = process.env.TWILIO_AUTH_TOKEN;

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

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

Go · net/http

package main

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

func main() {
	accountSid := os.Getenv("TWILIO_ACCOUNT_SID")
	applicationSid := os.Getenv("TWILIO_APPLICATION_SID")
	authToken := os.Getenv("TWILIO_AUTH_TOKEN")

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

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

PHP · cURL

<?php

$accountSid = getenv('TWILIO_ACCOUNT_SID');
$applicationSid = getenv('TWILIO_APPLICATION_SID');
$authToken = getenv('TWILIO_AUTH_TOKEN');

$url = "https://api.twilio.com/2010-04-01/Accounts/{$accountSid}/Applications/{$applicationSid}.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') {
    echo $response;
} else {
    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']
application_sid = ENV['TWILIO_APPLICATION_SID']
auth_token = ENV['TWILIO_AUTH_TOKEN']

uri = URI.parse("https://api.twilio.com/2010-04-01/Accounts/#{account_sid}/Applications/#{application_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: #{response.code} #{response.message}"
end

Swift · URLSession

import Foundation

let accountSid = ProcessInfo.processInfo.environment["TWILIO_ACCOUNT_SID"] ?? ""
let applicationSid = ProcessInfo.processInfo.environment["TWILIO_APPLICATION_SID"] ?? ""
let authToken = ProcessInfo.processInfo.environment["TWILIO_AUTH_TOKEN"] ?? ""

let urlString = "https://api.twilio.com/2010-04-01/Accounts/" + accountSid + "/Applications/" + applicationSid + ".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, httpResponse.statusCode < 400 else {
        fatalError("Request failed: \((response as? HTTPURLResponse)?.statusCode ?? 0)")
    }
    if let data = data, let json = try? JSONSerialization.jsonObject(with: data) {
        print(json)
    }
}
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 application_sid = env::var("TWILIO_APPLICATION_SID")?;
    let auth_token = env::var("TWILIO_AUTH_TOKEN")?;

    let url = format!(
        "https://api.twilio.com/2010-04-01/Accounts/{}/Applications/{}.json",
        account_sid, application_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!("Request failed: {}", response.status()).into());
    }

    let _ = response.json::<serde_json::Value>()?;
    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 applicationSid = Environment.GetEnvironmentVariable("TWILIO_APPLICATION_SID");
        var authToken = Environment.GetEnvironmentVariable("TWILIO_AUTH_TOKEN");

        var url = $"https://api.twilio.com/2010-04-01/Accounts/{accountSid}/Applications/{applicationSid}.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: {(int)response.StatusCode} {response.ReasonPhrase}");
        }

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

Translation notes

  • Basic auth is implemented via the library's built-in auth helpers where available
  • Environment variables are used for credentials to avoid hardcoding secrets
  • Error handling checks HTTP status codes >= 400 as failures
  • All implementations use HTTPS and follow redirects by default
  • JSON response bodies are parsed where applicable (e.g., Swift, Rust)
  • Python implementations use both requests and httpx for completeness

Common pitfalls when porting

  • Forgetting to set environment variables before running the code
  • Using incorrect environment variable names (e.g., TWILIO_API_KEY instead of TWILIO_AUTH_TOKEN)
  • Not handling HTTPS properly in languages where it's not default (e.g., Go without http.Client{})
  • Assuming the response body is always JSON (some APIs may return XML or plain text)
  • Ignoring SSL certificate validation in production (not shown here for simplicity)

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 credentials per environment (dev, staging, prod).

Can I use bearer token auth instead of basic auth?

Twilio's API primarily uses Basic Auth with Account SID and Auth Token. Bearer tokens are not standard for this API, but you could wrap the Basic Auth in a Bearer token if required by a proxy or gateway.

How do I handle pagination or rate limits?

Twilio's API uses standard HTTP headers like 'X-Total-Count' and 'Link' for pagination. Rate limits are indicated by 'Retry-After' headers. These are not shown in the example but should be handled in production code.

Why does the Go example use blocking HTTP client?

The Go example uses the blocking client for simplicity. In production, you'd typically use the async client (http.Client with context) or a library like 'github.com/go-resty/resty' for better ergonomics.