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())
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())
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);
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);
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
$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);
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)
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()
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(())
}
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);
}
}