Zig Requires Chilkat v11.5.0+
Zig
Box: Get a Service Account Token with Client Credentials
See more Box Examples
Obtain a Box service-account token using the client credentials grant. Configure and authorize a Server app first. Load credentials from protected application configuration; do not ship a client secret in a public client.
See the Box API guide for setup and the complete workflow.
Chilkat Zig Downloads
const std = @import("std");
const chilkat = @import("chilkat");
pub fn main(init: std.process.Init) !void {
const alloc = init.arena.allocator();
var success: bool = false;
// Requires Chilkat 11.5.0 or later and a previously unlocked Chilkat bundle.
// See Global Unlock Sample.
// Guide: Box API Guide.
success = false;
const curl = try chilkat.HttpCurl.init();
defer curl.deinit();
curl.setVar("client_id", "BOX_CLIENT_ID");
curl.setVar("client_secret", "BOX_CLIENT_SECRET");
curl.setVar("enterprise_id", "BOX_ENTERPRISE_ID");
// enterprise identifies the app's service account. This is not an admin-user token.
curl.clearTargetOutput("*");
curl.clearVar("access_token");
curl.addTargetOutput("access_token", "access_token");
success = if (curl.doYourThing("curl -X POST \"https://api.box.com/oauth2/token\" --data-urlencode \"grant_type=client_credentials\" --data-urlencode \"client_id={{client_id}}\" --data-urlencode \"client_secret={{client_secret}}\" --data-urlencode \"box_subject_type=enterprise\" --data-urlencode \"box_subject_id={{enterprise_id}}\"")) true else |_| false;
if ((!success) or (curl.getStatusCode() != 200)) {
std.debug.print("Box request failed. HTTP status: {d}\n", .{curl.getStatusCode()});
std.debug.print("Failure reason: {d}\n", .{curl.getFailReason()});
return;
}
if (!curl.varDefined("!")) {
std.debug.print("Expected response fields are missing.\n", .{});
return;
}
// Keep this token in protected application memory; reacquire it when it expires.
// Do not print tokens or the complete token response.
std.debug.print("Service-account access token obtained.\n", .{});
curl.clearTargetOutput("*");
const authorized_command1 = try chilkat.StringBuilder.init();
defer authorized_command1.deinit();
authorized_command1.setString("curl -X GET \"https://api.box.com/2.0/users/me?fields=id,name,login\" -H \"Authorization: Bearer {{access_token}}\"") catch {};
_ = authorized_command1.replace("{{access_token}}", try curl.getVar(alloc, "access_token"));
success = if (curl.doYourThing(try authorized_command1.getAsString(alloc))) true else |_| false;
if ((!success) or (curl.getStatusCode() != 200)) {
std.debug.print("Box request failed. HTTP status: {d}\n", .{curl.getStatusCode()});
std.debug.print("Failure reason: {d}\n", .{curl.getFailReason()});
std.debug.print("{s}\n", .{try curl.getResponseBodyStr(alloc)});
return;
}
std.debug.print("{s}\n", .{try curl.getResponseBodyStr(alloc)});
}