Qaynaq LABS · TOOLS

CURL → CODE · POST · BASIC

cURL → 10 languages

POST api.twilio.com · body: form · secrets replaced with env vars.

Source cURL
curl -X POST https://api.twilio.com/2010-04-01/Accounts/AC1234567890/Notifications.json \
  -u AC1234567890:your_auth_token \
  -d "Body=Hello&To=+1234567890&From=+1234567890"

Python · requests

import os
import requests

account_sid = os.environ['TWILIO_ACCOUNT_SID']
auth_token = os.environ['TWILIO_AUTH_TOKEN']

url = f"https://api.twilio.com/2010-04-01/Accounts/{account_sid}/Notifications.json"

payload = {
    'Body': 'Hello',
    'To': '+1234567890',
    'From': '+1234567890'
}

response = requests.post(url, auth=(account_sid, auth_token), data=payload)

if response.status_code >= 400:
    raise Exception(f"Request failed: {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']

url = f"https://api.twilio.com/2010-04-01/Accounts/{account_sid}/Notifications.json"

payload = {
    'Body': 'Hello',
    'To': '+1234567890',
    'From': '+1234567890'
}

with httpx.Client() as client:
    response = client.post(url, auth=(account_sid, auth_token), data=payload)

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

    print(response.json())

Node.js · fetch

import fetch from 'node-fetch';
import { Buffer } from 'buffer';

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

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

const payload = new URLSearchParams({
  Body: 'Hello',
  To: '+1234567890',
  From: '+1234567890'
});

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

fetch(url, {
  method: 'POST',
  headers: {
    'Authorization': `Basic ${credentials}`,
    'Content-Type': 'application/x-www-form-urlencoded'
  },
  body: payload
})
  .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 authToken = process.env.TWILIO_AUTH_TOKEN;

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

const payload = new URLSearchParams({
  Body: 'Hello',
  To: '+1234567890',
  From: '+1234567890'
});

axios.post(url, payload, {
  auth: {
    username: accountSid,
    password: authToken
  },
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  }
})
  .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"
	"io"
	"log"
	"net/http"
	"net/url"
	"os"
)

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

	baseURL := "https://api.twilio.com/2010-04-01/Accounts/"
	endpoint := fmt.Sprintf("%s%s/Notifications.json", baseURL, accountSid)

	formData := url.Values{}
	formData.Set("Body", "Hello")
	formData.Set("To", "+1234567890")
	formData.Set("From", "+1234567890")

	req, err := http.NewRequest("POST", endpoint, 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 >= 400 {
		body, _ := io.ReadAll(resp.Body)
		log.Fatalf("Request failed: %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');

$url = "https://api.twilio.com/2010-04-01/Accounts/{$accountSid}/Notifications.json";

$data = [
    'Body' => 'Hello',
    'To' => '+1234567890',
    'From' => '+1234567890'
];

$options = [
    'http' => [
        'header' => "Authorization: Basic " . base64_encode("{$accountSid}:{$authToken}") . "\r\n",
        'method' => 'POST',
        'content' => http_build_query($data)
    ]
];

$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);

if ($http_response_header[0] === 'HTTP/1.1 200 OK') {
    echo $result;
} else {
    throw new Exception("Request failed: " . $http_response_header[0]);
}

Ruby · net/http

require 'net/http'
require 'uri'
require 'cgi'

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}/Notifications.json")

form_data = {
  'Body' => 'Hello',
  'To' => '+1234567890',
  'From' => '+1234567890'
}

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(form_data)

response = http.request(request)

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

puts response.body

Swift · URLSession

import Foundation

guard let accountSid = ProcessInfo.processInfo.environment["TWILIO_ACCOUNT_SID"],
      let authToken = ProcessInfo.processInfo.environment["TWILIO_AUTH_TOKEN"] else {
    fatalError("Missing environment variables TWILIO_ACCOUNT_SID or TWILIO_AUTH_TOKEN")
}

let urlString = "https://api.twilio.com/2010-04-01/Accounts/" + accountSid + "/Notifications.json"
let url = URL(string: urlString)!

var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")

let bodyString = "Body=Hello&To=+1234567890&From=+1234567890"
request.httpBody = bodyString.data(using: .utf8)

let credentials = "\(accountSid):\(authToken)".data(using: .utf8)!.base64EncodedString()
request.setValue("Basic \(credentials)", 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) as? [String: Any] {
        print(json)
    }
}

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

Rust · reqwest

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 url = format!(
        "https://api.twilio.com/2010-04-01/Accounts/{}/Notifications.json",
        account_sid
    );

    let mut form_data = HashMap::new();
    form_data.insert("Body", "Hello");
    form_data.insert("To", "+1234567890");
    form_data.insert("From", "+1234567890");

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

    if !response.status().is_success() {
        let body = response.text()?;
        return Err(format!("Request failed: {} - {}", response.status(), body).into());
    }

    let json: serde_json::Value = response.json()?;
    println!("{}", json);

    Ok(())
}

C# · HttpClient

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

        var url = $"https://api.twilio.com/2010-04-01/Accounts/{accountSid}/Notifications.json";

        var formData = new Dictionary<string, string>
        {
            {"Body", "Hello"},
            {"To", "+1234567890"},
            {"From", "+1234567890"}
        };

        using var client = new HttpClient();
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
            "Basic",
            Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes($"{accountSid}:{authToken}"))
        );

        var response = await client.PostAsync(url, new FormUrlEncodedContent(formData));

        if (!response.IsSuccessStatusCode)
        {
            var errorContent = await response.Content.ReadAsStringAsync();
            throw new Exception($"Request failed: {response.StatusCode} - {errorContent}");
        }

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

Translation notes

  • Basic auth is used with Twilio's Account SID as username and Auth Token as password
  • Form data is sent as application/x-www-form-urlencoded
  • Environment variables are used for sensitive credentials
  • Error handling checks for non-2xx status codes
  • All implementations preserve the exact same request semantics as the cURL command

Common pitfalls when porting

  • Forgetting to set the Content-Type header to application/x-www-form-urlencoded when using raw HTTP clients
  • Not properly encoding the form data in languages that don't automatically handle it
  • Mixing up the order of username/password in basic auth (Twilio uses Account SID as username)
  • Not handling SSL/TLS properly in languages that require explicit configuration
  • Assuming JSON responses without checking the Content-Type header

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 is Basic Auth used instead of Bearer Token?

Twilio's API uses HTTP Basic Auth with the Account SID as username and Auth Token as password. This is their standard authentication method for the API.

Can I use JSON instead of form data?

Twilio's Notifications API specifically requires form-encoded data for this endpoint. JSON would not work here.

What if I need to send more parameters?

Add them to the form data dictionary/object in the same way as the existing parameters.

How do I handle pagination?

Twilio's API uses query parameters like PageSize and Page for pagination. Add them to the URL or query parameters as needed.