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}/Calls.json",
auth=(account_sid, auth_token),
data={
"To": "+1234567890",
"From": "+1234567890",
"Url": "https://handler.twilio.com/twiml/EHf3b1234567890"
}
)
response.raise_for_status()
print(response.json())
import os
import httpx
account_sid = os.environ["TWILIO_ACCOUNT_SID"]
auth_token = os.environ["TWILIO_AUTH_TOKEN"]
async def make_call():
async with httpx.AsyncClient() as client:
response = await client.post(
f"https://api.twilio.com/2010-04-01/Accounts/{account_sid}/Calls.json",
auth=(account_sid, auth_token),
data={
"To": "+1234567890",
"From": "+1234567890",
"Url": "https://handler.twilio.com/twiml/EHf3b1234567890"
}
)
response.raise_for_status()
return response.json()
# For synchronous usage:
# with httpx.Client() as client:
# response = client.post(...)
# response.raise_for_status()
# print(response.json())
import 'dotenv/config';
import fetch from 'node-fetch';
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}/Calls.json`,
{
method: 'POST',
headers: {
'Authorization': 'Basic ' + Buffer.from(`${accountSid}:${authToken}`).toString('base64')
},
body: new URLSearchParams({
To: '+1234567890',
From: '+1234567890',
Url: 'https://handler.twilio.com/twiml/EHf3b1234567890'
})
}
);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
console.log(data);
import 'dotenv/config';
import axios from 'axios';
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}/Calls.json`,
new URLSearchParams({
To: '+1234567890',
From: '+1234567890',
Url: 'https://handler.twilio.com/twiml/EHf3b1234567890'
}),
{
auth: {
username: accountSid,
password: authToken
}
}
);
console.log(response.data);
} catch (error) {
if (error.response) {
console.error('Error:', error.response.status, error.response.data);
} else {
console.error('Error:', error.message);
}
}
package main
import (
"fmt"
"log"
"net/http"
"net/url"
"os"
)
func main() {
accountSid := os.Getenv("TWILIO_ACCOUNT_SID")
authToken := os.Getenv("TWILIO_AUTH_TOKEN")
formData := url.Values{}
formData.Add("To", "+1234567890")
formData.Add("From", "+1234567890")
formData.Add("Url", "https://handler.twilio.com/twiml/EHf3b1234567890")
req, err := http.NewRequest(
"POST",
fmt.Sprintf("https://api.twilio.com/2010-04-01/Accounts/%s/Calls.json", accountSid),
strings.NewReader(formData.Encode()),
)
if err != nil {
log.Fatal(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 {
log.Fatal(err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
log.Fatalf("unexpected status code: %d", resp.StatusCode)
}
// Process response body as needed
}
<?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}/Calls.json");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
'To' => '+1234567890',
'From' => '+1234567890',
'Url' => 'https://handler.twilio.com/twiml/EHf3b1234567890'
]));
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 !== 200) {
throw new Exception("HTTP error: {$httpCode}");
}
$data = json_decode($response, true);
print_r($data);
require 'net/http'
require 'uri'
require 'json'
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}/Calls.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' => '+1234567890',
'Url' => 'https://handler.twilio.com/twiml/EHf3b1234567890'
})
response = http.request(request)
unless response.is_a?(Net::HTTPSuccess)
raise "HTTP error: #{response.code}"
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 url = URL(string: "https://api.twilio.com/2010-04-01/Accounts/" + accountSid + "/Calls.json")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
let bodyString = "To=+1234567890&From=+1234567890&Url=https://handler.twilio.com/twiml/EHf3b1234567890"
request.httpBody = bodyString.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 {
print("Error: \(error)")
return
}
guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else {
print("HTTP error")
return
}
if let data = data, let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] {
print(json)
}
}
task.resume()
// For synchronous execution in a playground or test:
// let (data, response) = try await URLSession.shared.data(for: request)
// guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else { throw URLError(.badServerResponse) }
// let json = try JSONSerialization.jsonObject(with: data) as? [String: Any]
// print(json)
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 params = HashMap::new();
params.insert("To", "+1234567890");
params.insert("From", "+1234567890");
params.insert("Url", "https://handler.twilio.com/twiml/EHf3b1234567890");
let response: Response = client
.post(&format!("https://api.twilio.com/2010-04-01/Accounts/{}/Calls.json", account_sid))
.basic_auth(&account_sid, Some(&auth_token))
.form(¶ms)
.send()?;
if !response.status().is_success() {
return Err(format!("HTTP error: {}", response.status()).into());
}
let body = response.json::<serde_json::Value>()?;
println!("{:?}", body);
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 request = new HttpRequestMessage(HttpMethod.Post,
$"https://api.twilio.com/2010-04-01/Accounts/{accountSid}/Calls.json");
request.Headers.Authorization = new AuthenticationHeaderValue(
"Basic", Convert.ToBase64String(
System.Text.Encoding.ASCII.GetBytes($"{accountSid}:{authToken}")));
var formData = new Dictionary<string, string>
{
{"To", "+1234567890"},
{"From", "+1234567890"},
{"Url", "https://handler.twilio.com/twiml/EHf3b1234567890"}
};
request.Content = new FormUrlEncodedContent(formData);
var response = await client.SendAsync(request);
response.EnsureSuccessStatusCode();
var responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
}