Sample code for 30+ languages & platforms
Rust

Find a Label ID by Name

See more GMail REST API Examples

Lookup the ID of a GMail label by the label name.

Chilkat Rust Downloads

Rust

// This example requires the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.

let http = chilkat::Http::new();
http.set_auth_token("GMAIL-ACCESS-TOKEN");

let user_id = "me".to_string();
let _ = http.set_url_var("userId", &user_id);

let url = "https://www.googleapis.com/gmail/v1/users/{$userId}/labels".to_string();

// Get the list of GMail labels as JSON.
let sb = chilkat::StringBuilder::new();
if http.quick_get_sb(&url, &sb).is_err() {
    println!("{}", http.last_error_text());
    return;
}

let json = chilkat::JsonObject::new();
let _ = json.load_sb(&sb);
json.set_emit_compact(false);
println!("{}", json.emit().unwrap_or_default());

if http.last_status() != 200 {
    println!("Failed.");
    return;
}

// The JSON returned looks like this:
// {
//   "labels": [
//     {
//       "id": "Label_5",
//       "name": "QA",
//       "messageListVisibility": "show",
//       "labelListVisibility": "labelShow",
//       "type": "user"
//     },
//     {
//       "id": "Label_21",
//       "name": "[Gmail]/testFolder",
//       "type": "user"
//     },
//     {
//       "id": "CATEGORY_PERSONAL",
//       "name": "CATEGORY_PERSONAL",
//       "type": "system"
//     },
// 	...

// The name of the label is generally known because it's what we visually see.
// The id is what we need to get.  Assuming the name is unique,
// find the JSON record having name=<desired name>
// For example...
let mut j_record = json.find_record("labels", "name", "QA", false).unwrap();
if json.last_method_success() {
    println!("The id of QA is: {}", j_record.string_of("id").unwrap_or_default());

}

j_record = json.find_record("labels", "name", "[Gmail]/testFolder", false).unwrap();
if json.last_method_success() {
    println!("The id of [Gmail]/testFolder is: {}", j_record.string_of("id").unwrap_or_default());

}

j_record = json.find_record("labels", "name", "questions", false).unwrap();
if json.last_method_success() {
    println!("The id of questions is: {}", j_record.string_of("id").unwrap_or_default());

}

// Output:

// The id of QA is: Label_5
// The id of [Gmail]/testFolder is: Label_21
// The id of questions is: Label_43