Sample code for 30+ languages & platforms
Rust Requires Chilkat v11.0.0+

Validate and format a phone number with Twilio Lookup

See more Twilio Examples

Use Basic Lookup v2 to check a national-format number and obtain its E.164 and national display formats. Supply the two-letter country code for a national number. The example requests only the basic fields.

Read the boolean valid field even when the HTTP request succeeds. When it is false, display any validation_errors that Twilio supplies. Numbering-plan validation does not establish reachability or control of a phone. To confirm control, send an SMS verification code.

Twilio documentation

Chilkat Rust Downloads

Rust
let mut success = false;

// Assumes Chilkat is unlocked. See Global Unlock Sample.
// Load an API key for the Twilio account from private application configuration.
let http = chilkat::Http::new();
http.set_require_ssl_cert_verify(true);
http.set_basic_auth(true);
http.set_login("YOUR_API_KEY_SID");
http.set_password("YOUR_API_KEY_SECRET");

// The phone number is one URL path segment. Percent-encode spaces and any leading +.
let number = chilkat::StringBuilder::new();
let _ = number.append("020 7946 0018");
if number.encode("url_rfc3986", "utf-8").is_err() {
    println!("Could not encode the phone number.");
    return;
}

let url = chilkat::StringBuilder::new();
let _ = url.append("https://lookups.twilio.com/v2/PhoneNumbers/");
let _ = url.append(&number.get_as_string().unwrap_or_default());
let _ = url.append("?CountryCode=GB");
let resp = chilkat::HttpResponse::new();
let reply = chilkat::JsonObject::new();

success = http.http_no_body("GET", &url.get_as_string().unwrap_or_default(), &resp).is_ok();
if resp.status_code() == 0 {
    println!("No HTTP response from Twilio.");
    return;
}

let parsed = reply.load(&resp.body_str()).is_ok();
if (!success) || (resp.status_code() != 200) {
    println!("Twilio returned HTTP {}", resp.status_code());
    if (parsed) && (reply.json_type_of("code") == 2) {
        println!("Twilio error: {}  {}", reply.int_of("code"), reply.string_of("message").unwrap_or_default());
    }

    return;
}

if !parsed {
    println!("Expected a JSON response from Twilio.");
    return;
}

if reply.json_type_of("valid") != 5 {
    println!("The lookup response is missing the validity flag.");
    return;
}

if !reply.bool_of("valid") {
    println!("The number is invalid for the specified country.");
    let mut i = 0;
    while i < reply.size_of_array("validation_errors") {
        reply.set_i(i);
        println!("{}", reply.string_of("validation_errors[i]").unwrap_or_default());
        i = i + 1;
    }

    return;
}

if reply.json_type_of("phone_number") != 1 {
    println!("The lookup response is missing the E.164 number.");
    return;
}

println!("E.164: {}", reply.string_of("phone_number").unwrap_or_default());
println!("National format: {}", reply.string_of("national_format").unwrap_or_default());