Sample code for 30+ languages & platforms
Rust

Create a New GMail Label

See more GMail REST API Examples

Demonstrates how to create a new GMail label.

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);

// Create the JSON to be sent in the HTTP request body.
// The name of the new label is "questions".
let json = chilkat::JsonObject::new();
let _ = json.update_string("name", "questions");
let _ = json.update_string("labelListVisibility", "labelShow");
let _ = json.update_string("messageListVisibility", "show");

json.set_emit_compact(false);
println!("{}", json.emit().unwrap_or_default());

// The JSON contains this:
// {
//   "name": "questions",
//   "labelListVisibility": "labelShow",
//   "messageListVisibility": "show"
// }

let url = "https://www.googleapis.com/gmail/v1/users/{$userId}/labels".to_string();
let resp = chilkat::HttpResponse::new();
if http.http_json("POST", &url, &json, "application/json", &resp).is_err() {
    println!("{}", http.last_error_text());
    return;
}

println!("status = {}", resp.status_code());

// A 200 response status indicate success.
if resp.status_code() != 200 {
    println!("{}", resp.body_str());
    println!("Failed.");
    return;
}

// A successful repsonse contains JSON that looks like this:

// {
//  "id": "Label_43",
//  "name": "questions",
//  "messageListVisibility": "show",
//  "labelListVisibility": "labelShow"
// }

println!("response body:");
println!("{}", resp.body_str());

println!("GMail label created!");