TwiML Rust
A comprehensive, type-safe Rust library for generating TwiML (Twilio Markup Language) XML responses for Voice, Messaging, and Fax applications.
TwiML is Twilio's XML-based language for controlling phone calls, SMS/MMS messages, and faxes. This library provides an idiomatic Rust API with strong type safety, builder patterns, and zero external dependencies.
Features
- Comprehensive Voice Support: All TwiML voice verbs including Say, Play, Dial, Gather, Record, Connect, Enqueue, Pay, and more
- Messaging (SMS/MMS): Full support for text and multimedia messages with multiple media attachments
- Fax Operations: Configure fax reception with PDF/TIFF formats and custom page sizes
- Built-in Validation: Validate TwiML structure, URLs, phone numbers, and content lengths
- Type Safety: Strongly typed API with builder patterns for compile-time correctness
- Zero Dependencies: No external dependencies for maximum compatibility and minimal footprint
- Full SSML Support: Advanced speech synthesis with break, emphasis, prosody, phonemes, and more
- Security: Automatic XML escaping to prevent injection attacks
- Well Documented: Comprehensive documentation with examples for every feature
- Thoroughly Tested: 167+ tests ensuring reliability and correctness
Installation
Add this to your Cargo.toml:
[]
= "0.1.0"
Minimum Supported Rust Version (MSRV): 1.70
Quick Start
Simple Voice Call
use ;
Output:
Hello! Welcome to TwiML Rust.
https://example.com/music.mp3
Simple SMS Message
use ;
Output:
Thanks for your message! We'll get back to you soon.
Comprehensive Examples
Interactive Voice Response (IVR)
Build sophisticated phone menus with DTMF and speech recognition:
use ;
Call Forwarding with Dial
Forward calls to phone numbers, SIP addresses, or Twilio clients:
use ;
Voice Recording (Voicemail)
Record caller messages with transcription:
use ;
MMS with Multiple Media Attachments
Send multimedia messages with images, videos, or other media:
use ;
Advanced SSML (Speech Synthesis)
Use SSML for fine-grained control over speech synthesis:
use ;
Conference Calls
Create and manage conference calls:
use ;
Fax Reception
Configure fax reception with custom settings:
use ;
Complete TwiML Verb Reference
Voice Verbs
The library supports all TwiML voice verbs with comprehensive attribute support:
| Verb | Description | Key Features |
|---|---|---|
<Say> |
Text-to-speech | Multiple voices, languages, SSML support, looping |
<Play> |
Play audio files | MP3/WAV support, looping, DTMF digit playback |
<Dial> |
Make outbound calls | Numbers, SIP, clients, conferences, queues |
<Gather> |
Collect user input | DTMF, speech recognition, hints, timeouts |
<Record> |
Record audio | Transcription, max length, finish keys, dual-channel |
<Pause> |
Add silence | Configurable duration |
<Hangup> |
End the call | Immediate call termination |
<Redirect> |
Transfer control | GET/POST methods, URL redirection |
<Reject> |
Reject calls | Busy or rejected reasons |
<Enqueue> |
Queue management | Wait URLs, workflow integration, max queue size |
<Leave> |
Exit queue | Leave current queue |
<Connect> |
Advanced connections | Streams, AI sessions, conversations, virtual agents |
<Pay> |
Payment processing | Credit cards, ACH, tokenization |
<Refer> |
SIP REFER | SIP call transfer |
<Start> |
Start services | Streaming, transcription, recording, SIPREC |
<Stop> |
Stop services | Stop active streams/recordings |
<Echo> |
Echo audio | Testing and debugging |
<Sms> |
Send SMS | Send SMS during voice call |
<Prompt> |
Payment prompts | Payment card prompts |
<Queue> |
Queue caller | TaskRouter integration |
Dial Nouns (Nested in <Dial>)
| Noun | Description | Use Case |
|---|---|---|
<Number> |
Phone number | Dial PSTN numbers with caller ID, machine detection |
<Client> |
Twilio Client | Dial browser/mobile clients |
<Conference> |
Conference room | Multi-party conferences with recording, coaching |
<Queue> |
Call queue | TaskRouter queue integration |
<Sip> |
SIP endpoint | Dial SIP addresses with custom headers |
<Sim> |
Twilio SIM | Dial Twilio Programmable Wireless SIMs |
<Application> |
TwiML App | Dial TwiML applications |
<WhatsApp> |
Dial WhatsApp numbers |
Connect Nouns (Nested in <Connect>)
| Noun | Description | Use Case |
|---|---|---|
<Stream> |
Media streams | WebSocket audio streaming |
<Room> |
Video room | Twilio Video room connections |
<Conversation> |
Conversations | Twilio Conversations API |
<VirtualAgent> |
AI agent | Google Dialogflow integration |
<Autopilot> |
Autopilot | Twilio Autopilot assistant |
<AiSession> |
AI session | AI-powered voice agents |
<Assistant> |
Assistant | Voice assistants |
<ConversationRelay> |
Relay | Conversation relay |
SSML Elements (Nested in <Say>)
Full support for Speech Synthesis Markup Language:
| Element | Description | Example |
|---|---|---|
<break> |
Pause/silence | Strength (weak, medium, strong) or time (1s, 500ms) |
<emphasis> |
Emphasis | Levels: strong, moderate, reduced |
<prosody> |
Speech properties | Pitch, rate, volume adjustments |
<lang> |
Language switch | Switch language mid-speech |
<p> |
Paragraph | Paragraph breaks |
<s> |
Sentence | Sentence breaks |
<say-as> |
Interpret as | Numbers, dates, times, addresses, etc. |
<phoneme> |
Pronunciation | IPA, X-SAMPA phonetic alphabets |
<sub> |
Substitution | Replace text with alias |
<w> |
Word | Word-level control |
<amazon:effect> |
Voice effects | Amazon Polly effects (whispered, etc.) |
<amazon:domain> |
Speaking style | News, conversational styles |
Messaging Verbs
| Verb | Description | Key Features |
|---|---|---|
<Message> |
Send SMS/MMS | Body, media, status callbacks, scheduling |
<Body> |
Message text | Plain text message content (max 1600 chars) |
<Media> |
Media attachment | Images, videos, PDFs (up to 10 per message) |
<Redirect> |
Redirect | Transfer to another TwiML URL |
Fax Verbs
| Verb | Description | Key Features |
|---|---|---|
<Receive> |
Receive fax | PDF/TIFF formats, Letter/Legal/A4 sizes, storage options |
Validation
The library includes comprehensive validation to catch errors before sending TwiML to Twilio:
Basic Validation
use ;
let response = new
.say
.hangup;
let xml = response.to_xml;
// Validate the generated TwiML
match validate_twiml
Strict Validation
Enable strict validation for production environments:
use validate_twiml_strict;
match validate_twiml_strict
What Gets Validated
- XML Well-formedness: Proper XML structure and balanced tags
- Required Elements: Presence of
<?xml>declaration and<Response>root - URL Validation: URLs start with
http://,https://, or/ - Phone Numbers: E.164 format validation (starts with
+) - Content Lengths: Say content (4096 chars), Message body (1600 chars)
- Logic Warnings: Unreachable verbs, infinite loops, etc.
Validation Warnings
The library also provides warnings for potential logic issues:
use MessagingResponse;
let response = new
.redirect
.message; // Warning: unreachable
let warnings = response.validate;
for warning in warnings
// Output: âš Warning: 1 verb(s) after Redirect at index 0 will never be reached
Security
XML Injection Prevention
All user-provided content is automatically escaped to prevent XML injection attacks:
use ;
let user_input = "<script>alert('xss')</script>";
let response = new.say;
println!;
// Output: <Say><script>alert('xss')</script></Say>
The library provides two escaping functions:
escape_xml_text()- For text content between tagsescape_xml_attr()- For attribute values (also escapes quotes)
Best Practices
- Always validate TwiML before sending to production
- Use strict validation in production environments
- Never disable automatic XML escaping
- Validate user input before using in phone numbers or URLs
- Use HTTPS for all callback URLs in production
Use Cases
Customer Support IVR
use ;
Appointment Reminders
use ;
Call Recording System
use ;
Two-Factor Authentication
use ;
Examples
See the examples/ directory for complete, runnable examples:
voice_call.rs- Voice call handling with IVR, call forwarding, voicemail, and SSMLsms_message.rs- SMS/MMS messaging with media attachments and attributesfax_receive.rs- Fax reception configuration with various options
Run examples with:
Architecture
Core Traits
The library is built around the TwiML trait:
All response types (VoiceResponse, MessagingResponse, FaxResponse) implement this trait, providing a consistent interface for XML generation.
Builder Pattern
All verbs and nouns use the builder pattern for ergonomic API:
let dial = new
.timeout
.caller_id
.record
.add_number;
Type Safety
The library uses Rust's type system to prevent invalid TwiML:
- Enums for valid values (e.g.,
ReceiveMediaType::ApplicationPdf) - Optional types for optional attributes
- Nested enums for verb-specific nouns (e.g.,
DialNoun,GatherNoun)
Advanced Features
Comments in TwiML
Add XML comments for debugging or documentation:
use ;
let response = new
.comment_before
.comment
.say
.comment_after;
println!;
Output:
<!-- Generated by my application v1.0 -->
<!-- Main greeting -->
Hello!
<!-- End of TwiML -->
Custom Voice Attributes
Fine-tune text-to-speech with voices and languages:
use ;
let say = new
.voice // Amazon Polly voice
.language // US English
.loop_count; // Repeat twice
let response = new.say_with;
Supported voices include:
- Amazon Polly:
Polly.Joanna,Polly.Matthew,Polly.Salli, etc. - Google:
Google.en-US-Standard-A,Google.en-GB-Wavenet-B, etc. - Standard:
man,woman,alice
Machine Detection
Detect answering machines when dialing:
use ;
let dial = new
.add_number;
let response = new.dial_with;
SIP Integration
Dial SIP endpoints with custom headers:
use ;
let sip = new
.username
.password
.add_custom_header;
let dial = new.add_sip;
let response = new.dial_with;
Media Streaming
Stream audio to WebSocket endpoints:
use ;
let stream = new
.url
.track
.status_callback;
let connect = new.add_stream;
let response = new.connect;
Payment Processing
Collect payment information securely:
use ;
let pay = new
.charge_amount
.currency
.payment_method
.action
.status_callback;
let response = new
.say
.pay;
Testing
The library includes 167+ comprehensive tests covering:
- All voice verbs and attributes
- All messaging verbs and nouns
- All fax operations
- SSML element generation
- XML escaping and security
- Validation logic
- Edge cases and error conditions
Run tests with:
Run tests with output:
Run specific test module:
Performance
- Zero allocations for simple responses
- Minimal overhead - direct string building without intermediate representations
- No external dependencies - fast compilation times
- Small binary size - adds minimal size to your application
Benchmark (simple voice response):
Time to generate: ~500ns
Memory allocated: ~200 bytes
Contributing
Contributions are welcome! Here's how you can help:
- Report bugs - Open an issue with a minimal reproduction
- Suggest features - Propose new TwiML verbs or improvements
- Submit PRs - Fix bugs or add features (please include tests)
- Improve docs - Help make the documentation better
Development Setup
# Clone the repository
# Run tests
# Run examples
# Check formatting
# Run clippy
# Build documentation
Guidelines
- Follow Rust naming conventions and idioms
- Add tests for new features
- Update documentation and examples
- Ensure all tests pass before submitting PR
- Keep commits focused and well-described
License
This project is licensed under the MIT License - see the LICENSE file for details.
Copyright (c) 2026 TwiML Rust Contributors
Resources
Official Twilio Documentation
- TwiML Voice Reference - Complete TwiML voice verb documentation
- TwiML Messaging Reference - SMS/MMS TwiML documentation
- TwiML Fax Reference - Fax TwiML documentation
- SSML Reference - Speech Synthesis Markup Language
Library Documentation
- API Documentation - Complete API reference on docs.rs
- Crates.io - Package on crates.io
- GitHub Repository - Source code and issues
Acknowledgments
- Built by developers, for developers
- Inspired by TwiML libraries for other languages
- Thanks to all contributors and users
- Special thanks to the Twilio team for creating TwiML
Changelog
See CHANGELOG.md for a detailed history of changes.
FAQ
Q: Does this library make HTTP requests to Twilio?
A: No, this library only generates TwiML XML. You need to serve the XML from your web server in response to Twilio's HTTP requests.
Q: Can I use this with async/await?
A: Yes! The library is sync but works perfectly in async contexts. Just call to_xml() to generate the XML string.
Q: How do I serve TwiML from my web server?
A: Use any Rust web framework (Actix, Axum, Rocket, etc.) and return the XML with Content-Type: application/xml:
// Example with Axum
use ;
use ;
async
Q: Is this library production-ready?
A: Yes! The library is thoroughly tested with 167+ tests and follows Rust best practices. However, always validate your TwiML before deploying to production.
Q: What's the difference between say() and say_with()?
A: say() is a convenience method for simple text. say_with() accepts a Say object with custom attributes and SSML elements.
Q: Can I contribute new TwiML verbs?
A: Absolutely! Please open an issue first to discuss, then submit a PR with tests and documentation.
Made with Rust | Open Source & Community Driven | TwiML XML Generator