Skip to contentSkip to navigationSkip to topbar
Rate this page:
On this page

Generate a Rust client for Twilio's API


(information)

Info

The Twilio OpenAPI Spec is currently in BETA . The spec is expected to be accurate, but is currently in active development and is unsupported . If you've identified a mismatch between Twilio's API behavior and the specification, please open an issue(link takes you to an external page).

With the rollout of Twilio's OpenAPI specification(link takes you to an external page), it is now possible to auto-generate your own Twilio client in your preferred programming language.

One language that Twilio currently does not have an official SDK for is Rust. By using the Twilio OpenAPI specification with open source tools such as OpenAPI Generator(link takes you to an external page), you can now generate a strongly-typed Rust client for Twilio's API methods.


Setup

setup page anchor

To begin, install(link takes you to an external page) OpenAPI Generator. If you are on a Mac, we recommend installing using Homebrew for ease of use as below:


_10
brew install openapi-generator

Once OpenAPI Generator is installed, the next step is to generate your very first Twilio client in Rust. Paste the following code snippet into your terminal to pull in the Twilio OpenAPI spec from GitHub, generate a client, and save the resulting client code to a directory named twilio-rust.


_10
openapi-generator generate -g rust \
_10
-i https://raw.githubusercontent.com/twilio/twilio-oai/main/spec/json/twilio_api_v2010.json \
_10
-o twilio-rust \
_10
--additional-properties=useSingleRequestParameter=true

(information)

Info

Refer to the configuration documentation(link takes you to an external page) for the Rust generator to see other ways you can customize the generated library to your needs.


Use the auto-generated Twilio Rust client

use-the-auto-generated-twilio-rust-client page anchor

Create a Rust project

create-a-rust-project page anchor

Now that the client has been generated, it's time to create some code that will enable you to interact with Twilio's API in Rust. If you don't already have Rust installed, you can install Rust(link takes you to an external page) by following the instructions as described in their documentation.

With Rust installed, create a new Rust project. We suggest that you use cargo to simplify this process and run the following command from the same directory where you executed the codegen process:


_10
cargo new twilio-rust-example

This will scaffold out a Rust project for you, with the necessary main.rs file and a Cargo.toml file for managing dependencies.


_10
.
_10
├── src
_10
│ └── main.rs
_10
└── Cargo.toml

In order to make use of the generated Twilio client, it must be added to the project's Cargo.toml. More specifically, it should be added as a path dependency(link takes you to an external page), since it is a crate currently residing on your local file system instead of crates.io(link takes you to an external page) or a similar repository.

Let's add two more dependencies as well:

  • dotenv to enable easy access to environment variables from a local .env file
  • tokio which provides an asynchronous runtime environment so that your code can use async/await

You can manually edit Cargo.toml to include these dependencies, but we suggest leveraging a tool such as cargo-edit(link takes you to an external page) to manage dependencies. Once you have installed cargo-edit, run the following commands:


_10
cargo add openapi --path=../twilio-rust
_10
cargo add dotenv
_10
cargo add tokio --features rt,rt-multi-thread,macros

Once cargo-edit has completed (or you skipped that step and did things manually), Cargo.toml will reflect the following contents:


_11
[package]
_11
name = "twilio-rust-example"
_11
version = "0.1.0"
_11
edition = "2021"
_11
_11
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
_11
_11
[dependencies]
_11
dotenv = "0.15.0"
_11
openapi = { path = "../twilio-rust" }
_11
tokio = { version = "1.21.1", features = ["rt", "rt-multi-thread", "macros"] }

(information)

Info

The specific versions of dotenv and tokio may vary from this example depending on when you are coming across this tutorial. Using cargo-edit as shown above will ensure you're on the latest version of each.

Once you've saved those changes to Cargo.toml, run the following command to install all of the above dependencies.


_10
cargo build

Send an SMS using Twilio and Rust

send-an-sms-using-twilio-and-rust page anchor

Now that our dependencies are in order, it's time to create a program in Rust.

We will leverage environment variables in order to securely access your Twilio credentials, so the next step is to create a .env file at the root of your Rust project and provide the necessary values. Be sure to replace the placeholder values here with your own credentials and a non-Twilio phone number such as your own as TO_NUMBER. Ensure that your phone numbers are declared in the E.164 format (+1234567890).


_10
TWILIO_API_KEY=SKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
_10
TWILIO_API_KEY_SECRET=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
_10
TWILIO_ACCOUNT_SID=ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
_10
TWILIO_PHONE_NUMBER=+1098765432
_10
TO_NUMBER=+1234567890

(information)

Info

Note that we're using best practices here, and creating the Twilio client using an API Key and Secret instead of directly using and potentially exposing your account's auth token. If you'd like to learn more about API Keys and how to create one, please refer to the API Keys documentation!

With the environment variables in place, it's time to open src/main.rs and replace the boilerplate code there with the following sample:

Send an SMS with Rust

send-an-sms-with-rust page anchor

_46
use dotenv;
_46
use openapi::apis::{
_46
configuration::Configuration,
_46
default_api::{self as twilio_api, CreateMessageParams},
_46
};
_46
use std::env;
_46
_46
#[tokio::main]
_46
async fn main() {
_46
// Securely import sensitive credentials and values from your .env file
_46
dotenv::dotenv().expect("Failed to read .env file");
_46
let account_sid = env::var("TWILIO_ACCOUNT_SID")
_46
.expect("env variable `TWILIO_ACCOUNT_SID` should be set");
_46
let api_key = env::var("TWILIO_API_KEY")
_46
.expect("env variable `TWILIO_API_KEY` should be set");
_46
let api_key_secret = env::var("TWILIO_API_KEY_SECRET")
_46
.expect("env variable `TWILIO_API_KEY_SECRET` should be set");
_46
let from = env::var("TWILIO_PHONE_NUMBER")
_46
.expect("env variable `TWILIO_PHONE_NUMBER` should be set");
_46
let to = env::var("TO_NUMBER").expect("env variable `TO_NUMBER` should be set");
_46
_46
// Create a new configuration for your Twilio client.
_46
let twilio_config = Configuration {
_46
basic_auth: Some((api_key, Some(api_key_secret))),
_46
..Default::default()
_46
};
_46
_46
// Define the message that you wish to send
_46
let message_params = CreateMessageParams {
_46
account_sid,
_46
to,
_46
from: Some(from),
_46
body: Some("Ahoy, Rustacean! 🦀".into()),
_46
..Default::default()
_46
};
_46
_46
// Asynchronously send the message from your Twilio phone number.
_46
let message = twilio_api::create_message(&twilio_config, message_params).await;
_46
_46
match message {
_46
Ok(result) => {
_46
println!("Message sent with SID {}", result.sid.unwrap().unwrap())
_46
}
_46
Err(error) => eprintln!("Error sending message: {}", error),
_46
};
_46
}

Execute cargo run in your terminal, and you will see a log output of the message's SID as well as an SMS appear on your intended phone shortly after.


_10
$ cargo run
_10
Finished dev [unoptimized + debuginfo] target(s) in 0.15s
_10
Running `target/debug/twilio-rust-example`
_10
Message sent with SID "SMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"


Rate this page: