AWS AWS

Simulating Amazon S3 Locally with Moto and AWS CLI

Dima Ноя 15, 2026

Introduction

Code that talks to Amazon S3 is awkward to develop and test against the real service. Every run needs credentials, every bucket a test creates stays there until something deletes it, and two developers running the same tests at once trample each other's objects. A run during a network outage fails for reasons that have nothing to do with the code.

Moto removes all of that. It is a Python library that imitates AWS services; started as a server with moto_server, it answers the same HTTP requests AWS would, from memory, on your own machine. In this tutorial we will start a Moto server, point the AWS CLI and boto3 at it, and run a full bucket and object lifecycle with each. Along the way we will hit the configuration errors a real setup produces, in the order it produces them.

A few assumptions so that every command is exact:

  • You are working in the AWS Cloud sandbox on Bytestark.com, which ships boto3, moto and the AWS CLI. Your starting folder is /home/coder/learning.
  • The sandbox has no internet access, so every request below goes to the local Moto server and nothing reaches real AWS.
  • You will need two terminals: one running the Moto server, one for everything else.

Background

Amazon S3 is AWS's object storage. Data lives in buckets, and each item in a bucket is an object identified by a key, a string such as q2-sales-report.txt that can contain slashes but is not a real folder path.

boto3 is the AWS SDK for Python. boto3.client("s3") returns a low-level client whose methods map one-to-one onto S3 API operations: create_bucket, list_objects_v2, delete_object and so on.

The AWS CLI is the aws command. aws s3api ... calls API operations directly, one command per operation; aws s3 ... offers file-oriented commands such as cp, ls and rm built on top of them.

An endpoint is the URL a client sends its requests to. By default boto3 and the CLI compute it from the service and the region, for example https://s3.us-east-1.amazonaws.com. Pointing the endpoint somewhere else is all it takes to talk to Moto instead.

Every AWS request is signed with an access key pair, and the client looks for credentials before sending anything. Moto accepts any key, but the client still insists on having one.


Practical Scenario

A data engineering team runs Python scripts that archive processed reports to S3: upload the file, list the bucket to confirm it arrived, download a report again for reprocessing, delete it once it has expired. All of it is written with boto3.

Testing these scripts against real S3 means a shared account, real credentials on every laptop and CI runner, and leftover buckets after every failed run. The team wants every developer to start from an empty, private S3 that costs nothing and disappears when they are done.

The operations team, who do not write Python, want to inspect the same buckets with the AWS CLI while a script is running. So the local S3 must be reachable by both tools at once, and both must see the same state.


The Problem

Before Moto, let's see what the archive code does in a fresh environment. Create a file:

touch s3_no_moto.py

Put this code in it:

import boto3

s3 = boto3.client("s3", region_name="us-east-1")
s3.create_bucket(Bucket="reports-bucket")


Run it:

python3 s3_no_moto.py


  File "/usr/local/lib/python3.12/site-packages/botocore/auth.py", line 429, in add_auth
    raise NoCredentialsError()
botocore.exceptions.NoCredentialsError: Unable to locate credentials


Only the end of the traceback is shown; the frames above it are boto3 preparing the request. The last frame tells you where it failed: botocore/auth.py, in add_auth. That is the step that signs the request, which happens before a single byte is sent. boto3 looked for credentials in the places it always checks (the AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment variables, then ~/.aws/credentials, then a few others), found none, and gave up.

region_name="us-east-1" picks which regional endpoint the client would talk to. Even with real credentials, the next step would be a network call to s3.us-east-1.amazonaws.com, which the sandbox cannot make, and which in an ordinary environment would create a real bucket on a real bill.

Try it: Export a fake key pair in this terminal, export AWS_ACCESS_KEY_ID=testing AWS_SECRET_ACCESS_KEY=testing, and run the script again. Predict the new last line before you look. It is no longer NoCredentialsError but botocore.exceptions.EndpointConnectionError: Could not connect to the endpoint URL: "https://reports-bucket.s3.amazonaws.com/". Signing now succeeds, so boto3 tries to reach the real S3 endpoint, and the sandbox has no route to it. Notice that the bucket name is part of the host name: by default S3 addresses a bucket as a subdomain. Close this terminal afterwards so the fake keys do not follow you into the next section.


Starting the Moto server

We need something that answers AWS requests locally. In a terminal, start Moto's server:

moto_server


WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
 * Running on http://127.0.0.1:5000
