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

S3: Download a Specific Object Version

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.

Downloads the exact key to an unused temporary path, requires HTTP 200, compares the local byte count with Content-Length, and renames only after success. Create the output directory first. Interrupted or failed downloads are not promoted to the final path. This is not a resumable download and does not independently verify an S3 checksum; ETag must not be assumed to be MD5.

Requires s3:GetObject, or s3:GetObjectVersion for a specified version, plus applicable KMS permissions. Archived S3 Glacier Flexible Retrieval or Deep Archive objects must be restored before reading; a restoration request does not immediately make them downloadable. Use the original key without adding a leading slash.

The opaque version ID is URL-encoded as a query value, not concatenated unescaped. A delete marker is not downloadable object content. AwsSubResources belongs to this Http instance; clear it before reusing the instance for requests that should not select the same version.

AWS reference

Chilkat Ruby Downloads

Ruby
require 'chilkat'

success = false

stringCompare = Chilkat::CkStringBuilder.new()
#  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.
credentials = Chilkat::CkJsonObject.new()
credentials.put_Strict(true)
success = credentials.LoadFile("qa_data/aws/s3.json")
if (success != true)
    print "Could not load private S3 credentials." + "\n";
    exit
end

stringCompare.SetString(credentials.stringOf("access_key"))
stringMatch1 = stringCompare.ContentsEqual("",true)
if ((credentials.JsonTypeOf("access_key") != 1) or (stringMatch1 == true))
    print "Missing or invalid access_key." + "\n";
    exit
end

stringCompare.SetString(credentials.stringOf("secret_key"))
stringMatch2 = stringCompare.ContentsEqual("",true)
if ((credentials.JsonTypeOf("secret_key") != 1) or (stringMatch2 == true))
    print "Missing or invalid secret_key." + "\n";
    exit
end

http = Chilkat::CkHttp.new()
http.put_AwsAccessKey(credentials.stringOf("access_key"))
http.put_AwsSecretKey(credentials.stringOf("secret_key"))
if (credentials.HasMember("session_token") == true)
    stringCompare.SetString(credentials.stringOf("session_token"))
    stringMatch3 = stringCompare.ContentsEqual("",true)
    if ((credentials.JsonTypeOf("session_token") != 1) or (stringMatch3 == true))
        print "session_token must be a nonempty string when supplied." + "\n";
        exit
    end

    http.put_AwsSessionToken(credentials.stringOf("session_token"))
end

#  Current Chilkat uses SigV4 by default. Do not select deprecated SigV2.
#  Set the actual bucket region, not the caller's location.
region = "us-west-2"
http.put_AwsRegion(region)
endpoint = Chilkat::CkStringBuilder.new()
endpoint.Append("s3.")
endpoint.Append(region)
endpoint.Append(".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.
bucketName = "your-bucket-name"
#  A leading slash is part of a key. Do not add one to imitate a file path.
objectName = "images/seahorse.jpg"

#  Start with the original key. Encode once and retain '/' path separators.
#  This also protects a literal "%2F" from being interpreted as a slash.
keyPath = Chilkat::CkStringBuilder.new()
keyPath.Append(http.urlEncode(objectName))
slashCount = keyPath.ReplaceNoCase("%2f","/")
encodedKey = keyPath.getAsString()
versionId = "YOUR_VERSION_ID"
subresource = Chilkat::CkStringBuilder.new()
encodedVersion = Chilkat::CkStringBuilder.new()
encodedVersion.Append(versionId)
subresource.Append("versionId=")
subresource.Append(encodedVersion.getEncoded("url","utf-8"))
http.put_AwsSubResources(subresource.getAsString())
files = Chilkat::CkFileAccess.new()
finalPath = "qa_output/seahorse.jpg"
partialPath = "qa_output/seahorse.jpg.part"
if ((files.FileExists(finalPath) == true) or (files.FileExists(partialPath) == true))
    print "Choose unused output paths before downloading." + "\n";
    exit
end

success = http.S3_DownloadFile(bucketName,encodedKey,partialPath)
if (success != true)
    print "Request failed (transport or S3 error). HTTP status: " + http.get_LastStatus().to_s() + "\n";
    #  Inspect LastErrorText privately. Do not log credentials or signed URLs.
    exit
end

if (http.get_LastStatus() != 200)
    print "Unexpected HTTP status: " + http.get_LastStatus().to_s() + "\n";
    exit
end

headers = Chilkat::CkMime.new()
success = headers.LoadMime(http.lastResponseHeader())
if (success != true)
    print "Could not parse download headers; keep the .part file." + "\n";
    exit
end

expectedSize = headers.getHeaderField("Content-Length")
stringCompare.SetString(expectedSize)
stringMatch4 = stringCompare.ContentsEqual("",true)
if ((headers.get_LastMethodSuccess() != true) or (stringMatch4 == true))
    print "Missing Content-Length; keep the .part file." + "\n";
    exit
end

actualSize = files.fileSizeStr(partialPath)
stringCompare.SetString(actualSize)
stringMatch5 = stringCompare.ContentsEqual(expectedSize,true)
if ((files.get_LastMethodSuccess() != true) or (stringMatch5 != true))
    print "Downloaded byte count mismatch; keep the .part file." + "\n";
    exit
end

success = files.FileRename(partialPath,finalPath)
if (success != true)
    print "Downloaded file remains at the .part path; rename failed." + "\n";
    exit
end

print "File download succeeded; byte count verified." + "\n";