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

Amazon S3: Download an Object into BinData

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.

For small objects that fit comfortably in memory. Use streaming for large or untrusted-size responses. The byte-array variant is for language bindings that expose native bytes; BinData is the portable alternative.

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 "CkXml.pb"
IncludeFile "CkStringBuilder.pb"
IncludeFile "CkRest.pb"
IncludeFile "CkBinData.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

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

    success = CkRest::ckReadRespBd(rest,data)
    If success <> 1
        Debug "Could not read download bytes."
        CkStringBuilder::ckDispose(textCompare)
        CkJsonObject::ckDispose(credentials)
        CkStringBuilder::ckDispose(endpoint)
        CkAuthAws::ckDispose(aws)
        CkRest::ckDispose(rest)
        CkSocket::ckDispose(connection)
        CkXml::ckDispose(xml)
        CkStringBuilder::ckDispose(objectPath)
        CkBinData::ckDispose(data)
        ProcedureReturn
    EndIf

    Debug "Downloaded bytes: " + Str(CkBinData::ckNumBytes(data))


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


    ProcedureReturn
EndProcedure