Amazon S3 (Chilkat.Rest) API Guide

Use Chilkat.Rest to make signed Amazon S3 requests, manage buckets and objects, and stream uploads and downloads. This guide explains the request workflow and links to 37 complete examples covering listing, transfers, multipart uploads, versions, checksums, encryption, and object management.

Before making requests

The linked examples require Chilkat 11.6.0 or later and an unlocked library. They target general purpose S3 buckets in the commercial AWS partition. Directory buckets (S3 Express), access points, Outposts, and other AWS partitions need their own endpoint and authentication handling. For the alternative interface with S3 convenience methods, see the S3 (Chilkat.Http) API Guide.

Load current IAM credentials from a private qa_data/aws/s3.json file with nonempty string fields access_key and secret_key, plus session_token for temporary credentials. Prefer short-lived role credentials and permissions appropriate to each operation. The examples explicitly read this file; they do not discover AWS profiles, obtain credentials, or refresh expired sessions. Keep it outside public web content and source control. Replace the sample bucket, region, object keys, IDs, and local paths before running.

How a signed Rest request works

Rest exposes the HTTP method, resource path, query parameters, headers, and body. Most examples attach an AuthAws object with SetAuthAws; Chilkat then signs each outgoing request. See the Rest reference and AuthAws reference.

From S3 request components to Chilkat.Rest
StepConfiguration or call
Configure signingSet AuthAws.AccessKey, SecretKey, Region, ServiceName = "s3", and SignatureVersion = 4, then call Rest.SetAuthAws.
Connect over HTTPSConnect a Socket to the regional hostname on port 443 with RequireSslCertVerify enabled. Attach it with Rest.UseConnection. The connection hostname must agree with the signed host.
Describe the requestPass the encoded resource path to the request method. Use AddQueryParam for query values and AddHeader for headers. Temporary credentials in these automatic-signing examples use the signed X-Amz-Security-Token query parameter.
Send a bodyFullRequestString sends text or XML; FullRequestBd sends BinData; FullRequestStream reads from a Stream. These full-request methods also read the response.
Inspect before downloadingUse SendReqNoBody and ReadResponseHeader, then check the status and headers before reading the body into a stream or BinData.
Validate the resultCheck transport success separately from ResponseStatusCode. Parse XML when the operation returns XML, including errors embedded in HTTP 200 responses. HEAD responses have no body.

Rest query parameters and headers remain on the object until removed. Between operations, remove parameters such as uploads, uploadId, or attributes and headers that no longer apply. Preserve the session token on every automatically signed request. When using AuthAws.PrecomputedSha256, clear or replace it before sending different bytes. Keep signed request URLs and full diagnostics private.

The bulk-delete example is a deliberate exception to automatic signing: it constructs SigV4 with Crypt2 and sends the signed request through Rest so the required Content-MD5 header is preserved. Its signing block is specific to the demonstrated request. The presigned-URL example uses an Http helper to sign locally and sends no network request.

An S3 object key is a case-sensitive name, not a filesystem path. The examples encode the original UTF-8 key once while preserving slash separators. A literal percent sign must remain distinguishable from an already encoded character; do not encode a pre-encoded key again or normalize it as a local path. Pass opaque query values through AddQueryParam. Keep version IDs, upload IDs, ETags, continuation tokens, and large byte counts as strings.

Buckets, Regions and Listing Objects

Start with Configure Rest for a Bucket Region. Use the bucket's actual region in both the signing scope and endpoint, typically bucket-name.s3.us-west-2.amazonaws.com. The examples use bucket names without dots for virtual-hosted TLS; the path-style example demonstrates the regional alternative for dotted names. Region discovery uses HeadBucket and its x-amz-bucket-region response header. A returned region does not itself establish access to the bucket. See HeadBucket.

Bucket creation sends a matching LocationConstraint outside us-east-1; that region uses an empty request body. The policy examples retrieve JSON or replace the entire policy with a reviewed local document. Replacement is not a merge. Preserve required statements and review the access effects before applying the new document.

Account bucket listing and object listing follow their continuation tokens. ListObjectsV2 returns up to 1,000 entries per response; process pages until IsTruncated is false, not merely until a page is empty. With encoding-type=url, decode returned keys once and keep continuation tokens opaque. The examples detect repeated/missing tokens and stop with an incomplete-result message at their page bound. Pagination does not create a snapshot of a changing bucket. See ListObjectsV2.

Version listing includes both data versions and delete markers. It continues with the key-marker and version-ID-marker pair. Preserve both values; a key alone is insufficient to continue through its versions. Use this listing to obtain the specific version or marker required by the recovery example. See ListObjectVersions.

