Sample code for 30+ languages & platforms
Zig

DynamoDB - Query

See more Amazon DynamoDB Examples

The Query operation finds items based on primary key values. You can query any table or secondary index that has a composite primary key (a partition key and a sort key).

Chilkat Zig Downloads

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

    // Implements the following CURL command:

    // curl -X POST https://dynamodb.us-west-2.amazonaws.com/ \
    //   -H "Accept-Encoding: identity" \
    //   -H "Content-Type: application/x-amz-json-1.0" \
    //   -H "Authorization: AWS4-HMAC-SHA256 Credential=<Credential>, SignedHeaders=<Headers>, Signature=<Signature>" \
    //   -H "X-Amz-Date: <Date>" \
    //   -H "X-Amz-Target: DynamoDB_20120810.Query" \
    //   -d '{
    //     "TableName": "Reply",
    //     "IndexName": "PostedBy-Index",
    //     "Limit": 3,
    //     "ConsistentRead": true,
    //     "ProjectionExpression": "Id, PostedBy, ReplyDateTime",
    //     "KeyConditionExpression": "Id = :v1 AND PostedBy BETWEEN :v2a AND :v2b",
    //     "ExpressionAttributeValues": {
    //         ":v1": {"S": "Amazon DynamoDB#DynamoDB Thread 1"},
    //         ":v2a": {"S": "User A"},
    //         ":v2b": {"S": "User C"}
    //     },
    //     "ReturnConsumedCapacity": "TOTAL"
    // }'

    // Use the following online tool to generate REST code from a CURL command
    // Convert a cURL Command to REST Source Code

    const auth_aws = try chilkat.AuthAws.init();
    defer auth_aws.deinit();
    auth_aws.setAccessKey("AWS_ACCESS_KEY");
    auth_aws.setSecretKey("AWS_SECRET_KEY");
    // Don't forget to change the region to your particular region. (Also make the same change in the call to Connect below.)
    auth_aws.setRegion("us-west-2");
    auth_aws.setServiceName("dynamodb");
    // SetAuthAws causes Chilkat to automatically add the following headers: Authorization, X-Amz-Date
    rest.setAuthAws(auth_aws) catch {};

    // URL: https://dynamodb.us-west-2.amazonaws.com/
    const b_tls = true;
    const port = 443;
    const b_auto_reconnect = true;
    rest.connect("dynamodb.us-west-2.amazonaws.com", port, b_tls, b_auto_reconnect) catch {
        std.debug.print("ConnectFailReason: {d}\n", .{rest.getConnectFailReason()});
        std.debug.print("{s}\n", .{try rest.getLastErrorText(alloc)});
        return;
    };

    // Note: The above code does not need to be repeatedly called for each REST request.
    // The rest object can be setup once, and then many requests can be sent.  Chilkat will automatically
    // reconnect within a FullRequest* method as needed.  It is only the very first connection that is explicitly
    // made via the Connect method.

    // Use this online tool to generate code from sample JSON:
    // Generate Code to Create JSON

    // The following JSON is sent in the request body.

    // {
    //   "TableName": "Reply",
    //   "IndexName": "PostedBy-Index",
    //   "Limit": 3,
    //   "ConsistentRead": true,
    //   "ProjectionExpression": "Id, PostedBy, ReplyDateTime",
    //   "KeyConditionExpression": "Id = :v1 AND PostedBy BETWEEN :v2a AND :v2b",
    //   "ExpressionAttributeValues": {
    //     ":v1": {
    //       "S": "Amazon DynamoDB#DynamoDB Thread 1"
    //     },
    //     ":v2a": {
    //       "S": "User A"
    //     },
    //     ":v2b": {
    //       "S": "User C"
    //     }
    //   },
    //   "ReturnConsumedCapacity": "TOTAL"
    // }

    const json = try chilkat.JsonObject.init();
    defer json.deinit();
    json.updateString("TableName", "Reply") catch {};
    json.updateString("IndexName", "PostedBy-Index") catch {};
    json.updateInt("Limit", 3) catch {};
    json.updateBool("ConsistentRead", true) catch {};
    json.updateString("ProjectionExpression", "Id, PostedBy, ReplyDateTime") catch {};
    json.updateString("KeyConditionExpression", "Id = :v1 AND PostedBy BETWEEN :v2a AND :v2b") catch {};
    json.updateString("ExpressionAttributeValues.:v1.S", "Amazon DynamoDB#DynamoDB Thread 1") catch {};
    json.updateString("ExpressionAttributeValues.:v2a.S", "User A") catch {};
    json.updateString("ExpressionAttributeValues.:v2b.S", "User C") catch {};
    json.updateString("ReturnConsumedCapacity", "TOTAL") catch {};

    rest.addHeader("Content-Type", "application/x-amz-json-1.0") catch {};
    rest.addHeader("X-Amz-Target", "DynamoDB_20120810.Query") catch {};
    rest.addHeader("Accept-Encoding", "identity") catch {};

    const sb_request_body = try chilkat.StringBuilder.init();
    defer sb_request_body.deinit();
    json.emitSb(sb_request_body) catch {};
    const sb_response_body = try chilkat.StringBuilder.init();
    defer sb_response_body.deinit();
    rest.fullRequestSb("POST", "/", sb_request_body, sb_response_body) catch {
        std.debug.print("{s}\n", .{try rest.getLastErrorText(alloc)});
        return;
    };

    const resp_status_code = rest.getResponseStatusCode();
    std.debug.print("response status code = {d}\n", .{resp_status_code});
    if (resp_status_code >= 400) {
        std.debug.print("Response Status Code = {d}\n", .{resp_status_code});
        std.debug.print("Response Header:\n", .{});
        std.debug.print("{s}\n", .{try rest.getResponseHeader(alloc)});
        std.debug.print("Response Body:\n", .{});
        std.debug.print("{s}\n", .{try sb_response_body.getAsString(alloc)});
        return;
    }

    const json_response = try chilkat.JsonObject.init();
    defer json_response.deinit();
    json_response.loadSb(sb_response_body) catch {};

    json_response.setEmitCompact(false);
    std.debug.print("{s}\n", .{try json_response.emit(alloc)});

    // Sample JSON response:
    // (Sample code for parsing the JSON response is shown below)

    // {
    //   "ConsumedCapacity": {
    //     "CapacityUnits": 1,
    //     "TableName": "Reply"
    //   },
    //   "Count": 2,
    //   "Items": [
    //     {
    //       "ReplyDateTime": {
    //         "S": "2015-02-18T20:27:36.165Z"
    //       },
    //       "PostedBy": {
    //         "S": "User A"
    //       },
    //       "Id": {
    //         "S": "Amazon DynamoDB#DynamoDB Thread 1"
    //       }
    //     },
    //     {
    //       "ReplyDateTime": {
    //         "S": "2015-02-25T20:27:36.165Z"
    //       },
    //       "PostedBy": {
    //         "S": "User B"
    //       },
    //       "Id": {
    //         "S": "Amazon DynamoDB#DynamoDB Thread 1"
    //       }
    //     }
    //   ],
    //   "ScannedCount": 2
    // }

    // Sample code for parsing the JSON response...
    // Use the following online tool to generate parsing code from sample JSON:
    // Generate Parsing Code from JSON

    var reply_date_time_s: [:0]const u8 = "";
    var posted_by_s: [:0]const u8 = "";
    var id_s: [:0]const u8 = "";

    _ = json_response.intOf("ConsumedCapacity.CapacityUnits");
    _ = try json_response.stringOf(alloc, "ConsumedCapacity.TableName");
    _ = json_response.intOf("Count");
    _ = json_response.intOf("ScannedCount");
    var i: i32 = 0;
    const count_i = json_response.sizeOfArray("Items");
    while (i < count_i) {
        json_response.setI(i);
        reply_date_time_s = try json_response.stringOf(alloc, "Items[i].ReplyDateTime.S");
        posted_by_s = try json_response.stringOf(alloc, "Items[i].PostedBy.S");
        id_s = try json_response.stringOf(alloc, "Items[i].Id.S");
        i = i + 1;
    }
}