Press CTRL+C to quit


moto_server is a small web server, built on Flask, which is why its first line is Flask's standard development-server warning. Running on http://127.0.0.1:5000 says it listens only on the sandbox's loopback interface, port 5000. That is the right choice here: the only clients are the AWS CLI and boto3 running inside the same sandbox, and nothing needs to reach it from your browser.

The server accepts requests for every service Moto imitates (S3, STS, EC2, SQS and many more) on that one port, and works out from each request which service it is meant for. Everything it stores lives in the server's memory. Stopping it with Ctrl+C throws all of it away, which is exactly the clean slate the scenario asks for.

Leave this terminal running for the rest of the tutorial.

Try it: Open http://127.0.0.1:5000/ from a second terminal with curl -s http://127.0.0.1:5000/ | head -c 200; echo. Predict what comes back. It is an XML ListAllMyBucketsResult document: an unsigned GET / looks to Moto like S3's ListBuckets operation, and there are no buckets yet. Watch the Moto terminal too: it logs the request as "GET / HTTP/1.1" 200.


Pointing the AWS CLI at Moto, one error at a time

Open a second terminal. The CLI has to learn three things: where to send requests, which region to use, and which credentials to sign with. Let's give them one at a time and read each error, because these are the same errors a misconfigured real setup produces.

Start with the endpoint:

export AWS_ENDPOINT_URL=http://127.0.0.1:5000

AWS_ENDPOINT_URL is read by both the AWS CLI and boto3 and replaces the endpoint they would otherwise compute, for every service. Now ask "who am I?", the simplest call there is:

aws sts get-caller-identity


You must specify a region. You can also configure your region by running "aws configure".


Even with an explicit endpoint, the CLI wants a region: it is part of every request signature. Set one:

export AWS_DEFAULT_REGION=us-east-1
aws sts get-caller-identity


Unable to locate credentials. You can configure credentials by running "aws configure".


This is the same failure as in The Problem, from the CLI this time. Give it a key pair. Moto accepts any value, so we use obviously fake ones:

export AWS_ACCESS_KEY_ID=testing
export AWS_SECRET_ACCESS_KEY=testing
aws sts get-caller-identity


{
    "UserId": "AKIAIOSFODNN7EXAMPLE",
    "Account": "123456789012",
    "Arn": "arn:aws:sts::123456789012:user/moto"
}


The call went through, and every field in the answer is Moto's fixed fake identity. UserId is an access key id in AWS's format, the very one AWS uses in its own documentation. Account is a twelve-digit account number, and 123456789012 is Moto's default. Arn is the Amazon Resource Name of the caller: arn, partition aws, service sts, an empty region field (identities are global), the account, and the resource user/moto.

The Moto terminal logged the request:

127.0.0.1 - - [15/Nov/2026 08:03:12] "POST / HTTP/1.1" 200 -


Taken apart: the client address 127.0.0.1; two - placeholders for identity fields the server does not use; the time; the request line, method POST on path / with protocol HTTP/1.1; the status 200; and a final - for the response size, which this server does not log. STS is a query-style API: every operation is a POST to / with the operation name, Action=GetCallerIdentity, in the form body, which is why the path says nothing about what was asked.

export sets a variable only for this terminal and the programs started from it. The alternative is aws configure, which asks for the same key pair and region and writes them to ~/.aws/credentials and ~/.aws/config, so they survive new terminals. For a throw-away local setup, the environment variables are the better fit: close the terminal and nothing is left behind.

Try it: Run unset AWS_ENDPOINT_URL and repeat aws sts get-caller-identity. Predict the outcome before pressing Enter. With the endpoint gone, the CLI computes the real endpoint again, and after about ten seconds of retries it prints Could not connect to the endpoint URL: "https://sts.us-east-1.amazonaws.com/". The region you exported is now part of the host name, and the sandbox cannot reach it. Export the variable again before continuing.


S3 operations with boto3

With the server running and the second terminal configured, the archive workflow from the scenario can run end to end. Create s3_demo.py:

touch s3_demo.py
import boto3
import io

