import os
import requests
account_sid = os.environ['TWILIO_ACCOUNT_SID']
auth_token = os.environ['TWILIO_AUTH_TOKEN']
response = requests.post(
f"https://api.twilio.com/2010-04-01/Accounts/{account_sid}/Call.json",
auth=(account_sid, auth_token),
data={
"To": "+1234567890",
"From": "+1987654321",
"Url": "https://example.com/twiml"
}
)
if response.status_code >= 400:
raise Exception(f"Request failed: {response.text}")
print(response.json())
import os
import httpx
account_sid = os.environ['TWILIO_ACCOUNT_SID']
auth_token = os.environ['TWILIO_AUTH_TOKEN']
with httpx.Client() as client:
response = client.post(
f"https://api.twilio.com/2010-04-01/Accounts/{account_sid}/Call.json",
auth=(account_sid, auth_token),
data={
"To": "+1234567890",
"From": "+1987654321",
"Url": "https://example.com/twiml"
}
)
if response.status_code >= 400:
raise Exception(f"Request failed: {response.text}")
print(response.json())
import fetch from 'node-fetch';
import * as process from 'process';
const accountSid = process.env.TWILIO_ACCOUNT_SID;
const authToken = process.env.TWILIO_AUTH_TOKEN;
const response = await fetch(
`https://api.twilio.com/2010-04-01/Accounts/${accountSid}/Call.json`,
{
method: 'POST',
headers: {
'Authorization': 'Basic ' + Buffer.from(`${accountSid}:${authToken}`).toString('base64')
},
body: new URLSearchParams({
To: '+1234567890',
From: '+1987654321',
Url: 'https://example.com/twiml'
})
}
);
if (!response.ok) {
throw new Error(`Request failed: ${await response.text()}`);
}
console.log(await response.json());
import axios from 'axios';
import * as process from 'process';
const accountSid = process.env.TWILIO_ACCOUNT_SID;
const authToken = process.env.TWILIO_AUTH_TOKEN;
try {
const response = await axios.post(
`https://api.twilio.com/2010-04-01/Accounts/${accountSid}/Call.json`,
new URLSearchParams({
To: '+1234567890',
From: '+1987654321',
Url: 'https://example.com/twiml'
}),
{
auth: {
username: accountSid,
password: authToken
}
}
);
if (response.status >= 400) {
throw new Error(`Request failed: ${response.statusText}`);
}
console.log(response.data);
} catch (error) {
console.error(error.message);
}
package main
import (
"encoding/base64"
"fmt"
"io"
"net/http"
"net/url"
"os"
)
func main() {
accountSid := os.Getenv("TWILIO_ACCOUNT_SID")
authToken := os.Getenv("TWILIO_AUTH_TOKEN")
formData := url.Values{}
formData.Set("To", "+1234567890")
formData.Set("From", "+1987654321")
formData.Set("Url", "https://example.com/twiml")
req, err := http.NewRequest(
"POST",
fmt.Sprintf("https://api.twilio.com/2010-04-01/Accounts/%s/Call.json", accountSid),
strings.NewReader(formData.Encode()),
)
if err != nil {
panic(err)
}
req.SetBasicAuth(accountSid, authToken)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
if resp.StatusCode >= 400 {
body, _ := io.ReadAll(resp.Body)
panic(fmt.Sprintf("Request failed: %s", string(body)))
}
body, _ := io.ReadAll(resp.Body)
fmt.Println(string(body))
}
<?php
$accountSid = getenv('TWILIO_ACCOUNT_SID');
$authToken = getenv('TWILIO_AUTH_TOKEN');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.twilio.com/2010-04-01/Accounts/{$accountSid}/Call.json");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
'To' => '+1234567890',
'From' => '+1987654321',
'Url' => 'https://example.com/twiml'
]));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, "{$accountSid}:{$authToken}");
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode >= 400) {
throw new Exception("Request failed: " . $response);
}
echo $response;
require 'net/http'
require 'uri'
require 'base64'
account_sid = ENV['TWILIO_ACCOUNT_SID']
auth_token = ENV['TWILIO_AUTH_TOKEN']
uri = URI.parse("https://api.twilio.com/2010-04-01/Accounts/#{account_sid}/Call.json")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
request = Net::HTTP::Post.new(uri.request_uri)
request.basic_auth(account_sid, auth_token)
request.set_form_data({
'To' => '+1234567890',
'From' => '+1987654321',
'Url' => 'https://example.com/twiml'
})
response = http.request(request)
if response.code.to_i >= 400
raise "Request failed: #{response.body}"
end
puts response.body
import Foundation
let accountSid = ProcessInfo.processInfo.environment["TWILIO_ACCOUNT_SID"] ?? ""
let authToken = ProcessInfo.processInfo.environment["TWILIO_AUTH_TOKEN"] ?? ""
let url = URL(string: "https://api.twilio.com/2010-04-01/Accounts/" + accountSid + "/Call.json")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
let body = "To=+1234567890&From=+1987654321&Url=https://example.com/twiml"
request.httpBody = body.data(using: .utf8)
let authString = "\(accountSid):\(authToken)"
let authData = authString.data(using: .utf8)?.base64EncodedString()
request.setValue("Basic \(authData ?? "")", 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) {
print(json)
}
}
task.resume()
RunLoop.main.run()
use std::collections::HashMap;
use std::env;
use reqwest::blocking::Client;
use reqwest::blocking::Response;
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 client = Client::new();
let mut form = HashMap::new();
form.insert("To", "+1234567890");
form.insert("From", "+1987654321");
form.insert("Url", "https://example.com/twiml");
let response: Response = client
.post(&format!("https://api.twilio.com/2010-04-01/Accounts/{}/Call.json", account_sid))
.basic_auth(account_sid, Some(auth_token))
.form(&form)
.send()?;
if !response.status().is_success() {
return Err(format!("Request failed: {}", response.text()?).into());
}
println!("{:?}", response.json::<serde_json::Value>()?);
Ok(())
}
using System;
using System.Collections.Generic;
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");
using var client = new HttpClient();
var formData = new Dictionary<string, string>
{
{"To", "+1234567890"},
{"From", "+1987654321"},
{"Url", "https://example.com/twiml"}
};
var content = new FormUrlEncodedContent(formData);
var request = new HttpRequestMessage(HttpMethod.Post,
$"https://api.twilio.com/2010-04-01/Accounts/{accountSid}/Call.json")
{
Content = content
};
request.Headers.Authorization = new AuthenticationHeaderValue(
"Basic", Convert.ToBase64String(
System.Text.Encoding.ASCII.GetBytes($"{accountSid}:{authToken}")));
var response = await client.SendAsync(request);
if (!response.IsSuccessStatusCode)
{
throw new Exception($"Request failed: {await response.Content.ReadAsStringAsync()}");
}
var responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
}