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

Amazon S3: Create or Replace an Object Conditionally

See more S3 - REST Examples

Create mode sends If-None-Match: * to avoid replacing an existing current object. Replace mode sends the exact quoted ETag recorded by the caller using If-Match. Requires s3:PutObject; If-Match can also require s3:GetObject. There is no fallback to an unconditional write.

HTTP 412 means the precondition failed; 409 indicates a conflicting concurrent operation. Re-read and reconcile before a bounded retry. In a versioned bucket, conditions concern the current version; a current delete marker can allow create mode to succeed. ETags are opaque validators, not necessarily MD5 hashes, and do not implement a transaction across multiple keys. A lost response leaves the outcome uncertain.

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 PutObject reference

Chilkat PureBasic Downloads

PureBasic
IncludeFile "CkAuthAws.pb"
IncludeFile "CkJsonObject.pb"
IncludeFile "CkSocket.pb"
IncludeFile "CkXml.pb"
IncludeFile "CkStringBuilder.pb"
IncludeFile "CkRest.pb"

Procedure ChilkatExample()

    success.i = 0

    ;  StringBuilder compares text by value in every generated language.
    textCompare.i = CkStringBuilder::ckCreate()
    If textCompare.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    ;  Assumes Chilkat is unlocked. See Global Unlock Sample.
    success = 0
    ;  Private configuration, not a file in public web content or source control.
    ;  Load current IAM credentials authorized for the S3 operation.
    credentials.i = CkJsonObject::ckCreate()
    If credentials.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    CkJsonObject::setCkStrict(credentials, 1)
    success = CkJsonObject::ckLoadFile(credentials,"qa_data/aws/s3.json")
    If success <> 1
        Debug "Could not load private AWS credentials."
        CkStringBuilder::ckDispose(textCompare)
        CkJsonObject::ckDispose(credentials)
        ProcedureReturn
    EndIf

    CkStringBuilder::ckClear(textCompare)
    CkStringBuilder::ckSetString(textCompare,CkJsonObject::ckStringOf(credentials,"access_key"))
    sameText1.i = CkStringBuilder::ckContentsEqual(textCompare,"",1)
    If (CkJsonObject::ckJsonTypeOf(credentials,"access_key") <> 1) OR (sameText1 = 1)
        Debug "Missing or invalid access_key."
        CkStringBuilder::ckDispose(textCompare)
        CkJsonObject::ckDispose(credentials)
        ProcedureReturn
    EndIf

    CkStringBuilder::ckClear(textCompare)
    CkStringBuilder::ckSetString(textCompare,CkJsonObject::ckStringOf(credentials,"secret_key"))
    sameText2.i = CkStringBuilder::ckContentsEqual(textCompare,"",1)
    If (CkJsonObject::ckJsonTypeOf(credentials,"secret_key") <> 1) OR (sameText2 = 1)
        Debug "Missing or invalid secret_key."
        CkStringBuilder::ckDispose(textCompare)
        CkJsonObject::ckDispose(credentials)
        ProcedureReturn
    EndIf

    ;  General purpose bucket in the commercial AWS partition.
    region.s = "us-west-2"
    bucketName.s = "amzn-s3-demo-bucket"
    endpoint.i = CkStringBuilder::ckCreate()
    If endpoint.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    success = CkStringBuilder::ckAppend(endpoint,bucketName)
    If success <> 1
        Debug "Could not build text."
        CkStringBuilder::ckDispose(textCompare)
        CkJsonObject::ckDispose(credentials)
        CkStringBuilder::ckDispose(endpoint)
        ProcedureReturn
    EndIf

    success = CkStringBuilder::ckAppend(endpoint,".")
    If success <> 1
        Debug "Could not build text."
        CkStringBuilder::ckDispose(textCompare)
        CkJsonObject::ckDispose(credentials)
        CkStringBuilder::ckDispose(endpoint)
        ProcedureReturn
    EndIf

    success = CkStringBuilder::ckAppend(endpoint,"s3.")
    If success <> 1
        Debug "Could not build text."
        CkStringBuilder::ckDispose(textCompare)
        CkJsonObject::ckDispose(credentials)
        CkStringBuilder::ckDispose(endpoint)
        ProcedureReturn
    EndIf

    success = CkStringBuilder::ckAppend(endpoint,region)
    If success <> 1
        Debug "Could not build text."
        CkStringBuilder::ckDispose(textCompare)
        CkJsonObject::ckDispose(credentials)
        CkStringBuilder::ckDispose(endpoint)
        ProcedureReturn
    EndIf

    success = CkStringBuilder::ckAppend(endpoint,".amazonaws.com")
    If success <> 1
        Debug "Could not build text."
        CkStringBuilder::ckDispose(textCompare)
        CkJsonObject::ckDispose(credentials)
        CkStringBuilder::ckDispose(endpoint)
        ProcedureReturn
    EndIf

    aws.i = CkAuthAws::ckCreate()
    If aws.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    CkAuthAws::setCkAccessKey(aws, CkJsonObject::ckStringOf(credentials,"access_key"))
    CkAuthAws::setCkSecretKey(aws, CkJsonObject::ckStringOf(credentials,"secret_key"))
    CkAuthAws::setCkRegion(aws, region)
    CkAuthAws::setCkServiceName(aws, "s3")
    CkAuthAws::setCkSignatureVersion(aws, 4)
    rest.i = CkRest::ckCreate()
    If rest.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    CkRest::setCkConnectTimeoutMs(rest, 20000)
    CkRest::setCkIdleTimeoutMs(rest, 60000)
    success = CkRest::ckSetAuthAws(rest,aws)
    If success <> 1
        Debug "Could not configure AWS signing."
        CkStringBuilder::ckDispose(textCompare)
        CkJsonObject::ckDispose(credentials)
        CkStringBuilder::ckDispose(endpoint)
        CkAuthAws::ckDispose(aws)
        CkRest::ckDispose(rest)
        ProcedureReturn
    EndIf

    ;  Temporary credentials require this token in every signed query.
    ;  Keep request URLs private. Do not clear this parameter between requests.
    If CkJsonObject::ckHasMember(credentials,"session_token") = 1
        If CkJsonObject::ckJsonTypeOf(credentials,"session_token") <> 1
            Debug "session_token must be a string."
            CkStringBuilder::ckDispose(textCompare)
            CkJsonObject::ckDispose(credentials)
            CkStringBuilder::ckDispose(endpoint)
            CkAuthAws::ckDispose(aws)
            CkRest::ckDispose(rest)
            ProcedureReturn
        EndIf

        CkStringBuilder::ckClear(textCompare)
        CkStringBuilder::ckSetString(textCompare,CkJsonObject::ckStringOf(credentials,"session_token"))
        sameText3.i = CkStringBuilder::ckContentsEqual(textCompare,"",1)
        If sameText3 <> 1
            success = CkRest::ckAddQueryParam(rest,"X-Amz-Security-Token",CkJsonObject::ckStringOf(credentials,"session_token"))
            If success <> 1
                Debug "Could not prepare the request."
                CkStringBuilder::ckDispose(textCompare)
                CkJsonObject::ckDispose(credentials)
                CkStringBuilder::ckDispose(endpoint)
                CkAuthAws::ckDispose(aws)
                CkRest::ckDispose(rest)
                ProcedureReturn
            EndIf

        EndIf

    EndIf

    ;  Connect to the SAME hostname used for TLS verification and request signing.
    connection.i = CkSocket::ckCreate()
    If connection.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    CkSocket::setCkRequireSslCertVerify(connection, 1)
    CkSocket::setCkMaxReadIdleMs(connection, 60000)
    CkSocket::setCkMaxSendIdleMs(connection, 60000)
    success = CkSocket::ckConnect(connection,CkStringBuilder::ckGetAsString(endpoint),443,1,20000)
    If success <> 1
        Debug "TLS connection failed; inspect diagnostics privately."
        CkStringBuilder::ckDispose(textCompare)
        CkJsonObject::ckDispose(credentials)
        CkStringBuilder::ckDispose(endpoint)
        CkAuthAws::ckDispose(aws)
        CkRest::ckDispose(rest)
        CkSocket::ckDispose(connection)
        ProcedureReturn
    EndIf

    success = CkRest::ckUseConnection(rest,connection,1)
    If success <> 1
        Debug "Could not attach the TLS connection."
        CkStringBuilder::ckDispose(textCompare)
        CkJsonObject::ckDispose(credentials)
        CkStringBuilder::ckDispose(endpoint)
        CkAuthAws::ckDispose(aws)
        CkRest::ckDispose(rest)
        CkSocket::ckDispose(connection)
        ProcedureReturn
    EndIf

    xml.i = CkXml::ckCreate()
    If xml.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    CkXml::setCkStrict(xml, 1)
    ;  Supply an unencoded object key, not a URL. Preserve slashes in the key.
    objectKey.s = "documents/example.txt"
    objectPath.i = CkStringBuilder::ckCreate()
    If objectPath.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    success = CkStringBuilder::ckAppend(objectPath,objectKey)
    If success <> 1
        Debug "Could not build text."
        CkStringBuilder::ckDispose(textCompare)
        CkJsonObject::ckDispose(credentials)
        CkStringBuilder::ckDispose(endpoint)
        CkAuthAws::ckDispose(aws)
        CkRest::ckDispose(rest)
        CkSocket::ckDispose(connection)
        CkXml::ckDispose(xml)
        CkStringBuilder::ckDispose(objectPath)
        ProcedureReturn
    EndIf

    success = CkStringBuilder::ckEncode(objectPath,"url_rfc3986","utf-8")
    If success <> 1
        Debug "Could not encode the object key."
        CkStringBuilder::ckDispose(textCompare)
        CkJsonObject::ckDispose(credentials)
        CkStringBuilder::ckDispose(endpoint)
        CkAuthAws::ckDispose(aws)
        CkRest::ckDispose(rest)
        CkSocket::ckDispose(connection)
        CkXml::ckDispose(xml)
        CkStringBuilder::ckDispose(objectPath)
        ProcedureReturn
    EndIf

    restoredSlashes.i = CkStringBuilder::ckReplace(objectPath,"%2F","/")
    success = CkStringBuilder::ckPrepend(objectPath,"/")
    If success <> 1
        Debug "Could not prepare the request."
        CkStringBuilder::ckDispose(textCompare)
        CkJsonObject::ckDispose(credentials)
        CkStringBuilder::ckDispose(endpoint)
        CkAuthAws::ckDispose(aws)
        CkRest::ckDispose(rest)
        CkSocket::ckDispose(connection)
        CkXml::ckDispose(xml)
        CkStringBuilder::ckDispose(objectPath)
        ProcedureReturn
    EndIf

    operation.s = "create"
    ;  For replace, use the exact quoted ETag from the version you intend to update.
    expectedEtag.s = "YOUR_QUOTED_ETAG"
    CkStringBuilder::ckClear(textCompare)
    CkStringBuilder::ckSetString(textCompare,operation)
    sameText4.i = CkStringBuilder::ckContentsEqual(textCompare,"create",1)
    If sameText4 = 1
        success = CkRest::ckAddHeader(rest,"If-None-Match","*")
        If success <> 1
            Debug "Could not prepare the request."
            CkStringBuilder::ckDispose(textCompare)
            CkJsonObject::ckDispose(credentials)
            CkStringBuilder::ckDispose(endpoint)
            CkAuthAws::ckDispose(aws)
            CkRest::ckDispose(rest)
            CkSocket::ckDispose(connection)
            CkXml::ckDispose(xml)
            CkStringBuilder::ckDispose(objectPath)
            ProcedureReturn
        EndIf

    Else
        CkStringBuilder::ckClear(textCompare)
        CkStringBuilder::ckSetString(textCompare,operation)
        sameText5.i = CkStringBuilder::ckContentsEqual(textCompare,"replace",1)
        If sameText5 <> 1
            Debug "Choose create or replace."
            CkStringBuilder::ckDispose(textCompare)
            CkJsonObject::ckDispose(credentials)
            CkStringBuilder::ckDispose(endpoint)
            CkAuthAws::ckDispose(aws)
            CkRest::ckDispose(rest)
            CkSocket::ckDispose(connection)
            CkXml::ckDispose(xml)
            CkStringBuilder::ckDispose(objectPath)
            ProcedureReturn
        EndIf

        success = CkRest::ckAddHeader(rest,"If-Match",expectedEtag)
        If success <> 1
            Debug "Could not prepare the request."
            CkStringBuilder::ckDispose(textCompare)
            CkJsonObject::ckDispose(credentials)
            CkStringBuilder::ckDispose(endpoint)
            CkAuthAws::ckDispose(aws)
            CkRest::ckDispose(rest)
            CkSocket::ckDispose(connection)
            CkXml::ckDispose(xml)
            CkStringBuilder::ckDispose(objectPath)
            ProcedureReturn
        EndIf

    EndIf

    success = CkRest::ckAddHeader(rest,"Content-Type","text/plain; charset=utf-8")
    If success <> 1
        Debug "Could not prepare the request."
        CkStringBuilder::ckDispose(textCompare)
        CkJsonObject::ckDispose(credentials)
        CkStringBuilder::ckDispose(endpoint)
        CkAuthAws::ckDispose(aws)
        CkRest::ckDispose(rest)
        CkSocket::ckDispose(connection)
        CkXml::ckDispose(xml)
        CkStringBuilder::ckDispose(objectPath)
        ProcedureReturn
    EndIf

    responseBody.s = CkRest::ckFullRequestString(rest,"PUT",CkStringBuilder::ckGetAsString(objectPath),"Updated text." + Chr(10))
    If CkRest::ckLastMethodSuccess(rest) <> 1
        Debug "Write outcome is uncertain; inspect the object before retrying."
        CkStringBuilder::ckDispose(textCompare)
        CkJsonObject::ckDispose(credentials)
        CkStringBuilder::ckDispose(endpoint)
        CkAuthAws::ckDispose(aws)
        CkRest::ckDispose(rest)
        CkSocket::ckDispose(connection)
        CkXml::ckDispose(xml)
        CkStringBuilder::ckDispose(objectPath)
        ProcedureReturn
    EndIf

    If CkRest::ckResponseStatusCode(rest) = 412
        Debug "Precondition failed; the requested write was not applied."
        CkStringBuilder::ckDispose(textCompare)
        CkJsonObject::ckDispose(credentials)
        CkStringBuilder::ckDispose(endpoint)
        CkAuthAws::ckDispose(aws)
        CkRest::ckDispose(rest)
        CkSocket::ckDispose(connection)
        CkXml::ckDispose(xml)
        CkStringBuilder::ckDispose(objectPath)
        ProcedureReturn
    EndIf

    If CkRest::ckResponseStatusCode(rest) = 409
        Debug "Concurrent request conflict. Re-read state and apply a bounded retry policy."
        CkStringBuilder::ckDispose(textCompare)
        CkJsonObject::ckDispose(credentials)
        CkStringBuilder::ckDispose(endpoint)
        CkAuthAws::ckDispose(aws)
        CkRest::ckDispose(rest)
        CkSocket::ckDispose(connection)
        CkXml::ckDispose(xml)
        CkStringBuilder::ckDispose(objectPath)
        ProcedureReturn
    EndIf

    If CkRest::ckResponseStatusCode(rest) <> 200
        Debug "S3 HTTP status: " + Str(CkRest::ckResponseStatusCode(rest))
        success = CkXml::ckLoadXml(xml,responseBody)
        CkStringBuilder::ckClear(textCompare)
        CkStringBuilder::ckSetString(textCompare,CkXml::ckTag(xml))
        sameText6.i = CkStringBuilder::ckContentsEqual(textCompare,"Error",1)
        If (success = 1) AND (sameText6 = 1)
            Debug "S3 error code: " + CkXml::ckGetChildContent(xml,"Code")
        EndIf

        ;  Keep signed headers, credentials, URLs, and full diagnostics private.
        ;  A timeout may leave a write's outcome uncertain. Check before retrying.
        CkStringBuilder::ckDispose(textCompare)
        CkJsonObject::ckDispose(credentials)
        CkStringBuilder::ckDispose(endpoint)
        CkAuthAws::ckDispose(aws)
        CkRest::ckDispose(rest)
        CkSocket::ckDispose(connection)
        CkXml::ckDispose(xml)
        CkStringBuilder::ckDispose(objectPath)
        ProcedureReturn
    EndIf

    Debug "Conditional upload succeeded."
    Debug "ETag: " + CkRest::ckResponseHdrByName(rest,"ETag")


    CkStringBuilder::ckDispose(textCompare)
    CkJsonObject::ckDispose(credentials)
    CkStringBuilder::ckDispose(endpoint)
    CkAuthAws::ckDispose(aws)
    CkRest::ckDispose(rest)
    CkSocket::ckDispose(connection)
    CkXml::ckDispose(xml)
    CkStringBuilder::ckDispose(objectPath)


    ProcedureReturn
EndProcedure