def main():
    s3 = boto3.client("s3", region_name="us-east-1", endpoint_url="http://127.0.0.1:5000")

    bucket_name = "reports-bucket"
    s3.create_bucket(Bucket=bucket_name)

    response = s3.list_buckets()
    print("Existing buckets:")
    for bucket in response["Buckets"]:
        print(f"  {bucket['Name']}")

    file_content = "Q2 2025 regional sales report."
    file_obj = io.BytesIO(file_content.encode("utf-8"))
    s3.upload_fileobj(file_obj, bucket_name, "q2-sales-report.txt")

    response = s3.list_objects_v2(Bucket=bucket_name)
    print("Files in bucket:")
    for obj in response.get("Contents", []):
        print(f"  {obj['Key']}")

    download_obj = io.BytesIO()
    s3.download_fileobj(bucket_name, "q2-sales-report.txt", download_obj)
    download_obj.seek(0)
    print("Downloaded file content:")
    print(download_obj.read().decode("utf-8"))

    s3.delete_object(Bucket=bucket_name, Key="q2-sales-report.txt")

    response = s3.list_objects_v2(Bucket=bucket_name)
    print("Files in bucket after deletion:")
    for obj in response.get("Contents", []):
        print(f"  {obj['Key']}")
    if not response.get("Contents"):
        print("  (empty)")

if __name__ == "__main__":
    main()


Run it in the second terminal, the one with the exported variables:

python3 s3_demo.py


Existing buckets:
  reports-bucket
Files in bucket:
  q2-sales-report.txt
Downloaded file content:
Q2 2025 regional sales report.
Files in bucket after deletion:
  (empty)


The script runs the whole lifecycle against Moto. Part by part:

  • boto3.client("s3", region_name="us-east-1", endpoint_url="http://127.0.0.1:5000") creates the client. endpoint_url sends every request to Moto. The credentials come from the exported AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY, through the same lookup that failed in The Problem.
  • s3.create_bucket(Bucket=bucket_name) creates reports-bucket, and s3.list_buckets() returns a dictionary whose "Buckets" list has one entry per bucket.
  • io.BytesIO(file_content.encode("utf-8")) wraps the bytes of the report in a file-like object kept in memory, and upload_fileobj uploads it under the key q2-sales-report.txt. No temporary file is written to disk.
  • list_objects_v2 lists the bucket's objects. When the bucket is empty, the response has no "Contents" key at all, not an empty list, which is why the script uses response.get("Contents", []); indexing with response["Contents"] would raise KeyError after the deletion.
  • download_fileobj writes the object into a fresh BytesIO. Writing leaves the read position at the end, so seek(0) moves it back to the start before read(); without it, read() returns b"".
  • delete_object removes the object, and the final listing confirms the bucket is empty.

The Moto terminal shows how each call became an HTTP request:

127.0.0.1 - - [15/Nov/2026 08:03:12] "PUT /reports-bucket HTTP/1.1" 200 -
127.0.0.1 - - [15/Nov/2026 08:03:12] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [15/Nov/2026 08:03:12] "PUT /reports-bucket/q2-sales-report.txt HTTP/1.1" 200 -
127.0.0.1 - - [15/Nov/2026 08:03:12] "GET /reports-bucket?list-type=2&encoding-type=url HTTP/1.1" 200 -
127.0.0.1 - - [15/Nov/2026 08:03:12] "HEAD /reports-bucket/q2-sales-report.txt HTTP/1.1" 200 -
127.0.0.1 - - [15/Nov/2026 08:03:12] "GET /reports-bucket/q2-sales-report.txt HTTP/1.1" 200 -
127.0.0.1 - - [15/Nov/2026 08:03:12] "DELETE /reports-bucket/q2-sales-report.txt HTTP/1.1" 204 -
127.0.0.1 - - [15/Nov/2026 08:03:12] "GET /reports-bucket?list-type=2&encoding-type=url HTTP/1.1" 200 -


Unlike STS, S3 is a REST API, so the method and path carry the meaning. PUT /reports-bucket creates the bucket. GET / lists buckets. PUT /reports-bucket/<key> stores an object. GET /reports-bucket?list-type=2 is ListObjectsV2, the 2 in list_objects_v2. The download is two requests: download_fileobj first sends HEAD to learn the object's size, so that it can split large files into parallel parts, then GET for the content. DELETE answers 204 No Content, success with an empty body.

Try it: Delete , endpoint_url="http://127.0.0.1:5000" from the boto3.client(...) call and run the script again in the same terminal. Predict the output. It is the same as before, because boto3 also reads AWS_ENDPOINT_URL from the environment, so the exported variable now does the job the argument did. Now open a brand-new terminal, without any exports, and run the script there: it fails with NoCredentialsError again, because the variables lived only in the other terminal. Put the argument back so that the script names its endpoint explicitly.


