Sample code for 30+ languages & platforms
C++ Requires Chilkat v11.6.0+

Amazon S3: Delete Multiple Objects and Check Each Result

See more S3 - REST Examples

Deletes the explicitly supplied objects. Load qa_data/aws/delete-objects.json with {"objects":[{"key":"documents/old.txt"},{"key":"documents/older.txt","version_id":"VERSION_ID"}]}. Supply 1–1000 unique entries per request. The example does not enumerate a prefix or automatically retry. Requires s3:DeleteObject and, for explicit versions, s3:DeleteObjectVersion.

Without versionId, an unversioned object is permanently removed; a versioned bucket normally creates a delete marker. Explicit data-version deletion is permanent. Retention, legal holds and MFA Delete can restrict deletion. Absent keys can still be acknowledged as deleted. HTTP 200 may contain per-object errors; each returned key/version is matched against the intended batch. Reconcile uncertain or missing results before any retry.

General purpose DeleteObjects uses Content-MD5. The tested AuthAws path omits that header, so this example explicitly constructs Signature Version 4 for the fixed POST /?delete= request and sends it through Rest. This is deliberately not a general URL signer. Do not change the body, hostname, query, or signed headers after signing, or attach AuthAws as a second signer.

For general purpose S3 buckets, using regional HTTPS endpoints and AWS Signature Version 4. Directory buckets (S3 Express), access points, Outposts, and other AWS partitions need their own endpoint/authentication rules. Use a bucket name without dots for these virtual-hosted TLS examples; see the path-style example for dotted names.

Provide current IAM credentials in a private qa_data/aws/s3.json file with string fields access_key, secret_key, and session_token for temporary credentials. Prefer short-lived role credentials. This file is explicitly loaded; these examples do not discover profiles or refresh credentials. Keep it outside public content and source control. The session token is included in the signed request. TLS certificate verification is enabled on the Socket used by Rest.

Transport success and HTTP success are different. Keep full diagnostics private; signed requests and presigned URLs can contain credentials or grant access. For retryable reads use bounded backoff with jitter. Before retrying a write with an uncertain outcome, check the resource state. Keep keys, upload IDs, version IDs, ETags, and large sizes as strings.

AWS DeleteObjects reference

Chilkat C++ Downloads

C++
#include <CkStringBuilder.h>
#include <CkJsonObject.h>
#include <CkRest.h>
#include <CkSocket.h>
#include <CkXml.h>
#include <CkHashtable.h>
#include <CkDateTime.h>
#include <CkCrypt2.h>

