Skip to content

Twilio Setup: Account Configuration and SDK Installation

DodaTech Updated 2026-06-28 5 min read

In this tutorial, you will learn about Twilio Setup: Account Configuration and SDK Installation. We cover key concepts, practical examples, and best practices to help you master this topic.

Setting up Twilio requires creating an account, obtaining API credentials, purchasing a phone number, installing the Twilio SDK, and configuring environment variables for secure credential management.

What You'll Learn

How to create a Twilio account, find your Account SID and Auth Token, buy a phone number, install the Twilio Python and Node.js SDKs, configure environment variables, and verify your setup with a test API call.

Why It Matters

Proper setup prevents security leaks, ensures reliable API connections, and establishes a foundation for all Twilio integrations. DodaTech follows strict credential management practices across all environments.

Real-World Use

A developer joins the DodaTech team. They follow the setup guide, create API keys with restricted permissions, configure environment variables, and run the verification script before writing any communication features.

flowchart LR
    A["Create\nTwilio Account"] --> B["Get Account SID\nand Auth Token"]
    B --> C["Buy Phone\nNumber"]
    C --> D["Install Twilio\nSDK"]
    D --> E["Configure\nEnvironment Vars"]
    E --> F["Run Verification\nScript"]
    F --> G{"API\nWorks?"}
    G -->|Yes| H["Ready to\nDevelop"]
    G -->|No| I["Troubleshoot\nCredentials"]
    style A fill:#f22f46,color:#fff
    style D fill:#dbeafe,stroke:#2563eb
    style H fill:#bbf7d0,stroke:#16a34a

Creating Account and Getting Credentials

# 1. Sign up at twilio.com (free trial with $15 credit)
# 2. Verify your personal phone number
# 3. Find credentials in Console Dashboard

# Your Account SID and Auth Token
account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"  # Replace with yours
auth_token = "your_auth_token_here"                  # Replace with yours

print(f"Account SID: {account_sid[:6]}...{account_sid[-4:]}")
print(f"Auth Token: {'*' * 8}{auth_token[-4:]}")
# Expected output:
# Account SID: ACXXX...XXXX
# Auth Token: ********oken

Installing the Twilio SDK

# Python SDK
pip install twilio

# Node.js SDK
npm install twilio

# Verify installation
python3 -c "import twilio; print(f'Twilio SDK v{twilio.__version__}')"
# Expected output:
# Twilio SDK v9.2.0

Buying a Phone Number

from twilio.rest import Client

client = Client(account_sid, auth_token)

# Search for available numbers
available = client.available_phone_numbers("US").local.list(
    area_code=415,
    limit=5
)
print(f"Found {len(available)} numbers in 415 area code")
for num in available:
    print(f"  {num.phone_number}")

# Buy the first number
if available:
    purchased = client.incoming_phone_numbers.create(
        phone_number=available[0].phone_number,
        voice_url="https://example.com/voice",
        sms_url="https://example.com/sms"
    )
    print(f"\nPurchased: {purchanced.phone_number}")
    print(f"SID: {purchased.sid}")

# Expected output:
# Found 3 numbers in 415 area code
#   +14155551234
#   +14155555678
#   +14155559012
#
# Purchased: +14155551234
# SID: PNxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

Configuring Environment Variables

# .env file (never commit this)
"""
TWILIO_ACCOUNT_SID=ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
TWILIO_AUTH_TOKEN=your_auth_token_here
TWILIO_PHONE_NUMBER=+14155551234
"""

# Load and validate
import os
from dotenv import load_dotenv

load_dotenv()

required_vars = [
    "TWILIO_ACCOUNT_SID",
    "TWILIO_AUTH_TOKEN",
    "TWILIO_PHONE_NUMBER"
]

missing = [v for v in required_vars if not os.getenv(v)]
if missing:
    raise EnvironmentError(f"Missing: {', '.join(missing)}")

print("All environment variables configured")
print(f"Account SID: {os.getenv('TWILIO_ACCOUNT_SID')[:6]}...")
print(f"Phone: {os.getenv('TWILIO_PHONE_NUMBER')}")
# Expected output:
# All environment variables configured
# Account SID: ACXXX...
# Phone: +14155551234

