Zig
Zig
SugarCRM Authenticate
See more SugarCRM Examples
Demonstrates how to authenticate to the SugarCRM REST v10 API. This is how an OAuth2 access token is obtained.Chilkat Zig Downloads
const std = @import("std");
const chilkat = @import("chilkat");
pub fn main(init: std.process.Init) !void {
const alloc = init.arena.allocator();
const rest = try chilkat.Rest.init();
defer rest.deinit();
rest.connect("your.site.domain", 443, true, true) catch {
std.debug.print("{s}\n", .{try rest.getLastErrorText(alloc)});
return;
};
rest.addHeader("Cache-Control", "no-cache") catch {};
// The following code creates the JSON request body.
// The JSON created by this code is shown below.
const json_req = try chilkat.JsonObject.init();
defer json_req.deinit();
json_req.updateString("grant_type", "password") catch {};
json_req.updateString("client_id", "sugar") catch {};
json_req.updateString("client_secret", "CLIENT_SECRET") catch {};
json_req.updateString("username", "admin") catch {};
json_req.updateString("password", "password") catch {};
json_req.updateString("platform", "custom_api") catch {};
// The JSON request body created by the above code:
// {
// "grant_type": "password",
// "client_id": "sugar",
// "client_secret": "CLIENT_SECRET",
// "username": "admin",
// "password": "password",
// "platform": "custom_api"
// }
const sb_req = try chilkat.StringBuilder.init();
defer sb_req.deinit();
json_req.emitSb(sb_req) catch {};
rest.addHeader("Content-Type", "application/json") catch {};
const sb_json = try chilkat.StringBuilder.init();
defer sb_json.deinit();
rest.fullRequestSb("POST", "/rest/v10/oauth2/token", sb_req, sb_json) catch {
std.debug.print("{s}\n", .{try rest.getLastErrorText(alloc)});
return;
};
if (rest.getResponseStatusCode() != 200) {
std.debug.print("Received error response code: {d}\n", .{rest.getResponseStatusCode()});
std.debug.print("Response body:\n", .{});
std.debug.print("{s}\n", .{try sb_json.getAsString(alloc)});
return;
}
const json = try chilkat.JsonObject.init();
defer json.deinit();
json.loadSb(sb_json) catch {};
// The following code parses the JSON response.
// A sample JSON response is shown below the sample code.
_ = try json.stringOf(alloc, "access_token");
_ = json.intOf("expires_in");
_ = try json.stringOf(alloc, "token_type");
_ = json.isNullOf("scope");
_ = try json.stringOf(alloc, "refresh_token");
_ = json.intOf("refresh_expires_in");
_ = try json.stringOf(alloc, "download_token");
// A sample JSON response body that is parsed by the above code:
// {
// "access_token": "c6d495c9-bb25-81d2-5f81-533ef6479f9b",
// "expires_in": 3600,
// "token_type": "bearer",
// "scope": null,
// "refresh_token": "cbc40e67-12bc-4b56-a1d9-533ef62f2601",
// "refresh_expires_in": 1209600,
// "download_token": "cc5d1a9f-6627-3349-96e5-533ef6b1a493"
// }
std.debug.print("Example Completed.\n", .{});
}