# <img className="page-icon" src="/img/icons/s3.svg" alt="" /> Amazon S3

Go from files in a bucket to a tested data contract in about five minutes. Works with S3 and any S3-compatible endpoint (e.g. MinIO), for data in CSV, JSON, Delta, or Parquet format. You can also check the files themselves instead of their contents, with [metadata checks](#metadata-checks) on size, content type, age, naming, and number of files, whatever their format.

For tables in an Amazon S3 table bucket, use the dedicated [Amazon S3 Tables guide](./s3-tables.md) with `type: iceberg` instead.

## 1. Install

```bash
uv tool install --python python3.11 --upgrade 'datacontract-cli[s3]'
```

See [Installation](../installation.md) for pip, pipx, and Docker.

## 2. Authenticate

The easiest way is to sign in to AWS once — the CLI picks the session up, so no key is stored anywhere:

```bash
aws sso login   # or any other way of getting an AWS session
```

Prefer static keys? Set them directly and they are used instead:

```bash
# .env
DATACONTRACT_S3_REGION=eu-central-1
DATACONTRACT_S3_ACCESS_KEY_ID=AKIAXV5Q5QABCDEFGH
DATACONTRACT_S3_SECRET_ACCESS_KEY=93S7LRrJcqLaaaa/XXXXXXXXXXXXX
```

Public buckets need neither: with nothing configured the objects are read unsigned.

## 3. Create a contract from your files

Import the schema straight from the bucket. This also generates a ready-to-test `servers` block:

```bash
datacontract import s3 \
  --source 's3://my-bucket/orders/*.json' \
  --output datacontract.yaml
```

The format is taken from the file suffix; pass `--format` for Delta tables, which have none. Add `--endpoint-url` for an S3-compatible store such as MinIO.

The import reads only the field names and types. Properties like `required` cannot be inferred from the files and need to be adjusted manually.

## 4. Test the actual data

```bash
datacontract test datacontract.yaml
```

```
Testing datacontract.yaml
Server: production (type=s3, format=json, location=s3://my-bucket/orders/*.json)
╭────────┬─────────────────────────────────────────────────┬──────────┬─────────╮
│ Result │ Check                                           │ Field    │ Details │
├────────┼─────────────────────────────────────────────────┼──────────┼─────────┤
│  ...   │                                                 │          │         │
│ passed │ Check that field 'order_id' is present          │ order_id │         │
│ passed │ Check that field order_id has no missing values │ order_id │         │
│  ...   │                                                 │          │         │
╰────────┴─────────────────────────────────────────────────┴──────────┴─────────╯
🟢 Data contract is valid. Ran 11 checks. Took 3.6 seconds.
```

## 5. Let it catch a violation

The contract becomes valuable when it detects drift. Tighten an expectation — for example, add a quality rule:

```yaml
schema:
  - name: orders
    # ...
    quality:
      - type: sql
        description: No order has a negative total
        query: SELECT COUNT(*) FROM orders WHERE order_total < 0
        mustBe: 0
```

Run `datacontract test datacontract.yaml` again: every violation is listed as an error, and the command exits with code `1` — ready for [CI/CD and scheduled runs](../scheduling/index.md) so you catch drift before your consumers do.

## Metadata checks

Instead of reading the file contents, you can check the files themselves: their size, content type, age, naming, and number. Set the server's `format` to `metadata`; each of its schemas then describes the objects at the server `location`, one row per object, and its properties name object attributes:

```yaml
servers:
  - server: production
    type: s3
    location: s3://my-bucket/exports/nightly/  # a prefix, or a glob like s3://my-bucket/exports/*/*.png
    format: metadata

schema:
  - name: nightly_export_files
    quality:
      - metric: rowCount
        mustBeGreaterThan: 0
    properties:
      - name: name
        logicalType: string
        logicalTypeOptions:
          pattern: "^exports/nightly/[0-9]{4}-[0-9]{2}-[0-9]{2}/.*\\.png$"
      - name: contentType
        logicalType: string
        quality:
          - metric: invalidValues
            arguments:
              validValues: [image/png]
            mustBe: 0
      - name: size
        logicalType: integer
        logicalTypeOptions:
          maximum: 5242880  # 5 MiB
      - name: lastModified
        logicalType: timestamp
        logicalTypeOptions:
          minimum: "2026-01-01T00:00:00Z"

slaProperties:
  - property: freshness
    value: 24
    unit: h
    element: nightly_export_files.lastModified
```

Every check works on these properties as on the columns of a table: `required`, types, patterns, ranges, the quality metrics, SQL rules, `--filter`, and the freshness and retention service levels. No file is downloaded. To test both the contents and the metadata of the same files, declare two servers and select one with `--server`.

| Property | Type | S3 attribute |
|---|---|---|
| `name` | `string` | the object key |
| `size` | `integer` | size in bytes |
| `lastModified` | `timestamp` | when the object was written; S3 objects are immutable, so this is when the current version was created |
| `etag` | `string` | entity tag |
| `storageClass` | `string` | e.g. `STANDARD`, `GLACIER` |
| `contentType` | `string` | `Content-Type` |
| `contentEncoding` | `string` | `Content-Encoding` |
| `contentLanguage` | `string` | `Content-Language` |
| `contentDisposition` | `string` | `Content-Disposition` |
| `cacheControl` | `string` | `Cache-Control` |
| `serverSideEncryption` | `string` | e.g. `AES256`, `aws:kms` |
| `versionId` | `string` | version ID, in a versioned bucket |
| `metadata` | `object` | the user-defined metadata (`x-amz-meta-*`), see below |

The user-defined metadata is an `object` whose properties are the metadata keys, so each key is checked like a column:

```yaml
      - name: metadata
        logicalType: object
        properties:
          - name: owner  # x-amz-meta-owner
            logicalType: string
            required: true
            logicalTypeOptions:
              pattern: "^team-"
```

Declared without `properties`, `metadata` is a map of all keys, for SQL rules such as `metadata['owner'] IS NOT NULL`. S3 stores the keys in lower case.

The properties from `contentType` on, `metadata` included, cost one `HeadObject` request per object, so they are only fetched when the schema declares one of them. The identity needs `s3:ListBucket`, plus `s3:GetObject` for those.

## Reference

All authentication options and the data type handling per file format: **[S3 Reference](../reference/s3.md)**.

CSV files are read as UTF-8 unless the server declares an `encoding` (ODCS v3.2.0), such as `ISO-8859-1` or `UTF-16`. JSON files are always read as UTF-8.

## Troubleshooting

- **`403 Forbidden` / `Access Denied`** — the key pair lacks `s3:GetObject`/`s3:ListBucket` on the location, or `DATACONTRACT_S3_REGION` doesn't match the bucket's region.
- **`No files found that match the pattern`** — check the `location` glob; it matches object keys, not directories.
- **MinIO / S3-compatible storage fails to connect** — set `endpointUrl` in the `servers` block; the CLI then switches to path-style addressing.