void ChilkatSample(void)
    {
    bool success = false;

    //  StringBuilder compares text by value in every generated language.
    CkStringBuilder textCompare;
    //  Assumes Chilkat is unlocked. See Global Unlock Sample.
    success = false;
    //  Private configuration, not a file in public web content or source control.
    //  Load current IAM credentials authorized for the S3 operation.
    CkJsonObject credentials;
    credentials.put_Strict(true);
    success = credentials.LoadFile("qa_data/aws/s3.json");
    if (success != true) {
        std::cout << "Could not load private AWS credentials." << "\r\n";
        return;
    }

    textCompare.Clear();
    textCompare.SetString(credentials.stringOf("access_key"));
    bool sameText1 = textCompare.ContentsEqual("",true);
    if ((credentials.JsonTypeOf("access_key") != 1) || (sameText1 == true)) {
        std::cout << "Missing or invalid access_key." << "\r\n";
        return;
    }

    textCompare.Clear();
    textCompare.SetString(credentials.stringOf("secret_key"));
    bool sameText2 = textCompare.ContentsEqual("",true);
    if ((credentials.JsonTypeOf("secret_key") != 1) || (sameText2 == true)) {
        std::cout << "Missing or invalid secret_key." << "\r\n";
        return;
    }

    //  General purpose bucket in the commercial AWS partition.
    const char *region = "us-west-2";
    const char *bucketName = "amzn-s3-demo-bucket";
    CkStringBuilder endpoint;
    success = endpoint.Append(bucketName);
    if (success != true) {
        std::cout << "Could not build text." << "\r\n";
        return;
    }

    success = endpoint.Append(".");
    if (success != true) {
        std::cout << "Could not build text." << "\r\n";
        return;
    }

    success = endpoint.Append("s3.");
    if (success != true) {
        std::cout << "Could not build text." << "\r\n";
        return;
    }

    success = endpoint.Append(region);
    if (success != true) {
        std::cout << "Could not build text." << "\r\n";
        return;
    }

    success = endpoint.Append(".amazonaws.com");
    if (success != true) {
        std::cout << "Could not build text." << "\r\n";
        return;
    }

    CkRest rest;
    rest.put_ConnectTimeoutMs(20000);
    rest.put_IdleTimeoutMs(60000);
    //  Connect to the SAME hostname used for TLS verification and request signing.
    CkSocket connection;
    connection.put_RequireSslCertVerify(true);
    connection.put_MaxReadIdleMs(60000);
    connection.put_MaxSendIdleMs(60000);
    success = connection.Connect(endpoint.getAsString(),443,true,20000);
    if (success != true) {
        std::cout << "TLS connection failed; inspect diagnostics privately." << "\r\n";
        return;
    }

    success = rest.UseConnection(connection,true);
    if (success != true) {
        std::cout << "Could not attach the TLS connection." << "\r\n";
        return;
    }

    CkXml xml;
    xml.put_Strict(true);
    rest.put_Host(endpoint.getAsString());
    if (credentials.HasMember("session_token") == true) {
        if (credentials.JsonTypeOf("session_token") != 1) {
            std::cout << "session_token must be a string." << "\r\n";
            return;
        }

    }

    //  One explicit batch, at most 1000 objects. No prefix expansion or auto-retry.
    CkJsonObject batch;
    batch.put_Strict(true);
    success = batch.LoadFile("qa_data/aws/delete-objects.json");
    if (success != true) {
        std::cout << "Could not load the intended deletion batch." << "\r\n";
        return;
    }

    int count = batch.SizeOfArray("objects");
    if ((count < 1) || (count > 1000)) {
        std::cout << "Supply 1 to 1000 objects in the batch." << "\r\n";
        return;
    }

    xml.put_Tag("Delete");
    success = xml.AddAttribute("xmlns","http://s3.amazonaws.com/doc/2006-03-01/");
    if (success != true) {
        std::cout << "Could not prepare the request." << "\r\n";
        return;
    }

    xml.UpdateChildContent("Quiet","false");
    CkHashtable requested;
    CkJsonObject identity;
    int i = 0;
    while ((i < count)) {
        batch.put_I(i);
        xml.put_I(i);
        textCompare.Clear();
        textCompare.SetString(batch.stringOf("objects[i].key"));
        bool sameText3 = textCompare.ContentsEqual("",true);
        if ((batch.JsonTypeOf("objects[i].key") != 1) || (sameText3 == true)) {
            std::cout << "Each object needs a nonempty key." << "\r\n";
            return;
        }

        const char *key = batch.stringOf("objects[i].key");
        const char *version = "";
        if (batch.HasMember("objects[i].version_id") == true) {
            textCompare.Clear();
            textCompare.SetString(batch.stringOf("objects[i].version_id"));
            bool sameText4 = textCompare.ContentsEqual("",true);
            if ((batch.JsonTypeOf("objects[i].version_id") != 1) || (sameText4 == true)) {
                std::cout << "version_id must be a nonempty string when present." << "\r\n";
                return;
            }

            version = batch.stringOf("objects[i].version_id");
            xml.UpdateChildContent("Object[i]|VersionId",version);
        }

        xml.UpdateChildContent("Object[i]|Key",key);
        success = identity.UpdateString("key",key);
        if (success != true) {
            std::cout << "Could not build saved state." << "\r\n";
            return;
        }

        success = identity.UpdateString("version",version);
        if (success != true) {
            std::cout << "Could not build saved state." << "\r\n";
            return;
        }

        const char *requestIdentity = identity.emit();
        if (requested.Contains(requestIdentity) == true) {
            std::cout << "Duplicate key/version in deletion batch." << "\r\n";
            return;
        }

        success = requested.AddInt(requestIdentity,1);
        if (success != true) {
            std::cout << "Could not prepare the request." << "\r\n";
            return;
        }

        i = i + 1;
    }

    const char *requestBody = xml.getXml();
    //  Explicit signing is used only for this fixed request so Content-MD5 survives.
    //  Rest sends it; AuthAws must NOT also be configured on this Rest instance.
    //  Sign this exact POST /?delete= request, including its UTF-8 body and MD5.
    //  Do not change signed headers, body, endpoint, or query after signing.
    CkStringBuilder host;
    host.Append(endpoint.getAsString());
    CkDateTime now;
    success = now.SetFromCurrentSystemTime();
    if (success != true) {
        std::cout << "Could not read system time." << "\r\n";
        return;
    }

    CkStringBuilder timestamp;
    timestamp.Append(now.getAsTimestamp(false));
    int removedDashes = timestamp.Replace("-","");
    int removedColons = timestamp.Replace(":","");
    const char *amzDate = timestamp.getAsString();
    const char *dateStamp = timestamp.getRange(0,8,false);
    CkCrypt2 crypt;
    crypt.put_Charset("utf-8");
    crypt.put_HashAlgorithm("md5");
    crypt.put_EncodingMode("base64");
    const char *contentMd5 = crypt.hashStringENC(requestBody);
    if (crypt.get_LastMethodSuccess() != true) {
        std::cout << "Could not hash delete body." << "\r\n";
        return;
    }

    crypt.put_HashAlgorithm("sha256");
    crypt.put_EncodingMode("hexlower");
    const char *payloadHash = crypt.hashStringENC(requestBody);
    if (crypt.get_LastMethodSuccess() != true) {
        std::cout << "Could not hash delete body." << "\r\n";
        return;
    }

    CkStringBuilder signedHeaders;
    signedHeaders.Append("content-md5;host;x-amz-content-sha256;x-amz-date");
    CkStringBuilder canonical;
    canonical.Append("POST\n/\ndelete=\ncontent-md5:");
    canonical.Append(contentMd5);
    canonical.Append("\nhost:");
    canonical.Append(host.getAsString());
    canonical.Append("\nx-amz-content-sha256:");
    canonical.Append(payloadHash);
    canonical.Append("\nx-amz-date:");
    canonical.Append(amzDate);
    canonical.Append("\n");
    if (credentials.HasMember("session_token") == true) {
        textCompare.Clear();
        textCompare.SetString(credentials.stringOf("session_token"));
        bool sameText5 = textCompare.ContentsEqual("",true);
        if (sameText5 != true) {
            signedHeaders.Append(";x-amz-security-token");
            canonical.Append("x-amz-security-token:");
            canonical.Append(credentials.stringOf("session_token"));
            canonical.Append("\n");
            success = rest.AddHeader("x-amz-security-token",credentials.stringOf("session_token"));
            if (success != true) {
                std::cout << "Could not prepare the request." << "\r\n";
                return;
            }

        }

    }

    canonical.Append("\n");
    canonical.Append(signedHeaders.getAsString());
    canonical.Append("\n");
    canonical.Append(payloadHash);
    const char *canonicalHash = crypt.hashStringENC(canonical.getAsString());
    if (crypt.get_LastMethodSuccess() != true) {
        std::cout << "Could not hash canonical request." << "\r\n";
        return;
    }

    CkStringBuilder scope;
    scope.Append(dateStamp);
    scope.Append("/");
    scope.Append(region);
    scope.Append("/s3/aws4_request");
    CkStringBuilder stringToSign;
    stringToSign.Append("AWS4-HMAC-SHA256\n");
    stringToSign.Append(amzDate);
    stringToSign.Append("\n");
    stringToSign.Append(scope.getAsString());
    stringToSign.Append("\n");
    stringToSign.Append(canonicalHash);
    CkStringBuilder initialKey;
    initialKey.Append("AWS4");
    initialKey.Append(credentials.stringOf("secret_key"));
    crypt.put_MacAlgorithm("hmac");
    success = crypt.SetMacKeyString(initialKey.getAsString());
    if (success != true) {
        std::cout << "Could not set signing key." << "\r\n";
        return;
    }

    const char *derivedKey = crypt.macStringENC(dateStamp);
    if (crypt.get_LastMethodSuccess() != true) {
        std::cout << "Could not derive date signing key." << "\r\n";
        return;
    }

    success = crypt.SetMacKeyEncoded(derivedKey,"hex");
    if (success != true) {
        std::cout << "Could not set derived signing key." << "\r\n";
        return;
    }

    derivedKey = crypt.macStringENC(region);
    if (crypt.get_LastMethodSuccess() != true) {
        std::cout << "Could not derive signing key." << "\r\n";
        return;
    }

    success = crypt.SetMacKeyEncoded(derivedKey,"hex");
    if (success != true) {
        std::cout << "Could not set derived signing key." << "\r\n";
        return;
    }

    derivedKey = crypt.macStringENC("s3");
    if (crypt.get_LastMethodSuccess() != true) {
        std::cout << "Could not derive signing key." << "\r\n";
        return;
    }

    success = crypt.SetMacKeyEncoded(derivedKey,"hex");
    if (success != true) {
        std::cout << "Could not set derived signing key." << "\r\n";
        return;
    }

    derivedKey = crypt.macStringENC("aws4_request");
    if (crypt.get_LastMethodSuccess() != true) {
        std::cout << "Could not derive signing key." << "\r\n";
        return;
    }

    success = crypt.SetMacKeyEncoded(derivedKey,"hex");
    if (success != true) {
        std::cout << "Could not set final signing key." << "\r\n";
        return;
    }

    const char *signature = crypt.macStringENC(stringToSign.getAsString());
    if (crypt.get_LastMethodSuccess() != true) {
        std::cout << "Could not sign delete request." << "\r\n";
        return;
    }

    CkStringBuilder authorization;
    authorization.Append("AWS4-HMAC-SHA256 Credential=");
    authorization.Append(credentials.stringOf("access_key"));
    authorization.Append("/");
    authorization.Append(scope.getAsString());
    authorization.Append(", SignedHeaders=");
    authorization.Append(signedHeaders.getAsString());
    authorization.Append(", Signature=");
    authorization.Append(signature);
    success = rest.AddHeader("Authorization",authorization.getAsString());
    if (success != true) {
        std::cout << "Could not prepare the request." << "\r\n";
        return;
    }

    success = rest.AddHeader("Content-MD5",contentMd5);
    if (success != true) {
        std::cout << "Could not prepare the request." << "\r\n";
        return;
    }

    success = rest.AddHeader("x-amz-content-sha256",payloadHash);
    if (success != true) {
        std::cout << "Could not prepare the request." << "\r\n";
        return;
    }

    success = rest.AddHeader("x-amz-date",amzDate);
    if (success != true) {
        std::cout << "Could not prepare the request." << "\r\n";
        return;
    }

    success = rest.AddQueryParam("delete","");
    if (success != true) {
        std::cout << "Could not prepare the request." << "\r\n";
        return;
    }

    const char *responseBody = rest.fullRequestString("POST","/",requestBody);
    if (rest.get_LastMethodSuccess() != true) {
        std::cout << "Request did not complete; inspect diagnostics privately." << "\r\n";
        return;
    }

    if (rest.get_ResponseStatusCode() != 200) {
        std::cout << "S3 HTTP status: " << rest.get_ResponseStatusCode() << "\r\n";
        success = xml.LoadXml(responseBody);
        textCompare.Clear();
        textCompare.SetString(xml.tag());
        bool sameText6 = textCompare.ContentsEqual("Error",true);
        if ((success == true) && (sameText6 == true)) {
            std::cout << "S3 error code: " << xml.getChildContent("Code") << "\r\n";
        }

        //  Keep signed headers, credentials, URLs, and full diagnostics private.
        //  A timeout may leave a write's outcome uncertain. Check before retrying.
        return;
    }

    success = xml.LoadXml(responseBody);
    if (success != true) {
        std::cout << "Expected well-formed XML." << "\r\n";
        return;
    }

    textCompare.Clear();
    textCompare.SetString(xml.tag());
    bool sameText7 = textCompare.ContentsEqual("DeleteResult",true);
    if (sameText7 != true) {
        std::cout << "Unexpected S3 response element; this is not a successful result." << "\r\n";
        return;
    }

    int deleted = xml.NumChildrenHavingTag("Deleted");
    int failed = xml.NumChildrenHavingTag("Error");
    if (deleted + failed != count) {
        std::cout << "Incomplete result: reconcile every requested object before retrying." << "\r\n";
        return;
    }

    CkHashtable received;
    int resultType = 0;
    while ((resultType < 2)) {
        const char *itemTag = "Deleted";
        int resultCount = deleted;
        if (resultType == 1) {
            itemTag = "Error";
            resultCount = failed;
        }

        int j = 0;
        while ((j < resultCount)) {
            xml.put_I(j);
            CkStringBuilder itemPath;
            success = itemPath.Append(itemTag);
            if (success != true) {
                std::cout << "Could not build text." << "\r\n";
                return;
            }

            success = itemPath.Append("[i]");
            if (success != true) {
                std::cout << "Could not build text." << "\r\n";
                return;
            }

            CkXml *item = xml.FindChild(itemPath.getAsString());
            if (xml.get_LastMethodSuccess() != true) {
                std::cout << "Missing deletion result entry." << "\r\n";
                return;
            }

            const char *resultKey = item->getChildContent("Key");
            const char *resultVersion = "";
            if (item->HasChildWithTag("VersionId") == true) {
                resultVersion = item->getChildContent("VersionId");
            }

            success = identity.UpdateString("key",resultKey);
            if (success != true) {
                std::cout << "Could not build saved state." << "\r\n";
                return;
            }

            success = identity.UpdateString("version",resultVersion);
            if (success != true) {
                std::cout << "Could not build saved state." << "\r\n";
                return;
            }

            const char *responseIdentity = identity.emit();
            if ((requested.Contains(responseIdentity) != true) || (received.Contains(responseIdentity) == true)) {
                std::cout << "Unexpected or duplicated deletion result; reconcile manually." << "\r\n";
                return;
            }

            success = received.AddInt(responseIdentity,1);
            if (success != true) {
                std::cout << "Could not prepare the request." << "\r\n";
                return;
            }

            std::cout << itemTag << ": " << resultKey << "\r\n";
            if (resultType == 1) {
                std::cout << "Error code: " << item->getChildContent("Code") << "\r\n";
            }

            delete item;
            j = j + 1;
        }

        resultType = resultType + 1;
    }

    if (failed > 0) {
        std::cout << "Batch has per-object failures. Do not retry successful entries." << "\r\n";
        return;
    }

    std::cout << "All requested deletions acknowledged." << "\r\n";
    }