Verification Script

from twilio.rest import Client
import os

def verify_twilio_setup():
    account_sid = os.environ["TWILIO_ACCOUNT_SID"]
    auth_token = os.environ["TWILIO_AUTH_TOKEN"]
    from_number = os.environ["TWILIO_PHONE_NUMBER"]
    to_number = os.environ.get("MY_PHONE_NUMBER")  # Your verified number

    client = Client(account_sid, auth_token)

    # 1. Verify account
    account = client.api.accounts(account_sid).fetch()
    print(f"Account: {account.friendly_name}")
    print(f"Status: {account.status}")

    # 2. List owned numbers
    numbers = client.incoming_phone_numbers.list()
    print(f"Owned numbers: {len(numbers)}")
    for num in numbers:
        print(f"  {num.phone_number} (SMS: {num.sms_url or 'not set'})")

    # 3. Send test message
    if to_number:
        message = client.messages.create(
            body="Twilio setup verification successful!",
            from_=from_number,
            to=to_number
        )
        print(f"\nTest message sent: {message.sid}")
        print(f"Status: {message.status}")

verify_twilio_setup()
# Expected output:
# Account: My Twilio Account
# Status: active
# Owned numbers: 1
#   +14155551234 (SMS: not set)
#
# Test message sent: SMxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
# Status: queued

Common Mistakes

1. Committing Auth Tokens to Git

Auth Tokens grant full API access. Anyone with your token can send messages on your account. Always use environment variables and add .env to .gitignore.

2. Buying Numbers Without a Use Case

Phone numbers cost $1-2/month plus usage fees. Buy only what you need. You can release unused numbers to avoid charges.

3. Using Main Account Credentials in Development

Use API keys with restricted permissions for development and separate keys for production. Create subaccounts for environment isolation.

4. Forgetting the + in Phone Numbers

Twilio requires phone numbers in E.164 format with a leading + and country code. +14155551234 is correct. 4155551234 will fail.

5. Not Selecting a Messaging Service

For production SMS sending, create a Messaging Service instead of using a single phone number. It provides failover, A2P 10DLC Compliance, and geographic routing.

Practice Questions

  1. What three credentials do you need to start using Twilio?
  2. Why should you use environment variables for credentials?
  3. What format must phone numbers be in for Twilio?
  4. How do you verify your Twilio setup is working?

Answers:

  1. Account SID (starts with AC), Auth Token, and a Twilio phone number (purchased or trial number).
  2. Environment variables prevent accidental credential exposure in version control, enable per-environment configuration, and follow security best practices.
  3. E.164 format: a leading +, country code, and phone number. Example: +14155551234 for a US number.
  4. Create a verification script that fetches your account details, lists owned numbers, and sends a test message to a verified number.

Challenge: Complete the full setup: create a Twilio account, purchase a phone number, install the Python SDK, configure environment variables, create the verification script, run it successfully, and then create a restricted API key for development purposes.

FAQ

What is the difference between Account SID and Auth Token?

Account SID identifies your account publicly. Auth Token is the secret key to authenticate API requests. The Auth Token must be kept confidential, while SID appears in logs and URLs.

Can I use Twilio without buying a phone number?

Yes, but with limitations. Trial accounts can send messages to verified numbers only. For production, you need a purchased number to send to unverified recipients.

How do I create API keys for development vs production?

In Console > API Keys, create separate keys for dev and prod. Restrict dev keys by IP address. Rotate keys every 90 days.

What is a subaccount and when should I use one?

Subaccounts isolate usage, billing, and configuration per environment or team. Use them to separate dev, staging, and production environments.

How long does it take to buy a phone number?

Number purchase is instant after account verification. Porting existing numbers takes 5-10 business days.

Mini Project

Complete the full setup as described in the challenge. Document your Account SID (masked), phone number, and verification script output. Create a .env.example file with placeholder values for team onboarding.

What's Next

Send SMS — send your first SMS message with the Twilio API.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro