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

S3: Delete Multiple Objects and Check Per-Object Errors

See more S3 - HTTP Examples

Uses Chilkat.Http with Amazon S3 general purpose buckets and Signature Version 4. These examples do not cover directory buckets/S3 Express, access-point ARNs, Outposts, or other specialized endpoints. They target the commercial AWS partition; other partitions need their documented endpoint suffix.

Load private qa_data/aws/s3.json containing nonempty string fields access_key and secret_key, plus session_token for temporary credentials. Prefer short-lived role credentials. These samples do not discover AWS profiles or refresh credentials. Set the bucket's actual region and replace sample bucket names and object keys. TLS certificate verification is explicitly enabled. Keep detailed HTTP diagnostics private because they can contain credentials or presigned URLs.

Sends an explicit DeleteObjects request with Http.HttpStr and receives the original HttpResponse. XML APIs safely serialize up to 1,000 object identifiers. The request uses quiet mode; successful entries may be absent. HTTP 200 can still contain per-object errors, so every Error element is inspected before reporting success.

The sample uses Crypt2 to sign this fixed POST /?delete= request with SigV4, including Content-MD5, the SHA-256 payload hash, date, and optional session token. Keep the system clock accurate. Do not alter signed components after signing. This signing block is specific to this operation, not a general URL canonicalizer. See AWS header-signing rules.

Requires s3:DeleteObject, and s3:DeleteObjectVersion for explicit versions. Version-specific deletion is permanent. Without a version ID, a versioning-enabled bucket normally gains delete markers instead. Missing keys count as successful deletes. MFA Delete, retention, and legal holds may affect results. Retry only failed identifiers when appropriate, rather than repeating successful versioned deletes.

AWS reference

Chilkat Unicode C++ Downloads

Unicode C++
#include <CkStringBuilderW.h>
#include <CkJsonObjectW.h>
#include <CkHttpW.h>
#include <CkXmlW.h>
#include <CkDateTimeW.h>
#include <CkCrypt2W.h>
#include <CkHttpResponseW.h>

