Topics
This section is a tutorial that walks you step-by-step through many of the major tasks you perform using Amazon S3, including uploading, downloading, and deleting data. To get the most out of this guide, we recommend that you read the following sections in the sequence they're presented.
The HTML version of this guide enables you to hide the text in this section that doesn't pertain to the programming language you are using. There is a language selection menu in the upper-right corner of pages with language-specific text. Select your computer language to show the examples in only that computer language, or select All to show the examples in all available computer languages.

AWS provides libraries, sample code, tutorials, and other resources for software developers who prefer to build applications using language-specific APIs instead of Amazon S3's SOAP and REST APIs. These libraries provide basic functions (not included in Amazon S3's SOAP and REST APIs), such as request authentication, request retries, and error handling so that it's easier to get started. Libraries and resources are available for the following languages:
For libraries and sample code in all languages, go to Sample Code & Libraries.
Amazon S3 authentication validates the identity of the party making a request. Authentication ensures that you don't get charged for operations you did not authorize.
Security always relies on a secret. For Amazon S3 (and other AWS services), your secret is
your AWS Secret Access Key. Do not reveal it to anyone even if a request appears to come
from Amazon.com. AWS pairs your AWS Secret Access Key with your AWS Access Key ID. You
include in Amazon S3 requests your AWS Access Key ID and an HMAC SHA-1 value, called the
signature value, calculated using your AWS Secret Access Key.
Amazon S3 verifies that the sender of the request knows both the AWS Access Key ID and the
corresponding AWS Secret Access Key. Amazon S3 does not process requests where the AWS Access
Key ID and AWS Secret Key do not match.
In the following samples, you simply add your AWS Access Key ID and AWS Secret Key to the sample files. For more information about authentication, go to the Amazon Simple Storage Service Developer Guide.
![]() | Note |
|---|---|
Depending on how you set the access control list (ACL), Amazon S3 can accept anonymous requests. |
To complete the following sections, download the sample files in one of the following computer languages:
For information about the sample, including how to run it, refer to the README file in each sample.
Be sure to also check out the AWS Developer Resource Center, which has a complete collection of code samples, articles, and documentation for building applications using Amazon S3.
Before you can store data in Amazon S3 you need to create a bucket.
You must specify a name for the bucket when you create it. The name can be any string you choose (up to 255 bytes in length), but cannot be the same as any other bucket name already owned by an Amazon S3 user. Keep in mind that the bucket name is visible in any URLs that address your objects. So, you should choose a name that is appropriate in that context.
The following sample code snippets demonstrate how to create an Amazon S3 bucket.
![]() | Note |
|---|---|
For information on other bucket creation options, including how to store data in EU (Ireland) and US-West (Northern California), go to the section, Buckets and Regions, in the Amazon Simple Storage Service Developer Guide. |
To run the sample
Open the sample file.
Replace bucket-name with the bucket name to
create.
// all future examples assume this:
AWSAuthConnection conn =
new AWSAuthConnection("[aws-access-key-id]", "[aws-secret-access-key-id]");
Response response = conn.createBucket("[bucket-name]", null);
if (response.connection.getResponseCode() == 200) {
// bucket was created
} else {
// something bad happened This example uses AWS libraries. For more information, see AWS Libraries.
To run the sample
Open the sample file.
Replace bucket-name with the bucket name to create. Also,
replace secretKeyID and secretAccessKeyID with your personal values.
static void CreateABucket()
{
// all future examples assume this:
AmazonS3 client = Amazon.AWSClientFactory.CreateAmazonS3Client(secretKeyID, secretAccessKeyID);
try
{
PutBucketRequest request = new PutBucketRequest();
request.BucketName = "[bucket-name]";
S3Response response = client.PutBucket(request);
// Do something with the response
response.Dispose();
}
catch (AmazonS3Exception ex)
{
// something bad happened
}
}To run the sample
Open the sample file.
Replace bucket-name with the bucket name to
create.
# all future examples assume this:
my $conn =
S3::AWSAuthConnection->new("[aws-access-key-id]", "[aws-secret-access-key]");
my $response = $conn->create_bucket("[bucket-name]");
if ($response->http_response->code == 200) {
# bucket was created
} else {
# something bad happened
}To run the sample
Open the sample file.
Replace bucket-name with the bucket name to
create.
$req =& new HTTP_Request("http://s3.amazonaws.com/[bucket-name]");
$req->setMethod("PUT");
setAuthorizationHeader($req);
$req->sendRequest();
if ($req->getResponseCode() == 200) {
// bucket was created
} else {
// something bad happened
}To run the sample
Open the sample file.
Replace bucket-name with the bucket name to
create.
# all future examples assume this:
conn =
S3::AWSAuthConnection.new("[aws-access-key-id]", "[aws-secret-access-key]")
response = conn.create_bucket("[bucket-name]")
if response.http_response.code == 200
# bucket was created
else
# something bad happened
endTo run the sample
Open the sample file.
Replace bucket-name with the bucket name to
create.
# all future examples assume this:
conn = S3.AWSAuthConnection("[aws-access-key-id]", "[aws-secret-access-key]")
response = conn.create_bucket("[bucket-name]")
if response.http_response.status == 200:
# bucket was created
else:
# something bad happenedThe following is an example of an HTTP request.
# create bucket request PUT /[bucket-name] HTTP/1.0 Date: Wed, 08 Mar 2006 04:06:15 GMT Authorization: AWS [aws-access-key-id]:[header-signature] Host: s3.amazonaws.com # create bucket response HTTP/1.1 200 OK x-amz-id-2: VjzdTviQorQtSjcgLshzCZSzN+7CnewvHA+6sNxR3VRcUPyO5fmSmo8bWnIS52qa x-amz-request-id: 91A8CC60F9FC49E7 Date: Wed, 08 Mar 2006 04:06:15 GMT Location: /[bucket-name] Content-Length: 0 Connection: keep-alive Server: AmazonS3
Once you create a bucket you can store objects in it. To store objects, you use the
HTTP PUT method. When you store an object, Amazon S3 streams the data to
multiple storage servers in multiple data centers to ensure that the data remains
available in the event of internal network or hardware failure. Each object can hold up
to 5 GB of data.
To write data to Amazon S3, you specify a bucket and a key. The key may be any UTF-8
string. Many developers use a prefix-based, key-naming scheme that lends itself to the
List operation. For example, you can store all of your beach
pictures with keys that begin with the prefix "Pictures/Beach," for example, Pictures/Beach/BigWave.jpg and Pictures/Beach/Dune.png.
There is no distinction between overwriting an existing object and creating a new object. When you send data to a bucket and key, Amazon S3 updates the object. You cannot modify or append data to an existing object. Amazon S3 either replaces an existing object or does nothing to it at all. If a write operation gets cut off during upload, Amazon S3 maintains the old data (if any) in the object.
By default, Amazon S3 stores objects with the permission "private," which means that only the bucket owner can read the object later.
The following sample code snippets demonstrate how to store an Amazon S3 object. To write an object, you must have write access to the bucket.
To run the sample
Open the sample file.
Replace [bucket-name] with the name of your bucket and
[key-name] with the name of the object.
Make any changes and run the sample.
// simple object put
S3Object simpleObject = new S3Object("this is a test".getBytes(), null);
Response response = conn.put("[bucket-name]", "[key-name]", simpleObject, null);
// put a more complex object with some metadata and http headers.
Map metadata = new TreeMap();
metadata.put("title", Arrays.asList(new String[] { "my title" }));
S3Object titledObject =
new S3Object("this object has a title".getBytes(), metadata);
Map headers = new TreeMap();
headers.put("Content-Type", Arrays.asList(new String[] { "text/plain" }));
response = conn.put("[bucket-name]", "[key-name]", titledObject, headers);This example uses AWS libraries. For more information, see AWS Libraries.
To run the sample
Open the sample file.
Replace [bucket-name] with the name of your bucket and
[key-name] with the name of the object. Also, replace
secretKeyID and secretAccessKeyID with your personal values.
Make any changes and run the sample.
static void WritingAnObject()
{
// all future examples assume this:
AmazonS3 client = Amazon.AWSClientFactory.CreateAmazonS3Client(secretKeyID, secretAccessKeyID);
// simple object put
PutObjectRequest request = new PutObjectRequest();
request.WithContentBody("this is a test")
.WithBucketName("[bucket-name]")
.WithKey("[key-name]");
S3Response response = client.PutObject(request);
// put a more complex object with some metadata and http headers.
PutObjectRequest titledRequest = new PutObjectRequest();
titledRequest.WithMetaData("title", "my title")
.WithContentBody("this object has a title")
.WithBucketName("[bucket-name]")
.WithKey("[key-name]");
response = client.PutObject(titledRequest);
//Read response
response.Dispose();
}To run the sample
Open the sample file.
Replace [bucket-name] with the name of your bucket and
[key-name] with the name of the object.
Make any changes and run the sample.
# simple object put
my $response =
$conn->put("[bucket-name]", "[key-name]", S3Object->new("this is a test"));
# put a more complex object with some metadata and http headers.
$response =
$conn->put(
"[bucket-name]",
"[key-name]",
S3Object->new("this is a test", { title => "my title" }),
{ "Content-Type" => "text/plain" });To run the sample
Open the sample file.
Replace [bucket-name] with the name of your bucket and
[key-name] with the name of the object.
Make any changes and run the sample.
$req =& new HTTP_Request("http://s3.amazonaws.com/[bucket-name]/[object-name]");
$req->setMethod("PUT");
$req->setBody("this is a test");
$req->setHeader("Content-Type", "text/plain");
$req->setHeader("x-amz-meta-title", "my title");
setAuthorizationHeader($req);
$req->sendRequest();To run the sample
Open the sample file.
Replace [bucket-name] with the name of your bucket and
[key-name] with the name of the object.
Make any changes and run the sample.
# simple object put
conn.put("[bucket-name]", "[key-name]", S3::S3Object.new("this is a test"));
# put a more complex object with some metadata and http headers.
$conn->put(
"[bucket-name]",
"[key-name]",
S3::S3Object.new("this is a test", { "title" => "my title" }),
{ "Content-Type" => "text/plain" })To run the sample
Open the sample file.
Replace [bucket-name] with the name of your bucket and
[key-name] with the name of the object.
Make any changes and run the sample.
# simple object put
conn.put("[bucket-name]", "[key-name]", S3.S3Object("this is a test"));
# put a more complex object with some metadata and http headers.
$conn->put(
"[bucket-name]",
"[key-name]",
S3.S3Object("this is a test", { "title": "my title" })
{ "Content-Type": "text/plain" })The following is an example of an HTTP request.
# put object request PUT /[bucket-name]/[key-name] HTTP/1.0 Date: Wed, 08 Mar 2006 04:06:16 GMT Authorization: AWS [aws-access-key-id]:[header-signature] Host: s3.amazonaws.com Content-Length: 14 x-amz-meta-title: my title Content-Type: text/plain this is a test # put object response HTTP/1.1 200 OK x-amz-id-2: wc15E1LUrjDZhNtT4QZtsbtadnOMKGjw5QTxkRDVO1owwbA6YoiqJJEuKShopufw x-amz-request-id: 7487CD42C5CA7524 Date: Wed, 08 Mar 2006 04:06:16 GMT ETag: "54b0c58c7ce9f2a8b551351102ee0938" Content-Length: 0 Connection: keep-alive Server: AmazonS3
To read an object, you send an HTTP GET request to the URL (end
point, bucket name, and key) that identifies the object you want to read.
If the object you're returning is publicly readable, you can read it by pasting its
URL into a browser. You can also place a link to the object on a web page for others to
click. For developers that want to serve URLs to users without having to make their
objects publicly readable, Amazon S3 offers a query-string authentication mechanism for
GET operations that enables you to include the request
signature in the URL rather than in the request header. This
enables you to pre-sign a request and then hand it out to your customers. For more
information about query-string authentication, go to the Amazon Simple Storage Service Developer Guide.
The following sample code snippets demonstrate retrieving an Amazon S3 object.
To run the sample
Open the sample file.
Replace bucket-name with the name of your bucket and
key-name with the name of the object to read.
GetResponse response = conn.get("[bucket-name]", "[key-name]", null);
String value = response.object.data;
Map metadata = response.object.metadata;
List values = (List)metadata.get("title");
String title = (String)values.get(0);This example uses AWS libraries. For more information, see AWS Libraries.
To run the sample
Open the sample file.
Replace [bucket-name] with the name of your bucket and
[key-name] with the name of the EC2 key pair name. (For
more information, see How to Create a Key
Pair.) Also, replace secretKeyID and
secretAccessKeyID with your personal
values.
static void ReadingAnObject()
{
// all future examples assume this:
AmazonS3 client = Amazon.AWSClientFactory.CreateAmazonS3Client(secretKeyID, secretAccessKeyID);
GetObjectRequest request = new GetObjectRequest().WithBucketName("[bucket-name").WithKey("[key-name]");
//Consider calling client.GetObjectMetadata so only metadata is brought back
S3Response response = client.GetObject(request);
string title = response.Metadata["title"];
response.Dispose();
}
To run the sample
Open the sample file.
Replace bucket-name with the name of your bucket and
key-name with the name of the object to read.
my $response = $conn->get("[bucket-name]", "[key-name]");
my $data = $response->object->data;
my $metadata = $response->object->metadata;
my $title = $metadata->{title};To run the sample
Open the sample file.
Replace bucket-name with the name of your bucket and
key-name with the name of the object to read.
$req =& new HTTP_Request("http://s3.amazonaws.com/[bucket-name]/[key-name]");
$req->setMethod("GET");
setAuthorizationHeader($req);
$req->sendRequest();
if ($req->getResponseCode() == 200) {
$data = $req->getResponseBody();
} else {
// something bad happened
}To run the sample
Open the sample file.
Replace bucket-name with the name of your bucket and
key-name with the name of the object to read.
response = conn.get("[bucket-name]", "[key-name]");
data = response.object.data
metadata = response.object.metadata
title = metadata["title"]To run the sample
Open the sample file.
Replace bucket-name with the name of your bucket and
key-name with the name of the object to read.
response = conn.get("[bucket-name]", "[key-name]");
data = response.object.data
metadata = response.object.metadata
title = metadata["title"]The following is an example of an HTTP request.
# get object request GET /[bucket-name]/[key-name] HTTP/1.0 Date: Wed, 08 Mar 2006 04:06:18 GMT Authorization: AWS [aws-access-key-id]:[header-signature] Host: s3.amazonaws.com # get object response HTTP/1.1 200 OK x-amz-id-2: FbGpiykb9oJEdJd0bcfwkL6S3lc06X0y7XSeA/GWyRdvlNEZ0irthljxKoeGFfB6 x-amz-request-id: 9298531013923634 Date: Wed, 08 Mar 2006 04:06:18 GMT Last-Modified: Wed, 08 Mar 2006 04:06:16 GMT ETag: "54b0c58c7ce9f2a8b551351102ee0938" x-amz-meta-title: my title Content-Type: text/plain Content-Length: 14 Connection: keep-alive Server: AmazonS3 this is a test
Deleting an object removes the object key from your bucket and makes the object
permanently irretrievable.. To delete an object, send an HTTP DELETE request to the URL that identifies the object you want to delete.
Be sure to include the required, authentication information.
The following sample code snippets how to delete an Amazon S3 object.
To run the sample
Open the sample file.
Replace bucket-name with the name of your bucket and
key-name with the name of the object to delete.
Response response = conn.delete("[bucket-name]", "[key-name]", null);
if (response.connection.getResponseCode() == 204) {
// object was deleted
} else {
// something bad happened
}This example uses AWS libraries. For more information, see AWS Libraries.
To run the sample
Open the sample file.
Replace bucket-name with the name of your bucket and
key-name with the name of the object to delete.
static void DeletingAnObject()
{
// all future examples assume this:
AmazonS3 client = Amazon.AWSClientFactory.CreateAmazonS3Client(secretKeyID, secretAccessKeyID);
try
{
DeleteObjectRequest request = new DeleteObjectRequest();
request.WithBucketName("[bucket-name]")
.WithKey("[key-name]");
DeleteObjectResponse response = client.DeleteObject(request);
response.Dispose();
}
catch (AmazonS3Exception ex)
{
// Something bad happened
}
}
To run the sample
Open the sample file.
Replace bucket-name with the name of your bucket and
key-name with the name of the object to delete.
$conn->delete("[bucket-name]", "[key-name]");
if ($response->http_response->code == 204) {
# object was deleted
} else {
# something bad happened
}To run the sample
Open the sample file.
Replace bucket-name with the name of your bucket and
key-name with the name of the object to delete.
$req =& new HTTP_Request("http://s3.amazonaws.com/[bucket-name]/[key-name]");
$req->setMethod("DELETE");
setAuthorizationHeader($req);
$req->sendRequest();
if ($req->getResponseCode() == 204) {
// bucket was deleted
} else {
// something bad happened
}To run the sample
Open the sample file.
Replace bucket-name with the name of your bucket and
key-name with the name of the object to delete.
conn.delete("[bucket-name]", "[key-name]");
if response.http_response.status == 204
# object was deleted
else
# something bad happened
endTo run the sample
Open the sample file.
Replace bucket-name with the name of your bucket and
key-name with the name of the object to delete.
conn.delete("[bucket-name]", "[key-name]");
if response.http_response.status == 204:
# object was deleted
else:
# something bad happenedThe following is an example of an HTTP request.
# delete object request DELETE /[bucket-name]/[key-name] HTTP/1.0 Date: Wed, 08 Mar 2006 04:06:19 GMT Authorization: AWS [aws-access-key-id]:[header-signature] Host: s3.amazonaws.com # delete object response HTTP/1.1 204 No Content x-amz-id-2: RvtfYQa0bFoavLma0eYJ1tgK17N/N6AWs6VQOUBSdzNTXwTL5W9BGIxt+D6gK+7I x-amz-request-id: 6F7B7DB829785419 Date: Wed, 08 Mar 2006 04:06:19 GMT Connection: keep-alive Server: AmazonS3
You can retrieve an ordered list of keys for objects in your bucket using an HTTP
GET request. To help narrow the list, you can specify a key
prefix to ensure that Amazon S3 returns only keys matching the prefix. For each key
returned, the List operation returns some basic information about
the object represented by the key, including:
The size of the object
A time stamp that specifies when the object was last modified
An identifier for the user that last modified the object
Amazon S3 returns the identifier only if you are the bucket owner
The following sample code snippets demonstrate how to list objects.
To run the sample
Open the sample file.
Replace bucket-name with the name of your
bucket.
Use the following sample to test different list operations.
// simple list
ListBucketResponse response =
conn.listBucket("[bucket-name]", null, null, null, null);
List objects = response.entries;
for (Iterator it = objects.iterator(); it.hasNext(); ) {
ListEntry entry = (ListEntry)it.next();
System.out.println("key = " + entry.key + " size = " + entry.size);
}
// list only things starting with "foo"
response = conn.listBucket("[bucket-name]", "foo", null, null, null);
// list only things that come after "bar" alphabetically
response = conn.listBucket("[bucket-name]", null, "bar", null, null);
// only list 3 things
response = conn.listBucket("[bucket-name]", null, null, new Integer(3), null);This example uses AWS libraries. For more information, see AWS Libraries.
To run the sample
Open the sample file.
Replace [bucket-name] with the name of your bucket. Also,
replace secretKeyID and secretAccessKeyID with your personal values.
Use the following sample to test different list operations.
static void ListingObjects()
{
// all future examples assume this:
AmazonS3 client = Amazon.AWSClientFactory.CreateAmazonS3Client(secretKeyID, secretAccessKeyID);
// simple list
ListObjectsRequest request = new ListObjectsRequest();
request.BucketName = "[bucket-name]";
ListObjectsResponse response = client.ListObjects(request);
foreach (S3Object entry in response.S3Objects)
{
Console.WriteLine("key = {0} size = {1}", entry.Key, entry.Size);
}
// list only things starting with "foo"
request.WithPrefix("foo");
response = client.ListObjects(request);
// list only things that come after "bar" alphabetically
request.WithPrefix("")
.WithMarker("bar");
response = client.ListObjects(request);
// only list 3 things
request.WithPrefix("")
.WithMarker("")
.WithMaxKeys("3");
response = client.ListObjects(request);
response.Dispose();
}
To run the sample
Open the sample file.
Replace bucket-name with the name of your
bucket.
Use the following sample to test different list operations.
# simple list
my $response = $conn->list_bucket("[bucket-name]");
foreach my $entry (@{$response->entries}) {
print "key = $entry->{Key} size = $entry->{Size}\n";
}
# list only things starting with "foo"
$response = $conn->list_bucket("[bucket-name]", {prefix => "foo"});
# list only things that come after "bar" alphabetically
$response = $conn->list_bucket("[bucket-name]", {marker => "bar"});
# only list 3 things
$response = $conn->list_bucket("[bucket-name]", {"max-keys" => 3});To run the sample
Open the sample file.
Replace bucket-name with the name of your
bucket.
Use the following sample to test different list operations.
$req =& new HTTP_Request("http://s3.amazonaws.com/[bucket-name]");
$req->setMethod("GET");
setAuthorizationHeader($req);
$req->sendRequest();
if ($req->getResponseCode() == 200) {
$listXml = $req->getResponseBody();
} else {
// something bad happened
}
// list only things starting with "foo"
$req =& new HTTP_Request("http://s3.amazonaws.com/[bucket-name]/?prefix=foo");
...
// list only things that come after "bar" alphabetically
$req =& new HTTP_Request("http://s3.amazonaws.com/[bucket-name]/?marker=bar");
...
# only list 3 things
$req =& new HTTP_Request("http://s3.amazonaws.com/[bucket-name]/?max-keys=3");
...To run the sample
Open the sample file.
Replace bucket-name with the name of your
bucket.
Use the following sample to test different list operations.
response = conn.list_bucket("[bucket-name]");
response.entries.each do |entry|
print "key = #{entry.key} size = #{entry.size}\n"
end
# list only things starting with "foo"
response = conn.list_bucket("[bucket-name]", {"prefix" => "foo"});
# list only things that come after "bar" alphabetically
response = conn.list_bucket("[bucket-name]", {"marker" => "bar"});
# only list 3 things
response = conn.list_bucket("[bucket-name]", {"max-keys" => "3"});To run the sample
Open the sample file.
Replace bucket-name with the name of your
bucket.
Use the following sample to test different list operations.
# simple list
response = conn.list_bucket("[bucket-name]");
for entry in response.entries:
print "key = %s size = %d" % (entry.key, entry.size)
# list only things starting with "foo"
response = conn.list_bucket("[bucket-name]", {"prefix": "foo"});
# list only things that come after "bar" alphabetically
response = conn.list_bucket("[bucket-name]", {"marker": "bar"});
# only list 3 things
response = conn.list_bucket("[bucket-name]", {"max-keys" => "3"});The following is an example of an HTTP request.
# list bucket request
GET /[test-bucket] HTTP/1.0
Date: Wed, 08 Mar 2006 04:06:17 GMT
Authorization: AWS [aws-access-key-id]:[header-signature]
Host: s3.amazonaws.com
# list bucket response (xml pretty formatted)
HTTP/1.1 200 OK
x-amz-id-2: 0rSP+1mPucqZ95lYmd53HsgDr6fi2KK8j1uNHz81AngfeOAIaVpNnOBLQ/B9pXJ/
x-amz-request-id: 317FD4EE0A1984DD
Date: Wed, 08 Mar 2006 04:06:17 GMT
Content-Type: application/xml
Connection: close
Server: AmazonS3
<?xml version="1.0" encoding="UTF-8"?>
<ListBucketResult xmlns="http://webservices.amazon.com/schema/request">
<Name>[bucket-name]</Name>
<Prefix/>
<Marker/>
<MaxKeys>1000</MaxKeys>
<IsTruncated>false</IsTruncated>
<Contents>
<Key>>[key-name]</Key>
<LastModified>2006-03-07T20:06:18.000-08:00</LastModified>
<ETag>"54b0c58c7ce9f2a8b551351102ee0938"</ETag>
<Size>14</Size>
<Owner>
<ID>AmazonCustomer|[amazon-id]</ID>
<DisplayName>[display-name]</DisplayName>
</Owner>
<StorageClass>STANDARD<StorageClass>
</Contents>
</ListBucketResult>Your input is important to us to help make our documentation helpful and easy to use. Please take a minute to give us your feedback on how well we were able to help you get started using Amazon S3. Just click this Documentation Feedback link. Thank you.
Now that you've used this guide to upload, download, delete, and list data in Amazon S3, you've become familiar with the architecture of the system, some of its basic functionality, and the kind of responses you can expect. The next section explains how to learn more about Amazon S3 and how to implement advanced Amazon S3 functionality in your applications.