Uploading

Choose the source type that matches the application: UTF-8 text, binary data already in BinData, or a file streamed from disk. For a streamed upload, precompute the file's hexadecimal SHA-256 in a separate pass and set AuthAws.PrecomputedSha256. Keep the file unchanged while hashing and sending. This avoids loading the whole file merely to calculate the signature. Use multipart upload when the object exceeds the single-PUT limit or when dividing work into parts is useful.

The Expect: 100-continue example allows the service to reject a request before its body is sent. It is still one PUT, not multipart upload or an automatic retry mechanism. An ordinary upload can replace an unversioned object or create a new version. The conditional example uses If-None-Match: * for create-only behavior, or the exact quoted ETag with If-Match for a conditional replacement. A 412 means the condition failed; a 409 requires handling a concurrent conflict. Do not silently retry without the condition. See PutObject.

The SSE-KMS example supplies a KMS key ARN in the bucket's region and stores a full-object SHA-256 checksum. After upload it uses HEAD, the returned version ID when present, and the ETag to verify the encryption algorithm and key ARN. Upload-only encryption and checksum headers are removed before HEAD. IAM permissions and the KMS key policy must allow the operation; KMS requests can incur charges. This sets encryption for the object, not the bucket defaults. Its stored checksum can be used with the verified-download example below.

Downloading

Use the stream example for files and the BinData example when the bytes need to be in memory. Inspect the HTTP status before consuming a binary body so an XML error is not saved as a successful download. For a particular historical version, supply the exact versionId; do not convert it to a number.

Resume using the original object's identity

The resume example uses an existing s3-download.part and a private s3-download.json sidecar containing the original bucket, key, region, quoted ETag, and total size as strings. Save these when starting the download. It does not create this checkpoint for you or substitute metadata from a newly overwritten object.

It sends Range and If-Match, then appends only a matching HTTP 206 response with the expected ETag, range start, and total size. Never append an HTTP 200 full response to a partial file. A 412 stops the download; 416 is not automatic proof of completion. Final length is checked, but this resume example does not independently verify a stored object checksum. Keep local partial files protected from concurrent modification.

Verify content or recover a version

The checksum example retrieves metadata using GetObjectAttributes and supports FULL_OBJECT SHA-256. It pins the returned version when available, applies If-Match, downloads with checksum mode enabled, and compares both length and the base64 SHA-256 of the downloaded bytes. It explicitly stops for other algorithms or a composite multipart checksum. ETags are opaque validators, not universally MD5 hashes; a composite checksum is not the ordinary whole-file hash. KMS-encrypted reads and checksum access can need additional KMS permissions. See GetObjectAttributes.

The recovery example defaults to downloading a selected version. Its separate remove-delete-marker mode first checks that the selected version is a marker before deleting it. Removing the current marker can reveal an older version; removing an unrelated marker might not restore the current object. List versions again afterward. Deleting a data version is a different, permanent operation.

Restore archived content before downloading

The restore example targets Glacier Flexible Retrieval and Deep Archive objects. Request mode starts a Standard restore with a seven-day restored-copy lifetime; check mode only inspects readiness. An accepted request is not a ready download. Wait for x-amz-restore to report ongoing-request="false", and check the expiry. Restoration can take hours and incur retrieval/storage charges. The copy is temporary; Intelligent-Tiering archive tiers have different semantics and are outside this example. See RestoreObject.

Multipart Uploads

Run Initiate a Multipart Upload, then Upload Multipart Parts and Record ETags, then Complete a Multipart Upload and Check Embedded Errors. A private s3-multipart.json binds the upload ID to its bucket, region, and key. The upload-parts example reads an unchanged file in 8 MiB chunks and writes the ordered completion manifest only after every part succeeds.

Restarting the upload-parts example sends every part again for that upload ID. It does not selectively resume from a possibly stale local parts list. To design selective recovery, bind the source identity to durable state and reconcile the remote parts. These Rest multipart examples also do not calculate and verify an explicit composite checksum; adding one requires coordinating initiation, per-part checksums, and completion fields. The Http guide covers a separate implementation with those features.

HTTP 200 alone does not prove completion. CompleteMultipartUpload can return an embedded error after beginning a successful HTTP response. The example validates the complete XML result. If the response is lost, reconcile the upload and destination before starting over; a missing upload ID alone does not prove that completion succeeded. See CompleteMultipartUpload.

List Parts paginates one upload's parts; List Unfinished Multipart Uploads enumerates uploads using the key/upload-ID marker pair. Incomplete parts incur storage charges. Stop active upload workers before aborting, and verify cleanup if requests were in flight. A bucket lifecycle rule that aborts incomplete multipart uploads provides additional cleanup protection.

