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

Amazon S3: Stream an Object Download to a File

See more S3 - REST Examples

Download object bytes with GetObject after checking response headers. Requires s3:GetObject, and potentially kms:Decrypt. Archived objects may need restoration first. HTTP 403 can mean insufficient permission, including a missing object when ListBucket is not allowed; it does not prove existence.

The output is streamed to a new staging file. Publish or rename it only after successful completion. Do not treat a partially written file as complete.

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

Chilkat PureBasic Downloads

PureBasic
IncludeFile "CkAuthAws.pb"
IncludeFile "CkJsonObject.pb"
IncludeFile "CkSocket.pb"
IncludeFile "CkFileAccess.pb"
IncludeFile "CkXml.pb"
IncludeFile "CkStream.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

    success = CkRest::ckSendReqNoBody(rest,"GET",CkStringBuilder::ckGetAsString(objectPath))
    If success <> 1
        Debug "Could not send download 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

    statusCode.i = CkRest::ckReadResponseHeader(rest)
    If statusCode < 0
        Debug "Could not read download headers."
        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 statusCode <> 200
        Debug "Download HTTP status: " + Str(statusCode)
        errorBody.s = CkRest::ckReadRespBodyString(rest)
        If CkRest::ckLastMethodSuccess(rest) = 1
            success = CkXml::ckLoadXml(xml,errorBody)
            CkStringBuilder::ckClear(textCompare)
            CkStringBuilder::ckSetString(textCompare,CkXml::ckTag(xml))
            sameText4.i = CkStringBuilder::ckContentsEqual(textCompare,"Error",1)
            If (success = 1) AND (sameText4 = 1)
                Debug "S3 error code: " + CkXml::ckGetChildContent(xml,"Code")
            EndIf

        EndIf

        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

    ;  Use a new staging filename. A failed transfer can leave a partial file.
    files.i = CkFileAccess::ckCreate()
    If files.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    If (CkFileAccess::ckFileExists(files,"s3-download.part") = 1) OR (CkFileAccess::ckFileExists(files,"s3-download.json") = 1)
        Debug "A staging file or checkpoint already exists; choose new output paths."
        CkStringBuilder::ckDispose(textCompare)
        CkJsonObject::ckDispose(credentials)
        CkStringBuilder::ckDispose(endpoint)
        CkAuthAws::ckDispose(aws)
        CkRest::ckDispose(rest)
        CkSocket::ckDispose(connection)
        CkXml::ckDispose(xml)
        CkStringBuilder::ckDispose(objectPath)
        CkFileAccess::ckDispose(files)
        ProcedureReturn
    EndIf

    ;  Save the original validator and length BEFORE reading the body so a failed
    ;  download can be continued by the resume example.
    originalEtag.s = CkRest::ckResponseHdrByName(rest,"ETag")
    CkStringBuilder::ckClear(textCompare)
    CkStringBuilder::ckSetString(textCompare,originalEtag)
    sameText5.i = CkStringBuilder::ckContentsEqual(textCompare,"",1)
    If (CkRest::ckLastMethodSuccess(rest) <> 1) OR (sameText5 = 1)
        Debug "Missing object 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)
        CkFileAccess::ckDispose(files)
        ProcedureReturn
    EndIf

    originalSize.s = CkRest::ckResponseHdrByName(rest,"Content-Length")
    CkStringBuilder::ckClear(textCompare)
    CkStringBuilder::ckSetString(textCompare,originalSize)
    sameText6.i = CkStringBuilder::ckContentsEqual(textCompare,"",1)
    If (CkRest::ckLastMethodSuccess(rest) <> 1) OR (sameText6 = 1)
        Debug "Missing object length."
        CkStringBuilder::ckDispose(textCompare)
        CkJsonObject::ckDispose(credentials)
        CkStringBuilder::ckDispose(endpoint)
        CkAuthAws::ckDispose(aws)
        CkRest::ckDispose(rest)
        CkSocket::ckDispose(connection)
        CkXml::ckDispose(xml)
        CkStringBuilder::ckDispose(objectPath)
        CkFileAccess::ckDispose(files)
        ProcedureReturn
    EndIf

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

    success = CkJsonObject::ckUpdateString(checkpoint,"bucket",bucketName)
    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)
        CkFileAccess::ckDispose(files)
        CkJsonObject::ckDispose(checkpoint)
        ProcedureReturn
    EndIf

    success = CkJsonObject::ckUpdateString(checkpoint,"key",objectKey)
    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)
        CkFileAccess::ckDispose(files)
        CkJsonObject::ckDispose(checkpoint)
        ProcedureReturn
    EndIf

    success = CkJsonObject::ckUpdateString(checkpoint,"region",region)
    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)
        CkFileAccess::ckDispose(files)
        CkJsonObject::ckDispose(checkpoint)
        ProcedureReturn
    EndIf

    success = CkJsonObject::ckUpdateString(checkpoint,"etag",originalEtag)
    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)
        CkFileAccess::ckDispose(files)
        CkJsonObject::ckDispose(checkpoint)
        ProcedureReturn
    EndIf

    success = CkJsonObject::ckUpdateString(checkpoint,"total_size",originalSize)
    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)
        CkFileAccess::ckDispose(files)
        CkJsonObject::ckDispose(checkpoint)
        ProcedureReturn
    EndIf

    success = CkJsonObject::ckWriteFile(checkpoint,"s3-download.json")
    If success <> 1
        Debug "Could not save the resume checkpoint."
        CkStringBuilder::ckDispose(textCompare)
        CkJsonObject::ckDispose(credentials)
        CkStringBuilder::ckDispose(endpoint)
        CkAuthAws::ckDispose(aws)
        CkRest::ckDispose(rest)
        CkSocket::ckDispose(connection)
        CkXml::ckDispose(xml)
        CkStringBuilder::ckDispose(objectPath)
        CkFileAccess::ckDispose(files)
        CkJsonObject::ckDispose(checkpoint)
        ProcedureReturn
    EndIf

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

    CkStream::setCkSinkFile(output, "s3-download.part")
    CkStream::setCkSinkFileAppend(output, 0)
    success = CkRest::ckReadRespBodyStream(rest,output,1)
    If success <> 1
        Debug "Download incomplete; retain the partial file and checkpoint for the resume example."
        CkStringBuilder::ckDispose(textCompare)
        CkJsonObject::ckDispose(credentials)
        CkStringBuilder::ckDispose(endpoint)
        CkAuthAws::ckDispose(aws)
        CkRest::ckDispose(rest)
        CkSocket::ckDispose(connection)
        CkXml::ckDispose(xml)
        CkStringBuilder::ckDispose(objectPath)
        CkFileAccess::ckDispose(files)
        CkJsonObject::ckDispose(checkpoint)
        CkStream::ckDispose(output)
        ProcedureReturn
    EndIf

    downloadedSize.s = CkFileAccess::ckFileSizeStr(files,"s3-download.part")
    CkStringBuilder::ckClear(textCompare)
    CkStringBuilder::ckSetString(textCompare,downloadedSize)
    sameText7.i = CkStringBuilder::ckContentsEqual(textCompare,originalSize,1)
    If (CkFileAccess::ckLastMethodSuccess(files) <> 1) OR (sameText7 <> 1)
        Debug "Downloaded length does not match the original response."
        CkStringBuilder::ckDispose(textCompare)
        CkJsonObject::ckDispose(credentials)
        CkStringBuilder::ckDispose(endpoint)
        CkAuthAws::ckDispose(aws)
        CkRest::ckDispose(rest)
        CkSocket::ckDispose(connection)
        CkXml::ckDispose(xml)
        CkStringBuilder::ckDispose(objectPath)
        CkFileAccess::ckDispose(files)
        CkJsonObject::ckDispose(checkpoint)
        CkStream::ckDispose(output)
        ProcedureReturn
    EndIf

    Debug "Download complete: s3-download.part"


    CkStringBuilder::ckDispose(textCompare)
    CkJsonObject::ckDispose(credentials)
    CkStringBuilder::ckDispose(endpoint)
    CkAuthAws::ckDispose(aws)
    CkRest::ckDispose(rest)
    CkSocket::ckDispose(connection)
    CkXml::ckDispose(xml)
    CkStringBuilder::ckDispose(objectPath)
    CkFileAccess::ckDispose(files)
    CkJsonObject::ckDispose(checkpoint)
    CkStream::ckDispose(output)


    ProcedureReturn
EndProcedure