aws.s3
Module aws.s3
Definitions
ballerinax/aws.s3 Ballerina library
Overview
Amazon S3 (Simple Storage Service) is a highly scalable, durable, and secure object storage service provided by Amazon Web Services (AWS). It is designed to store and retrieve any amount of data from anywhere on the web, making it ideal for a wide range of use cases, including data backup, archiving, content distribution, and big data analytics.
The ballerinax/aws.s3 connector offers APIs to connect and interact with Amazon S3, specifically based on the 2006-03-01 version of the Amazon S3 REST API. It supports creating, listing, and deleting buckets, uploading, retrieving, and deleting objects, managing object metadata and tagging, multipart uploads, and bucket and object access control lists (ACLs).
Setup guide
To use the Ballerina AWS S3 connector, you need an AWS account with the necessary IAM user credentials. For detailed steps on obtaining these credentials, refer to the Obtaining IAM user credentials guide.
Quickstart
To use the aws.s3 connector in your Ballerina application, update your .bal file as follows.
Step 1: Import the module
Import the aws.s3 module and the aws module.
import ballerinax/aws; import ballerinax/aws.s3;
Step 2: Instantiate a new connector
- Create a
Config.tomlfile and configure the credentials obtained above:
accessKeyId = "<ACCESS_KEY_ID>" secretAccessKey = "<SECRET_ACCESS_KEY>"
- Instantiate an
s3:Clientwith the obtained credentials and initialize the connector with it.
configurable string accessKeyId = ?; configurable string secretAccessKey = ?; final s3:Client s3Client = check new ({ region: aws:US_EAST_1, auth: { accessKeyId, secretAccessKey } });
Alternative authentication methods
Profile-based authentication
You can use AWS profile-based authentication as an alternative to static credentials.
final s3:Client s3Client = check new ({ region: aws:US_EAST_1, auth: { profileName: "myAwsProfile", credentialsFilePath: "/path/to/custom/credentials" } });
Note: Ensure your AWS credentials file follows the standard format.
[default] aws_access_key_id = YOUR_ACCESS_KEY_ID aws_secret_access_key = YOUR_SECRET_ACCESS_KEY [myAwsProfile] aws_access_key_id = ANOTHER_ACCESS_KEY_ID aws_secret_access_key = ANOTHER_SECRET_ACCESS_KEY
Default credential provider chain
The standard default credential provider chain, trying each of the following in order and taking the first source that yields credentials:
- Environment variables (
AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY, andAWS_WEB_IDENTITY_TOKEN_FILEif set) - The shared config/credentials file's active profile (
AWS_PROFILE, ordefaultif unset) — which may itself resolve via SSO, an external process, or a chainedAssumeRolecall, depending on that profile's configuration - Container credentials (ECS/EKS)
- EC2 instance profile (IMDS)
import ballerinax/aws.auth; final s3:Client s3Client = check new ({ region: aws:US_EAST_1, auth: auth:DEFAULT_CREDENTIALS });
Step 3: Invoke the connector operations
Now, utilize the available connector operations. A sample use case is shown below.
public function main() returns error? { check s3Client->createBucket("add-unique-bucket-name"); }
Step 4: Run the Ballerina application
Use the following command to compile and run the Ballerina program.
bal run
Examples
The ballerinax/aws.s3 connector provides practical examples illustrating usage in various scenarios. Explore these examples, covering the following use cases.
-
S3 Report Archiver: Implements an ETL-style workflow that processes CSV reports and archives them to Amazon S3. Reads report data, transforms it, and uploads the results to a designated S3 bucket for long-term storage.
-
FTP to S3 Sync: Syncs files from an FTP server to Amazon S3. Downloads files from the FTP source, uploads them to an S3 bucket, and generates a summary report of skipped or failed transfers.
Clients
aws.s3: Client
The AWS S3 Client Connector.
Provides access to Amazon Simple Storage Service (S3) using the AWS SDK for Java V2. Supports static credentials, profile-based credentials, and the default AWS credential provider chain (environment variables, ECS container credentials, EC2 instance profiles, etc.).
Constructor
Initializes the S3 Client.
init (*ConnectionConfig config)- config *ConnectionConfig - The connection configuration
createBucket
function createBucket(string bucketName, *CreateBucketConfig config) returns Error?Creates an S3 bucket.
Parameters
- bucketName string - The name of the bucket
- config *CreateBucketConfig - Optional bucket configuration
Return Type
- Error? - An Error if bucket creation fails
deleteBucket
Deletes an S3 bucket.
Parameters
- bucketName string - The name of the bucket
Return Type
- Error? - An Error if bucket deletion fails
listBuckets
Lists all buckets in the AWS account.
getBucketLocation
Gets the AWS region of a bucket.
Parameters
- bucketName string - The name of the bucket
putObjectFromFile
function putObjectFromFile(string bucketName, string objectKey, string filePath, *PutObjectConfig config) returns Error?Uploads an S3 object from a file path.
Parameters
- bucketName string - The name of the bucket
- objectKey string - The path of the object
- filePath string - The local file path to upload
- config *PutObjectConfig - Optional upload configuration
Return Type
- Error? - An Error if the upload fails
putObject
function putObject(string bucketName, string objectKey, UploadContent content, *PutObjectConfig config) returns Error?Uploads an S3 object from content.
Parameters
- bucketName string - The name of the bucket
- objectKey string - The path of the object
- content UploadContent - The object content (to be used for automatic data binding).
Supported types:
- Built-in subtypes of
anydata(byte[],string,json,xml) - Custom types (e.g.,
User,Student, etc.), written as JSON for a.jsonobject key and as XML for a.xmlobject key - Arrays of custom types (e.g.,
User[],Student[], etc.), written as CSV with the field names as headers, needs a.csvobject key - Stream of custom types (e.g.,
stream<User, error?>), written as CSV, needs a.csvobject key - Stream of byte arrays (
stream<byte[], error?>), collected into bytes before uploading ThePutObjectConfig.fileFormatconfiguration overrides the format inferred from the object key
- Built-in subtypes of
- config *PutObjectConfig - Optional upload configuration
Return Type
- Error? - An Error if the upload fails
putObjectAsStream
function putObjectAsStream(string bucketName, string objectKey, stream<byte[], error?> contentStream, *PutObjectStreamConfig config) returns Error?Uploads an S3 object from a stream.
Parameters
- bucketName string - The name of the bucket
- objectKey string - The path of the object
- config *PutObjectStreamConfig - Optional upload configuration
Return Type
- Error? - An Error if the upload fails
getObject
function getObject(string bucketName, string objectKey, typedesc<RetrievableType> targetType, *GetObjectConfig config) returns targetType|ErrorDownloads an S3 object from an S3 bucket.
Parameters
- bucketName string - The name of the bucket
- objectKey string - The path of the object
- targetType typedesc<RetrievableType> (default <>) - Expected return type (to be used for automatic data binding).
Supported types:
- Built-in subtypes of
anydata(byte[],string,json,xml) - Custom types (e.g.,
User,Student, etc.), read as JSON for a.jsonobject key and as XML for a.xmlobject key - Arrays of custom types (e.g.,
User[],Student[], etc.), read as CSV with the first row as headers, needs a.csvobject key - Stream of custom types (e.g.,
stream<User, error?>), read as CSV, needs a.csvobject key - Stream of byte arrays (
stream<byte[], error?>), to retrieve large objects without loading the entire content into memory
- Built-in subtypes of
- config *GetObjectConfig - Optional retrieval configuration
Return Type
- targetType|Error - The object content in the requested type or an Error
deleteObject
function deleteObject(string bucketName, string objectKey, *DeleteObjectConfig config) returns Error?Deletes an S3 object from an S3 bucket.
Parameters
- bucketName string - The name of the bucket
- objectKey string - The path of the object
- config *DeleteObjectConfig - Optional deletion configuration
Return Type
- Error? - An Error if deletion fails
listObjects
function listObjects(string bucketName, *ListObjectsConfig config) returns ListObjectsResponse|ErrorLists S3 objects in an S3 bucket.
Parameters
- bucketName string - The name of the bucket
- config *ListObjectsConfig - Optional listing configuration
Return Type
- ListObjectsResponse|Error - List of objects or an Error
createPresignedUrl
function createPresignedUrl(string bucketName, string objectKey, *PresignedUrlConfig config) returns string|ErrorCreates a presigned URL for temporary access to an S3 object.
Parameters
- bucketName string - The name of the bucket
- objectKey string - The path of the object
- config *PresignedUrlConfig - Optional presigned URL configuration
getObjectMetadata
function getObjectMetadata(string bucketName, string objectKey, *HeadObjectConfig config) returns ObjectMetadata|ErrorGets metadata for an S3 object without downloading it.
Parameters
- bucketName string - The name of the bucket
- objectKey string - The path of the object
- config *HeadObjectConfig - Optional metadata retrieval configuration
Return Type
- ObjectMetadata|Error - Object metadata or an Error
copyObject
function copyObject(string sourceBucket, string sourceKey, string destinationBucket, string destinationKey, *CopyObjectConfig config) returns Error?Copies an S3 object from one location to another.
Parameters
- sourceBucket string - Source bucket name
- sourceKey string - Source object path
- destinationBucket string - Destination bucket name
- destinationKey string - Destination object path
- config *CopyObjectConfig - Optional copy configuration
Return Type
- Error? - An Error if copy fails
doesObjectExist
Checks if an S3 object exists in an S3 bucket.
Return Type
createMultipartUpload
function createMultipartUpload(string bucketName, string objectKey, *MultipartUploadConfig config) returns string|ErrorCreates a multipart upload.
Parameters
- bucketName string - The name of the bucket
- objectKey string - The path of the object
- config *MultipartUploadConfig - Optional multipart upload configuration
uploadPart
function uploadPart(string bucketName, string objectKey, string uploadId, int partNumber, UploadContent content, *UploadPartConfig config) returns string|ErrorUploads a part in a multipart upload.
Supported content types: byte[], string, json, xml, record {}, record {}[],
stream<byte[], error?>, and stream<record {}, error?>.
For record {} content, the object key must end with .json or .xml.
.json keys serialize the record as JSON; .xml keys serialize as XML.
For record {}[] and stream<record {}, error?> content, the object key must end with .csv.
The records are serialized as CSV (field names as headers).
stream<byte[], error?> content is collected into bytes before uploading.
Parameters
- bucketName string - The name of the bucket
- objectKey string - The path of the object
- uploadId string - The upload ID from createMultipartUpload
- partNumber int - The part number (1-10000)
- content UploadContent - The part content
- config *UploadPartConfig - Optional upload part configuration
uploadPartAsStream
function uploadPartAsStream(string bucketName, string objectKey, string uploadId, int partNumber, stream<byte[], error?> contentStream, *UploadStreamPartConfig config) returns string|ErrorUploads a part from a stream.
Parameters
- bucketName string - The name of the bucket
- objectKey string - The path of the object
- uploadId string - The upload ID from createMultipartUpload
- partNumber int - The part number (1-10000)
- config *UploadStreamPartConfig - Optional upload part configuration
completeMultipartUpload
function completeMultipartUpload(string bucketName, string objectKey, string uploadId, int[] partNumbers, string[] etags) returns Error?Completes a multipart upload.
Parameters
- bucketName string - The name of the bucket
- objectKey string - The path of the object
- uploadId string - The upload ID from createMultipartUpload
- partNumbers int[] - Array of part numbers
- etags string[] - Array of ETags corresponding to each part
Return Type
- Error? - An Error if completion fails
abortMultipartUpload
Aborts a multipart upload.
Parameters
- bucketName string - The name of the bucket
- objectKey string - The path of the object
- uploadId string - The upload ID from createMultipartUpload
Return Type
- Error? - An Error if abort fails
close
function close() returns Error?Closes the underlying S3 client and releases resources.
Return Type
- Error? - An Error if closing fails
Enums
aws.s3: CannedACL
Access control options for buckets and objects.
Members
aws.s3: FileFormat
Represents the file format for serializing record content.
Members
aws.s3: HttpMethod
HTTP methods for presigned URLs.
Members
aws.s3: ObjectOwnership
Who owns objects uploaded to the bucket.
Members
aws.s3: StorageClass
Storage options for S3 objects (affects cost and access speed).
Members
Records
aws.s3: Bucket
Defines bucket.
Fields
- name string - The name of the bucket
- creationDate string - The creation date of the bucket
aws.s3: ConnectionConfig
Configuration for the AWS S3 Client.
Fields
- auth AuthConfig - Authentication configuration
- endpoint? EndpointConfig - Optional endpoint configuration for FIPS, dualstack, or custom endpoint overrides (e.g., LocalStack)
aws.s3: CopyObjectConfig
Configuration for copying an object.
Fields
- acl CannedACL(default PRIVATE) - Specifies accessibility for the copied object (e.g., "private", "public-read")
- storageClass StorageClass(default STANDARD) - Storage type for the copied object (e.g., "STANDARD", "GLACIER")
- metadataDirective? string - "COPY" to keep original metadata or "REPLACE" to use new metadata
- contentType? string - The MIME type of the copied object
- cacheControl? string - Specifies caching behavior along the request/reply chain
- contentDisposition? string - Specifies presentational information for the object
- contentEncoding? string - Specifies what content encodings have been applied to the object and thus what decoding mechanisms must be applied to obtain the media-type referenced by the Content-Type header field
- tagging? string - Tags for the copied object (e.g., "env=prod&team=finance")
- copySourceIfMatch? string - Copy the object only if its entity tag (ETag) is the same as the one specified
- copySourceIfNoneMatch? string - Copy the object only if its entity tag (ETag) is different from the one specified
- copySourceIfModifiedSince? string - Copy the object only if it has been modified since the specified time (e.g., "2024-01-15T00:00:00Z")
- copySourceIfUnmodifiedSince? string - Copy the object only if it has not been modified since the specified time (e.g., "2024-01-15T00:00:00Z")
aws.s3: CreateBucketConfig
Configuration for creating a bucket.
Fields
- acl CannedACL(default PRIVATE) - Specifies accessibility for this object (e.g., "private", "public-read")
- objectOwnership ObjectOwnership(default BUCKET_OWNER_ENFORCED) - Specifies ownership of objects uploaded to this bucket (e.g., "BucketOwnerEnforced", "ObjectWriter")
- objectLockEnabled? boolean - Enable Object Lock to prevent objects from being deleted or overwritten
aws.s3: DeleteObjectConfig
Configuration for deleting an object.
Fields
- versionId? string - Delete a specific version of the object (when versioning is enabled)
- mfa? string - Multi-factor authentication token (needed if MFA Delete is turned on for the bucket)
- bypassGovernanceRetention? boolean - Skip the lock protection and delete the object even if it's protected (use with caution)
aws.s3: GetObjectConfig
Configuration for retrieving an object.
Fields
- versionId? string - Get a specific version of the object (when versioning is enabled)
- range? string - Downloads the specified range bytes of an object
- ifMatch? string - Return the object only if its entity tag (ETag) is the same as the one specified
- ifNoneMatch? string - Return the object only if its entity tag (ETag) is different from the one specified
- ifModifiedSince? string - Return the object only if it has been modified since the specified time (e.g., "2024-01-15T00:00:00Z")
- ifUnmodifiedSince? string - Return the object only if it has not been modified since the specified time (e.g., "2024-01-15T00:00:00Z")
- partNumber? int - The part number of the file part
- responseContentType? string - Override the MIME type of the content
- responseContentDisposition? string - Override presentational information for the object
aws.s3: HeadObjectConfig
Configuration for getting object metadata.
Fields
- versionId? string - Get metadata for a specific version of the object (when versioning is enabled)
- partNumber? int - The part number of the file part to get metadata for
- ifMatch? string - Return the metadata only if its entity tag (ETag) is the same as the one specified
- ifNoneMatch? string - Return the metadata only if its entity tag (ETag) is different from the one specified
- ifModifiedSince? string - Return the metadata only if it has been modified since the specified time
- ifUnmodifiedSince? string - Return the metadata only if it has not been modified since the specified time
aws.s3: ListObjectsConfig
Configuration for listing objects.
Fields
- prefix? string - Filter objects that start with this value (e.g., "photos/" for all objects in photos folder)
- delimiter? string - Character to group object keys (e.g., "/" to list like folders)
- maxKeys? int - Maximum number of objects to return (1-1000)
- continuationToken? string - Token to get the next page of results
- startAfter? string - List objects after this key name
- fetchOwner? boolean - Include owner info in the results
- encodingType? string - Encoding type for object keys (e.g., "url")
aws.s3: ListObjectsResponse
Response from listing objects in a bucket.
Fields
- objects S3Object[] - List of objects found
- count int - Number of objects returned
- isTruncated boolean - True if there are more results (use nextContinuationToken to get them)
- nextContinuationToken? string - Token to get the next page of results
aws.s3: MultipartUploadConfig
Configuration for multipart upload (for large files uploaded in parts).
Fields
- contentType? string - The MIME type of the content
- acl CannedACL(default PRIVATE) - Specifies accessibility for this object (e.g., "private", "public-read")
- storageClass StorageClass(default STANDARD) - The Storage class of the object (e.g., "STANDARD", "GLACIER" for archive)
- cacheControl? string - Specifies caching behavior along the request/reply chain
- contentDisposition? string - Specifies presentational information for the object
- contentEncoding? string - Specifies what content encodings have been applied to the object and thus what decoding mechanisms must be applied to obtain the media-type referenced by the Content-Type header field
- tagging? string - Tags for the object (e.g., "env=prod&team=finance")
- serverSideEncryption? string - Encryption type ("AES256" or "aws:kms")
aws.s3: ObjectMetadata
Metadata information about an S3 object.
Fields
- key string - The object's path/name in the bucket (e.g., "photos/image.jpg")
- contentLength int - Size of the object in bytes
- contentType? string - The MIME type of the content
- eTag string - Unique ID of the object's content
- lastModified string - When the object was last changed
- storageClass StorageClass(default STANDARD) - The Storage class of the object (e.g., "STANDARD", "GLACIER")
- versionId? string - Version ID of the object (when versioning is enabled)
- userMetadata? map<anydata> - Custom data attached to the object
aws.s3: PresignedUrlConfig
Configuration for creating presigned URLs.
Fields
- expirationMinutes int(default 15) - Specifies how long the URL is valid in minutes (default: 15, max: 10080 for 7 days)
- httpMethod HttpMethod(default GET) - Specifies what action the URL allows ("GET" to download, "PUT" to upload)
- contentType? string - The MIME type of the content (for PUT requests)
- contentDisposition? string - Specifies presentational information for the object (for GET requests)
- responseContentType? string - Override file type when downloading (for GET requests)
- versionId? string - Get URL for a specific version of the object (when versioning is enabled)
aws.s3: PutObjectConfig
Configuration for uploading an object.
Fields
- contentType? string - The MIME type of the content
- acl CannedACL(default PRIVATE) - Specifies accessibility for this object (e.g., "private", "public-read")
- storageClass StorageClass(default STANDARD) - The Storage class of the object (e.g., "STANDARD", "GLACIER" for archive, "INTELLIGENT_TIERING")
- cacheControl? string - Specifies caching behavior along the request/reply chain
- contentDisposition? string - Specifies presentational information for the object
- contentEncoding? string - Specifies what content encodings have been applied to the object and thus what decoding mechanisms must be applied to obtain the media-type referenced by the Content-Type header field
- contentLanguage? string - The language the content is in (e.g., "en-US", "fr")
- expires? string - The date and time at which the object is no longer cacheable
- tagging? string - Tags for the object
- serverSideEncryption? string - Encryption type ("AES256" or "aws:kms")
- fileFormat? FileFormat - The file format to use for serializing record content. Overrides the format inferred from the object key extension
aws.s3: PutObjectStreamConfig
Configuration for uploading an object as a stream.
Fields
- Fields Included from *PutObjectConfig
- contentLength int - The Size of the content, in bytes
aws.s3: S3Object
Represents a single S3 object in a listing.
Fields
- key string - The object's path/name in the bucket (e.g., "photos/image.jpg")
- size int - Size of the object in bytes
- lastModified string - When the object was last changed
- eTag string - Represents the hash value of the object, which reflects modifications made exclusively to the contents of the object
- storageClass StorageClass(default STANDARD) - The Storage class of the object (e.g., "STANDARD", "GLACIER")
aws.s3: UploadPartConfig
Configuration for uploading a single part in a multipart upload.
Fields
- contentLength? int - Size of the part in bytes
- contentMD5? string - MD5 hash of the part content (for data integrity check)
- fileFormat? FileFormat - The file format to use for serializing record content. Overrides the format inferred from the object key extension
aws.s3: UploadStreamPartConfig
Configuration for uploading a part as a stream in a multipart upload.
Fields
- Fields Included from *UploadPartConfig
- contentLength int
- contentMD5 string
- fileFormat FileFormat
- contentLength int - Size of the part in bytes
Errors
aws.s3: BucketAlreadyExistsError
Represents an error when trying to create a bucket that already exists.
aws.s3: BucketAlreadyOwnedByYouError
Represents an error when the bucket already exists and is owned by you.
aws.s3: BucketNotEmptyError
Represents an error when the bucket is not empty (for deletion).
aws.s3: Error
Represents the base error type for this module.
This is a distinct type to avoid mixing with generic error values.
aws.s3: NoSuchBucketError
Represents an error when the specified bucket does not exist.
aws.s3: NoSuchKeyError
Represents an error when the specified key does not exist.
Union types
Import
import ballerinax/aws.s3;Metadata
Released date: about 16 hours ago
Version: 4.0.0
License: Apache-2.0
Compatibility
Platform: java21
Ballerina version: 2201.12.0
GraalVM compatible: Yes
Pull count
Total: 15458
Current verison: 2
Weekly downloads
Keywords
Cloud/Object Storage
Cost/Paid
Vendor/Amazon
Area/Storage & File Management
Type/Connector
Contributors
Dependencies