Copy a large object without downloading it

The multipart-copy example reads source size and ETag, starts a destination upload, and sends UploadPartCopy requests with byte ranges and a source ETag condition. Its exact decimal-string arithmetic handles offsets beyond 2 GB without int64. The example uses one-billion-byte parts for sources larger than 5 MiB through 10 TB; 10 TB is this implementation's bound, not a statement of S3's maximum object size. It saves state for cleanup with the abort example and does not implement selective resume.

The source remains in place. Destination metadata and tags are not automatically copied by this workflow; configure what you need when initiating the destination. Validate each copy-part result and the final completion body. See UploadPartCopy.

Object Metadata, Tags, Renaming and Deleting

HEAD reads headers without an object body. System metadata includes content type, size, and ETag; user-defined metadata uses x-amz-meta-*. Tags are a separate key/value collection. The replace-tag-set example overwrites the complete set. The manage-tags example reads, merges, removes one tag, or deletes all tags, preserving unrelated values when it performs a merge.

Read/merge/replace is not atomic. Coordinate concurrent tag writers, and for unversioned or mutable null-version objects also account for concurrent object replacement. A tag update is not a user-metadata update. See PutObjectTagging.

For general purpose buckets, the rename example copies to a new key and then deletes the source. It deletes only after validating the entire copy result, including any embedded error. The sequence is not atomic: a failed delete leaves both keys, and concurrent writers can change the source or destination. Coordinate writers for this example; use a version-aware workflow where concurrency is required. Large copies need the multipart-copy example. See CopyObject.

A delete without a version ID permanently removes an unversioned object; with versioning enabled it normally adds a delete marker and retains previous data versions. An explicit version deletion is permanent. The examples do not bypass Object Lock, legal holds, MFA Delete, or policy restrictions.

The bulk-delete example reads a private JSON list of up to 1,000 key/version identifiers, builds XML, and sends the required Content-MD5 with its explicit signature. It requests verbose results and matches each Deleted or Error entry to an input, checking for missing, duplicate, and unexpected results. HTTP 200 can contain per-object failures. A missing object can be reported as successfully deleted. Reconcile uncertain outcomes and retry only appropriate failures rather than blindly repeating a whole versioned batch. See DeleteObjects.

Pre-Signed URLs

The presigned-download example uses Chilkat.Http.S3_GenPresignedUrl as a local signing helper. It does not switch the transfer examples to Http or perform a download. It requests a 15-minute HTTPS URL and supports temporary credentials.

The URL grants its holder the specified access within the signer's permissions. Keep it out of public logs and share it only with intended recipients. It can be reused while valid; temporary credentials or policy restrictions can end access before the requested expiration. Generation alone does not verify that the object exists or that the credentials are authorized. Do not change the signed method, hostname, path, or query after generation. See AWS presigned URL guidance.

Troubleshooting and Permissions

Check the request, HTTP response, and operation result separately
ResultWhat to check
Signing error or region redirectBucket region, endpoint, clock, session token, exact path/query encoding, and whether a precomputed payload hash still matches the body. Correct the endpoint and signing scope together.
403 / AccessDeniedIAM and bucket policies, KMS permissions, and access restrictions. A 403 does not prove an object is absent. HEAD errors may have no XML body.
412 or 409A condition failed or a concurrent operation conflicted. Recheck object state and preserve the intended condition when retrying.
Unexpected range responseOriginal ETag, inclusive byte offsets, total size, and the exact partial file. Never append a full HTTP 200 response.
Timeout, throttling, or 5xxUse bounded backoff where appropriate. A write may have reached S3; inspect remote state and saved checkpoints before retrying initiation, completion, or deletion.
HTTP 200 with failed workParse and validate XML, including multipart/copy errors and individual bulk-delete results. Transport success is not application success.

Bucket listing uses s3:ListAllMyBuckets; object and version listings use s3:ListBucket and s3:ListBucketVersions. Reads and writes typically need s3:GetObject/s3:GetObjectVersion and s3:PutObject. Multipart inspection and cleanup use s3:ListBucketMultipartUploads, s3:ListMultipartUploadParts, and s3:AbortMultipartUpload. Attributes, tags, policies, deletion, and restoration have their own actions; KMS-encrypted operations also require suitable KMS access. IAM actions do not always have the same names as REST operations. See S3 actions and required permissions.

For private diagnostics, retain the operation, HTTP status, S3 error code, and request identifiers. Keep credentials, signed URLs, and full request dumps protected. The linked examples document their limits and validate the operation-specific results rather than treating any response as success.