Zig
Zig
Find a Label ID by Name
See more GMail REST API Examples
Lookup the ID of a GMail label by the label name.Chilkat Zig Downloads
const std = @import("std");
const chilkat = @import("chilkat");
pub fn main(init: std.process.Init) !void {
const alloc = init.arena.allocator();
// This example requires the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
const http = try chilkat.Http.init();
defer http.deinit();
http.setAuthToken("GMAIL-ACCESS-TOKEN");
const user_id = "me";
http.setUrlVar("userId", user_id) catch {};
const url = "https://www.googleapis.com/gmail/v1/users/{$userId}/labels";
// Get the list of GMail labels as JSON.
const sb = try chilkat.StringBuilder.init();
defer sb.deinit();
http.quickGetSb(url, sb) catch {
std.debug.print("{s}\n", .{try http.getLastErrorText(alloc)});
return;
};
const json = try chilkat.JsonObject.init();
defer json.deinit();
json.loadSb(sb) catch {};
json.setEmitCompact(false);
std.debug.print("{s}\n", .{try json.emit(alloc)});
if (http.getLastStatus() != 200) {
std.debug.print("Failed.\n", .{});
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...
var j_record: chilkat.JsonObject = try json.findRecord("labels", "name", "QA", false);
defer j_record.deinit();
if (json.getLastMethodSuccess()) {
std.debug.print("The id of QA is: {s}\n", .{try j_record.stringOf(alloc, "id")});
}
{
const next = try json.findRecord("labels", "name", "[Gmail]/testFolder", false);
j_record.deinit();
j_record = next;
}
if (json.getLastMethodSuccess()) {
std.debug.print("The id of [Gmail]/testFolder is: {s}\n", .{try j_record.stringOf(alloc, "id")});
}
{
const next = try json.findRecord("labels", "name", "questions", false);
j_record.deinit();
j_record = next;
}
if (json.getLastMethodSuccess()) {
std.debug.print("The id of questions is: {s}\n", .{try j_record.stringOf(alloc, "id")});
}
// Output:
// The id of QA is: Label_5
// The id of [Gmail]/testFolder is: Label_21
// The id of questions is: Label_43
}