rust-s3 [docs]
Rust library for Amazon S3 and compatible object storage. Supports async/await and synchronous use. Eligible operations retry according to the configured count; see set_retries.
Create a project with these files. rust-s3 is imported as s3. Set AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY (and, for temporary credentials, AWS_SESSION_TOKEN), AWS_REGION, and S3_BUCKET. For MinIO or another compatible service, also set S3_ENDPOINT (for example, http://localhost:9000). This example selects path-style requests when an endpoint is set, which is useful for MinIO; choose URL style based on your provider. Use a bucket where these credentials may write and delete objects. The UUID key avoids overwriting existing objects; after a successful upload, the example attempts deletion even if the read fails.
Create Cargo.toml:
[package]
name = "s3-quickstart"
version = "0.1.0"
edition = "2024"
[dependencies]
rust-s3 = "0.39.0"
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
uuid = { version = "1", features = ["v4"] }Save as src/main.rs:
use std::{env, error::Error};
use uuid::Uuid;
use s3::{creds::Credentials, Bucket, Region};
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
let bucket_name = env::var("S3_BUCKET")?;
let region_name = env::var("AWS_REGION")?;
let endpoint = env::var("S3_ENDPOINT").ok().filter(|value| !value.is_empty());
let region = match &endpoint {
Some(endpoint) => Region::Custom {
region: region_name,
endpoint: endpoint.clone(),
},
None => region_name.parse()?,
};
let credentials = Credentials::from_env()?;
let mut bucket = Bucket::new(&bucket_name, region, credentials)?;
if endpoint.is_some() {
bucket = bucket.with_path_style();
}
let key = format!("rust-s3-quickstart/{}.txt", Uuid::new_v4());
let payload = b"Hello from rust-s3!";
bucket.put_object(&key, payload).await?;
let downloaded = bucket.get_object(&key).await;
bucket.delete_object(&key).await?;
assert_eq!(downloaded?.as_slice(), payload);
println!("uploaded, verified, and deleted {key}");
Ok(())
}Run it with cargo run. For local MinIO, set your local AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY, then use (with the matching bucket name):
AWS_REGION=us-east-1 S3_BUCKET=rust-s3 S3_ENDPOINT=http://localhost:9000 cargo runTo use synchronous requests, replace the dependency with this Cargo.toml line and use a synchronous fn main:
rust-s3 = { version = "0.39.0", default-features = false, features = ["sync", "sync-native-tls", "fail-on-err"] }Remove #[tokio::main], async from fn main, and .await from the same three calls. The synchronous flow is:
bucket.put_object(&key, payload)?;
let downloaded = bucket.get_object(&key);
bucket.delete_object(&key)?;
assert_eq!(downloaded?.as_slice(), payload);fail-on-err turns unsuccessful HTTP statuses into errors and enables retries for eligible operations; without it, check each response's status_code(). For streaming downloads, see get_object_stream. Common next steps are list, presign_get, presign_put, and copy_object_from.
As many have noted my attention to the this library oscialtes, the best way to ensure I keep maintaining and adding features to it is to donate som BTC, or become a sponsor. Thank you for the support!
π° BTC π bc1q7ukqe09zplg2sltgfrkukghpelfaz7qja8pw6u
Modest interface towards Amazon S3, as well as S3 compatible object storage APIs such as Backblaze B2, Wasabi, Yandex, Minio or Google Cloud Storage.
Supports: put, get, list, delete, operations on tags and location, as well as head.
Additionally, a dedicated presign_get Bucket method is available. You can upload to S3 and share access with a presigned URL without making the object public. A PUT presigned URL allows uploads to a specific key for the URL's lifetime.
Read and run examples from the examples folder for additional runtime and provider setups.
# tokio, default
cargo run --example tokio
# async-std
cargo run --example async-std --no-default-features --features async-std-native-tls
# sync
cargo run --example sync --no-default-features --features sync-native-tls
# minio
cargo run --example minio
# r2
cargo run --example r2
# google cloud
cargo run --example google-cloudThere are a lot of various features that enable a wide variety of use cases, refer to s3/Cargo.toml for an exhaustive list. Below is a table of various useful features as well as a short description for each.
default-tokioruntime and anative-tlsimplementationblocking- generates*_blockingvariant of allBucketmethods, otherwise onlyasyncversions are availablefail-on-err- return Result::Err for HTTP errors
with-async-std-async-stdruntime,surfclient usedasync-std-native-tlsandasync-std-rustls-tlsopen a fresh HTTP/1 connection for each request to honor serverConnection: closeresponses. This adds TCP/TLS setup overhead and disables Surf's HTTP/1 pool, so its implicit per-host connection cap no longer applies.sync- no async runtime,attohttpcis used for HTTP requeststags- required forBucket::get_object_tagging
All runtimes support either native-tls or rustls-tls, there are features for all combinations, refer to s3/Cargo.toml for a complete list.
To build with Tokio and rustls backed by ring, disable the default native-TLS feature:
cargo build -p rust-s3 --no-default-features --features tokio-rustls-tls-ringThe default feature set remains Tokio with native TLS.
Bucket struct provides constructors for path-style paths, subdomain style is the default. Bucket exposes methods for configuring and accessing path-style configuration. blocking feature will generate a *_blocking variant of all the methods listed below.
When using LocalStack, you may need to skip sending the location constraint in bucket creation requests. LocalStack doesn't support location constraints in the request body and will return InvalidLocationConstraint errors. Set this environment variable to skip the constraint:
export RUST_S3_SKIP_LOCATION_CONSTRAINT=true
# or
export RUST_S3_SKIP_LOCATION_CONSTRAINT=1This may also be needed for other S3-compatible services that don't support AWS-style location constraints.
create |
async |
delete |
async |
list |
async |
exists |
async |
POST |
presign_post |
PUT |
presign_put |
GET |
presign_get |
DELETE |
presign_delete |
There are a few different options for getting an object. sync and async methods are generic over std::io::Write,
while tokio methods are generic over tokio::io::AsyncWriteExt.
async/sync/async-blocking |
get_object |
async/sync/async-blocking |
get_object_stream |
async/sync/async-blocking |
get_object_to_writer |
Each GET method has a PUT companion sync and async methods are generic over std::io::Read. async stream methods are generic over futures_io::AsyncReadExt, while tokio methods are generic over tokio::io::AsyncReadExt.
async/sync/async-blocking |
put_object |
async/sync/async-blocking |
put_object_with_content_type |
async/sync/async-blocking |
put_object_stream |
async/sync/async-blocking |
list |
async/sync/async-blocking |
delete_object |
async/sync/async-blocking |
delete_objects |
async/sync/async-blocking |
location |
async/sync/async-blocking |
put_object_tagging |
async/sync/async-blocking |
get_object_tagging |
async/sync/async-blocking |
head_object |