void ChilkatSample(void)
    {
    bool success = false;

    CkStringBuilderW stringCompare;
    //  This example requires the Chilkat API to have been previously unlocked.
    //  See Global Unlock Sample for sample code.
    //  Load private credentials; never put access keys or session tokens in source.
    CkJsonObjectW credentials;
    credentials.put_Strict(true);
    success = credentials.LoadFile(L"qa_data/aws/s3.json");
    if (success != true) {
        wprintf(L"Could not load private S3 credentials.\n");
        return;
    }

    stringCompare.SetString(credentials.stringOf(L"access_key"));
    bool stringMatch1 = stringCompare.ContentsEqual(L"",true);
    if ((credentials.JsonTypeOf(L"access_key") != 1) || (stringMatch1 == true)) {
        wprintf(L"Missing or invalid access_key.\n");
        return;
    }

    stringCompare.SetString(credentials.stringOf(L"secret_key"));
    bool stringMatch2 = stringCompare.ContentsEqual(L"",true);
    if ((credentials.JsonTypeOf(L"secret_key") != 1) || (stringMatch2 == true)) {
        wprintf(L"Missing or invalid secret_key.\n");
        return;
    }

    CkHttpW http;
    http.put_AwsAccessKey(credentials.stringOf(L"access_key"));
    http.put_AwsSecretKey(credentials.stringOf(L"secret_key"));
    if (credentials.HasMember(L"session_token") == true) {
        stringCompare.SetString(credentials.stringOf(L"session_token"));
        bool stringMatch3 = stringCompare.ContentsEqual(L"",true);
        if ((credentials.JsonTypeOf(L"session_token") != 1) || (stringMatch3 == true)) {
            wprintf(L"session_token must be a nonempty string when supplied.\n");
            return;
        }

        http.put_AwsSessionToken(credentials.stringOf(L"session_token"));
    }

    //  Current Chilkat uses SigV4 by default. Do not select deprecated SigV2.
    //  Set the actual bucket region, not the caller's location.
    const wchar_t *region = L"us-west-2";
    http.put_AwsRegion(region);
    CkStringBuilderW endpoint;
    endpoint.Append(L"s3.");
    endpoint.Append(region);
    endpoint.Append(L".amazonaws.com");
    http.put_AwsEndpoint(endpoint.getAsString());
    http.put_RequireSslCertVerify(true);
    http.put_FollowRedirects(false);
    //  A region redirect is not success. Correct the endpoint and signing region.
    const wchar_t *bucketName = L"your-bucket-name";
    CkXmlW deleteRequest;
    deleteRequest.put_Tag(L"Delete");
    deleteRequest.AddAttribute(L"xmlns",L"http://s3.amazonaws.com/doc/2006-03-01/");
    deleteRequest.UpdateChildContent(L"Quiet",L"true");
    //  XML APIs escape key text. Do NOT URL-encode keys in this XML body.
    deleteRequest.UpdateChildContent(L"Object[0]|Key",L"images/seahorse.jpg");
    deleteRequest.UpdateChildContent(L"Object[1]|Key",L"images/starfish.jpg");
    //  For permanent deletion of a specific version, add Object[i]|VersionId
    //  deliberately. Use separate XML elements, not an embedded string convention.
    if ((deleteRequest.NumChildrenHavingTag(L"Object") < 1) || (deleteRequest.NumChildrenHavingTag(L"Object") > 1000)) {
        wprintf(L"Use a batch of 1 to 1,000 object identifiers.\n");
        return;
    }

    const wchar_t *requestBody = deleteRequest.getXml();
    //  Sign this exact POST /?delete= request, including its UTF-8 body and MD5.
    //  Do not change signed headers, body, endpoint, or query after signing.
    CkStringBuilderW host;
    host.Append(bucketName);
    host.Append(L".");
    host.Append(endpoint.getAsString());
    CkDateTimeW now;
    success = now.SetFromCurrentSystemTime();
    if (success != true) {
        wprintf(L"Could not read system time.\n");
        return;
    }

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

    crypt.put_HashAlgorithm(L"sha256");
    crypt.put_EncodingMode(L"hexlower");
    const wchar_t *payloadHash = crypt.hashStringENC(requestBody);
    if (crypt.get_LastMethodSuccess() != true) {
        wprintf(L"Could not hash delete body.\n");
        return;
    }

    CkStringBuilderW signedHeaders;
    signedHeaders.Append(L"content-md5;host;x-amz-content-sha256;x-amz-date");
    CkStringBuilderW canonical;
    canonical.Append(L"POST\n/\ndelete=\ncontent-md5:");
    canonical.Append(contentMd5);
    canonical.Append(L"\nhost:");
    canonical.Append(host.getAsString());
    canonical.Append(L"\nx-amz-content-sha256:");
    canonical.Append(payloadHash);
    canonical.Append(L"\nx-amz-date:");
    canonical.Append(amzDate);
    canonical.Append(L"\n");
    if (credentials.HasMember(L"session_token") == true) {
        signedHeaders.Append(L";x-amz-security-token");
        canonical.Append(L"x-amz-security-token:");
        canonical.Append(credentials.stringOf(L"session_token"));
        canonical.Append(L"\n");
        http.SetRequestHeader(L"x-amz-security-token",credentials.stringOf(L"session_token"));
    }

    canonical.Append(L"\n");
    canonical.Append(signedHeaders.getAsString());
    canonical.Append(L"\n");
    canonical.Append(payloadHash);
    const wchar_t *canonicalHash = crypt.hashStringENC(canonical.getAsString());
    if (crypt.get_LastMethodSuccess() != true) {
        wprintf(L"Could not hash canonical request.\n");
        return;
    }

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

    const wchar_t *derivedKey = crypt.macStringENC(dateStamp);
    if (crypt.get_LastMethodSuccess() != true) {
        wprintf(L"Could not derive date signing key.\n");
        return;
    }

    success = crypt.SetMacKeyEncoded(derivedKey,L"hex");
    if (success != true) {
        wprintf(L"Could not set derived signing key.\n");
        return;
    }

    derivedKey = crypt.macStringENC(region);
    if (crypt.get_LastMethodSuccess() != true) {
        wprintf(L"Could not derive signing key.\n");
        return;
    }

    success = crypt.SetMacKeyEncoded(derivedKey,L"hex");
    if (success != true) {
        wprintf(L"Could not set derived signing key.\n");
        return;
    }

    derivedKey = crypt.macStringENC(L"s3");
    if (crypt.get_LastMethodSuccess() != true) {
        wprintf(L"Could not derive signing key.\n");
        return;
    }

    success = crypt.SetMacKeyEncoded(derivedKey,L"hex");
    if (success != true) {
        wprintf(L"Could not set derived signing key.\n");
        return;
    }

    derivedKey = crypt.macStringENC(L"aws4_request");
    if (crypt.get_LastMethodSuccess() != true) {
        wprintf(L"Could not derive signing key.\n");
        return;
    }

    success = crypt.SetMacKeyEncoded(derivedKey,L"hex");
    if (success != true) {
        wprintf(L"Could not set final signing key.\n");
        return;
    }

    const wchar_t *signature = crypt.macStringENC(stringToSign.getAsString());
    if (crypt.get_LastMethodSuccess() != true) {
        wprintf(L"Could not sign delete request.\n");
        return;
    }

    CkStringBuilderW authorization;
    authorization.Append(L"AWS4-HMAC-SHA256 Credential=");
    authorization.Append(credentials.stringOf(L"access_key"));
    authorization.Append(L"/");
    authorization.Append(scope.getAsString());
    authorization.Append(L", SignedHeaders=");
    authorization.Append(signedHeaders.getAsString());
    authorization.Append(L", Signature=");
    authorization.Append(signature);
    http.SetRequestHeader(L"Authorization",authorization.getAsString());
    http.SetRequestHeader(L"Content-MD5",contentMd5);
    http.SetRequestHeader(L"x-amz-content-sha256",payloadHash);
    http.SetRequestHeader(L"x-amz-date",amzDate);
    CkStringBuilderW requestUrl;
    requestUrl.Append(L"https://");
    requestUrl.Append(host.getAsString());
    requestUrl.Append(L"/?delete=");
    CkHttpResponseW response;
    success = http.HttpStr(L"POST",requestUrl.getAsString(),requestBody,L"utf-8",L"application/xml",response);
    if (success != true) {
        wprintf(L"Request failed (transport or S3 error). HTTP status: %d\n",http.get_LastStatus());
        //  Inspect LastErrorText privately. Do not log credentials or signed URLs.
        return;
    }

    if (response.get_StatusCode() != 200) {
        wprintf(L"Unexpected HTTP status: %d\n",response.get_StatusCode());
        return;
    }

    //  HTTP 200 can contain per-object errors. Inspect the actual XML body.
    CkXmlW xml;
    success = xml.LoadXml(response.bodyStr());
    if (success != true) {
        wprintf(L"Invalid XML response.\n");
        return;
    }

    stringCompare.SetString(xml.tag());
    bool stringMatch4 = stringCompare.ContentsEqual(L"DeleteResult",true);
    if (stringMatch4 != true) {
        wprintf(L"Unexpected XML response root.\n");
        return;
    }

    int failures = xml.NumChildrenHavingTag(L"Error");
    int i = 0;
    while ((i < failures)) {
        xml.put_I(i);
        wprintf(L"Failed key: %s\n",xml.getChildContent(L"Error[i]|Key"));
        wprintf(L"Error code: %s\n",xml.getChildContent(L"Error[i]|Code"));
        i = i + 1;
    }

    if (failures != 0) {
        wprintf(L"One or more objects were not deleted. Retry only appropriate failed identifiers.\n");
        return;
    }

    //  Quiet=true means success entries need not be returned.
    wprintf(L"Delete batch succeeded with no reported object errors.\n");
    }