The same bucket from the AWS CLI

The operations team wants to look at the same storage without writing Python. Because the CLI in the second terminal points at the same Moto server, it sees exactly the state boto3 created. Let's create a second bucket from the CLI and then work on the first one.

aws s3api create-bucket --bucket audit-bucket


{
    "Location": "/audit-bucket"
}


aws s3api list-buckets


{
    "Buckets": [
        {
            "Name": "reports-bucket",
            "CreationDate": "2026-11-15T08:03:12.000Z"
        },
        {
            "Name": "audit-bucket",
            "CreationDate": "2026-11-15T08:03:13.000Z"
        }
    ],
    "Owner": {
        "DisplayName": "webfile",
        "ID": "bcaf1ffd86f41161ca5fb16fd081034f"
    },
    "Prefix": null
}


Both buckets are there: reports-bucket, created by the Python script, and audit-bucket, created by the CLI a moment ago. Your dates will be the time you ran the commands. aws s3api commands print the API's response as JSON, field for field: Location is the path of the new bucket, and Owner is Moto's fixed fake account owner. Each s3api command is one API operation, named the same way as the boto3 method in kebab case: list-buckets is list_buckets.

Now upload, list, download and delete an object in reports-bucket with the higher-level aws s3 commands:

echo "Q2 2025 regional sales report." > q2-sales-report.txt
aws s3 cp q2-sales-report.txt s3://reports-bucket/q2-sales-report.txt
aws s3 ls s3://reports-bucket/
aws s3 cp s3://reports-bucket/q2-sales-report.txt downloaded-report.txt
cat downloaded-report.txt
aws s3 rm s3://reports-bucket/q2-sales-report.txt
aws s3 ls s3://reports-bucket/


upload: ./q2-sales-report.txt to s3://reports-bucket/q2-sales-report.txt
2026-11-15 08:03:14         31 q2-sales-report.txt
download: s3://reports-bucket/q2-sales-report.txt to ./downloaded-report.txt
Q2 2025 regional sales report.
delete: s3://reports-bucket/q2-sales-report.txt


s3://reports-bucket/q2-sales-report.txt is the CLI's way of writing "bucket reports-bucket, key q2-sales-report.txt". aws s3 cp copies in either direction depending on which side is the s3:// path, and prints one upload: or download: line per file once it is done. The ls line has three columns: the object's last-modified time, its size in bytes, and its key. The size is 31 because echo adds a newline to the 30 characters of the sentence. The last ls prints nothing at all, because the bucket is empty again.

aws s3 is the convenient layer: cp picks between a single upload and a multipart one depending on the file size, and ls formats the listing for humans. When you need an operation or a parameter it does not expose, aws s3api has every one.

Try it: Stop the Moto server with Ctrl+C, start it again with moto_server, and run aws s3api list-buckets in the second terminal. Predict how many buckets it lists. It lists none, "Buckets": [], because all of Moto's state lived in the memory of the process you just stopped. That is the isolation the scenario asked for: every run of the server starts from an empty S3.


Summary

We ran a local S3 with moto_server, worked through the CLI's configuration errors one at a time, and ran the same bucket and object lifecycle from boto3 and from the AWS CLI against shared in-memory state. Moto's other mode, the @mock_aws decorator that intercepts boto3 inside a single Python process without any server, is the natural next step for unit tests and is not covered here.

  • moto_server answers AWS API requests for many services on 127.0.0.1:5000 and keeps everything in memory, so a restart is a clean slate.
  • Clients need an endpoint, a region and credentials, and they fail in that order: You must specify a region, then Unable to locate credentials.
  • AWS_ENDPOINT_URL redirects both the AWS CLI and boto3 to Moto without code changes; an explicit endpoint_url= argument does the same for one client.
  • Moto accepts any credentials, but clients sign every request and refuse to send without a key pair; exported test keys last only as long as the terminal.
  • list_objects_v2 omits Contents entirely for an empty bucket, so read it with response.get("Contents", []).
  • After writing into a BytesIO, call seek(0) before reading it back, or read() returns empty bytes.
  • aws s3api maps one command to one API operation and prints raw JSON; aws s3 offers file-style cp, ls and rm on top of them.
  • Moto's request log shows which S3 operation each call became: PUT creates, GET lists or reads, HEAD checks size, DELETE removes.

Чтобы получить доступ к облачной лаборатории, необходимо войти в систему.

Войти