Twitter (X) API to Amazon S3: Partitioned JSONL and Parquet You Can Query with Athena

By TwitterAPI.io Team•14 min read
Diagram of a Twitter (X) API poller writing gzip JSONL to a raw S3 prefix and Parquet to a curated prefix, queried by Athena with partition projection
Raw and curated prefixes on S3, with bytes per post measured on 1,443 posts collected in 2026.
TL;DR
  • Layout: one bucket, two prefixes: tweets/raw/dt=YYYY-MM-DD/ (gzip JSONL, every field) and tweets/curated/dt=YYYY-MM-DD/ (Parquet, 20 columns). Re-running a day overwrites the same keys.
  • Measured size: 5,129 B per post raw, 915 B as JSONL.gz, 401 B as Parquet zstd on 140-post daily files (12.79x smaller than raw).
  • Small files hurt Parquet: on days of 3-70 posts the same Parquet averaged 805 B per post, only 6.44x smaller; one week-long file was 17.8% smaller than seven daily ones.
  • Athena: use partition projection on dt (no MSCK REPAIR, no crawler). A 3-column query read 2.0% of Parquet column bytes; the text column alone is 80.1%.
  • Cost: Athena bills $5 per TB scanned with a 10 MB minimum per query (about $0.00005); 1 million posts as Parquet is 0.373 GB, about $0.0086 a month in S3 Standard.
  • Lifecycle: all 21 daily objects of a low-volume search were under 128 KB in gzip and Parquet, so S3 Lifecycle will not transition them by default. Compact first, then tier.

This page covers the storage and query side of getting Twitter (X) data into AWS: the S3 key layout, the file format, the Athena table and the lifecycle rules. The compute side (an EventBridge schedule, a Lambda poller and SQS fan-out) is in our Twitter API on AWS Lambda guide; the job on this page can run inside that Lambda function, on a cron host, or in a CI runner, and the layout stays the same.

Searches for "twitter s3" and "tweets to s3" mostly land on tutorials that write one JSON object per tweet with Tweepy and boto3. That works for a demo and then turns into millions of tiny objects that are slow to list, awkward to query and too small for lifecycle rules. Instead of repeating that pattern we measured the alternatives: we pulled 1,443 real posts from two searches, wrote them as raw JSONL, gzip JSONL and Parquet in a dt= layout, and ran the sample query with DuckDB on the files. Every size on this page comes from that run.

Everything AWS-specific here (Athena SerDe names, partition projection properties, compression handling, lifecycle constraints and prices) was checked against the AWS documentation and pricing pages. We did not create AWS resources for this page: the sizes are real files on disk, the queries ran locally in DuckDB, and the Athena SQL follows the AWS docs.

Bytes per post on S3: raw JSONL vs zstd Parquet

5,129 B vs 401 B (12.79x smaller)

01 — Section

The layout: one bucket, a raw prefix and a curated prefix

A layout that ages well keeps two copies with different jobs. The raw copy is the API response exactly as returned, so you can re-derive anything later when you need a field you did not think of. The curated copy is a flat table with the columns your queries actually use, in a columnar format that Athena can read selectively.

PrefixFormatWhat it holdsWho reads it
tweets/raw/dt=YYYY-MM-DD/JSONL, gzipevery field of every postre-processing, audits
tweets/curated/dt=YYYY-MM-DD/Parquet, zstd20 flat columnsAthena, dashboards
tweets/raw-monthly/month=YYYY-MM/JSONL, gzipcompacted raw, one object per monthlifecycle tiering

Why dt= and not 2026/12/03/. Hive-style key=value folder names let Athena treat dt as a partition column. With partition projection you tell Athena the format and range of dt once in the table properties, and it computes the S3 locations itself instead of calling the AWS Glue catalog for each partition, so you never run MSCK REPAIR TABLE or a crawler after a new day lands.

Why UTC days. The API returns createdAt as a UTC timestamp string (format %a %b %d %H:%M:%S %z %Y, offset +0000), and Athena projects date partitions in UTC at query time per the AWS docs. Cutting days in UTC keeps the job, the keys and the queries on one clock. Use since_time and until_time (Unix seconds) inside the search query to cut the day exactly.

One object per day, not one per post. Every PUT costs $0.005 per 1,000 requests in S3 Standard (US East), and every object Athena opens is a GET. One object per day is 30 PUTs a month; one object per post or per minute is tens of thousands, and those tiny objects also fall below the size lifecycle rules act on (more below).

02 — Section

Step 1: pull one UTC day and write both copies

The job below is the whole ingestion path. It asks /twitter/tweet/advanced_search for one UTC day of a query with queryType=Latest, follows next_cursor while has_next_page is true, de-duplicates by id, then writes the gzip JSONL and the Parquet copy with two put_object calls. It takes an optional YYYY-MM-DD argument so the same script backfills older days.

Idempotent by key. A day always writes to part-0000 under its own dt= prefix, so a retry overwrites instead of duplicating. If one day can exceed what you want in a single object, write part-0001, part-0002 and so on; Athena reads every file under the partition prefix.

Explicit Parquet schema. Passing SCHEMA keeps column types stable on days where, for example, no post has a hashtag (an inferred schema would type that empty list column as null and break the table). created_at is written as a millisecond timestamp, which maps to Athena's timestamp type.

Fixed pacing. The one-second sleep between pages keeps a single job well under the request limits in the rate-limit calculator; a day of a narrow query is usually 1 to 4 pages.

python
"""Archive one UTC day of X (Twitter) search results to Amazon S3.

Writes two objects per day:
  s3://<bucket>/tweets/raw/dt=YYYY-MM-DD/part-0000.jsonl.gz      (every field the API returned)
  s3://<bucket>/tweets/curated/dt=YYYY-MM-DD/part-0000.parquet   (20 columns, zstd)
Re-running a day overwrites the same two keys, so the job is safe to retry.
pip install requests boto3 pyarrow
"""
import gzip
import io
import json
import os
import sys
import time
from datetime import datetime, timedelta, timezone

import boto3
import pyarrow as pa
import pyarrow.parquet as pq
import requests

API_KEY = os.environ["TWITTERAPI_IO_KEY"]
BUCKET = os.environ["TWEETS_BUCKET"]
BASE = "https://api.twitterapi.io"
QUERY = '("Amazon S3" OR "AWS S3" OR "S3 bucket") lang:en -filter:retweets'
s3 = boto3.client("s3")

SCHEMA = pa.schema([
    ("tweet_id", pa.string()), ("created_at", pa.timestamp("ms")), ("lang", pa.string()),
    ("text", pa.string()), ("like_count", pa.int64()), ("retweet_count", pa.int64()),
    ("reply_count", pa.int64()), ("quote_count", pa.int64()), ("view_count", pa.int64()),
    ("bookmark_count", pa.int64()), ("is_reply", pa.bool_()), ("conversation_id", pa.string()),
    ("has_media", pa.bool_()), ("media_types", pa.string()),
    ("hashtags", pa.list_(pa.string())), ("urls", pa.list_(pa.string())),
    ("author_id", pa.string()), ("author_username", pa.string()),
    ("author_followers", pa.int64()), ("author_blue", pa.bool_()),
])


def fetch_day(day_start):
    """Every post that matches QUERY between day_start and day_start + 24 h (UTC)."""
    since = int(day_start.timestamp())
    params = {"query": f"{QUERY} since_time:{since} until_time:{since + 86400}",
              "queryType": "Latest"}
    found = {}
    while True:
        r = requests.get(f"{BASE}/twitter/tweet/advanced_search", params=params,
                         headers={"X-API-Key": API_KEY}, timeout=30)
        r.raise_for_status()
        body = r.json()
        for t in body.get("tweets", []):
            found[t["id"]] = t          # de-duplicate across pages
        if not body.get("has_next_page") or not body.get("next_cursor"):
            break
        params["cursor"] = body["next_cursor"]
        time.sleep(1.0)                 # fixed pacing between pages
    return list(found.values())


def to_row(t):
    created = datetime.strptime(t["createdAt"], "%a %b %d %H:%M:%S %z %Y")
    media = (t.get("extendedEntities") or {}).get("media") or []
    ent = t.get("entities") or {}
    a = t.get("author") or {}
    return {
        "tweet_id": str(t["id"]),
        "created_at": created.astimezone(timezone.utc).replace(tzinfo=None),
        "lang": t.get("lang"),
        "text": t.get("text") or "",
        "like_count": t.get("likeCount") or 0,
        "retweet_count": t.get("retweetCount") or 0,
        "reply_count": t.get("replyCount") or 0,
        "quote_count": t.get("quoteCount") or 0,
        "view_count": t.get("viewCount") or 0,
        "bookmark_count": t.get("bookmarkCount") or 0,
        "is_reply": bool(t.get("isReply")),
        "conversation_id": str(t.get("conversationId") or ""),
        "has_media": bool(media),
        "media_types": ",".join(sorted({m.get("type", "") for m in media})),
        "hashtags": [h.get("text", "") for h in ent.get("hashtags") or []],
        "urls": [u.get("expanded_url") or u.get("url") or "" for u in ent.get("urls") or []],
        "author_id": str(a.get("id") or ""),
        "author_username": a.get("userName") or "",
        "author_followers": a.get("followers") or 0,
        "author_blue": bool(a.get("isBlueVerified")),
    }


def archive_day(day_start):
    dt = day_start.strftime("%Y-%m-%d")
    tweets = fetch_day(day_start)
    if not tweets:
        print(dt, "no posts, nothing written")
        return
    raw = "".join(json.dumps(t, ensure_ascii=False, separators=(",", ":")) + "\n"
                  for t in tweets).encode("utf-8")
    s3.put_object(Bucket=BUCKET, Key=f"tweets/raw/dt={dt}/part-0000.jsonl.gz",
                  Body=gzip.compress(raw, compresslevel=6), ContentType="application/gzip")

    table = pa.Table.from_pylist([to_row(t) for t in tweets], schema=SCHEMA)
    buf = io.BytesIO()
    pq.write_table(table, buf, compression="zstd")
    s3.put_object(Bucket=BUCKET, Key=f"tweets/curated/dt={dt}/part-0000.parquet",
                  Body=buf.getvalue(), ContentType="application/vnd.apache.parquet")
    print(dt, len(tweets), "posts,", len(raw), "raw bytes,", buf.tell(), "parquet bytes")


if __name__ == "__main__":
    # default: yesterday (UTC); or pass a day as YYYY-MM-DD to backfill
    if len(sys.argv) > 1:
        day = datetime.strptime(sys.argv[1], "%Y-%m-%d").replace(tzinfo=timezone.utc)
    else:
        today = datetime.now(timezone.utc).replace(hour=0, minute=0, second=0, microsecond=0)
        day = today - timedelta(days=1)
    archive_day(day)
03 — Section

What we measured: bytes per post, and where they go

We ran two searches and wrote each UTC day as its own partition. The first, (AWS OR "Amazon S3") lang:en -filter:retweets, is busy, so we kept the newest 140 posts of each of 7 days. The second, ("Amazon S3" OR "AWS S3" OR "S3 bucket") lang:en -filter:retweets, is narrow, so we kept every post of 21 complete days (3 to 70 posts a day, median 14). Raw JSONL is the full API object; Parquet uses the 20-column schema from Step 1.

FormatBusy query (B/post)RatioNarrow query (B/post)Ratio
Raw JSONL5,1291x5,1821x
JSONL.gz (level 6)9155.61x9715.34x
Flattened JSONL1,0005.13x1,1254.61x
Parquet snappy5289.71x9375.53x
Parquet zstd40112.79x8056.44x

Gzip alone gets you to about a fifth. JSONL.gz landed at 5.61x and 5.34x smaller than raw on the two queries, and it barely depends on file size. Athena reads gzip JSON directly as long as the key ends in .gz (it picks the codec from the file extension for JSON, CSV and TSV), so there is no reason to store uncompressed JSONL on S3.

Parquet wins on bigger files and loses its edge on small ones. With 140 posts per file, zstd Parquet was 401 bytes per post, 12.79x smaller than raw. On the narrow query's small daily files it was 805 bytes per post, only 6.44x, because every Parquet file carries a footer with the schema and column statistics. Writing the busy query's week as one file instead of seven made it 17.8% smaller again.

Snappy or zstd. Both are readable by Athena. On our files zstd was smaller in every case, which is why the curated prefix uses it.

A raw post object from the API had a median of 4,291 bytes and a mean of 5,145 bytes compact-encoded, with the largest at 38,085 bytes. The text itself is a small part of that.

Part of the post objectShare of raw bytes
author (profile embedded in every post)27.8%
card, place, article21.2%
entities + extendedEntities (links, media)19.2%
text11.3%
quoted_tweet + retweeted_tweet7.4%

The author profile repeats on every post. At 27.8% of raw bytes it is the largest single block, and it is the same profile each time the same account posts. That repetition is exactly what gzip and Parquet dictionary encoding compress away, and it is why the raw copy shrinks 5.61x under gzip.

Nested posts ride along. 7.6% of posts carried a quoted_tweet and 31.1% carried media in extendedEntities. If your curated table needs the quoted post, add quoted_tweet_id and keep the rest in raw rather than nesting a second post inside every row.

If you want to see the field list before you design a schema, the tweets to CSV guide walks through the same response fields as flat spreadsheet columns.

Bar chart of bytes per post on S3 by file format for two X searches: raw JSONL, JSONL.gz, flattened JSONL, Parquet snappy and Parquet zstd
Bytes per post by format, 1,443 posts collected in 2026. Ratios are relative to raw JSONL.
04 — Section

Step 2: create the Athena tables with partition projection

The curated table reads the Parquet prefix. The projection.* properties tell Athena that dt is a daily date in yyyy-MM-dd format over the last three years, and storage.location.template maps each value to its prefix. Per the AWS docs, enabling projection makes Athena ignore partitions registered in the Glue catalog for this table, and a projected day with no files simply returns no rows.

Relative ranges. NOW-3YEARS,NOW is one of the documented relative forms, so the range moves forward on its own. A query for a day outside the range succeeds and returns zero rows rather than failing, which is worth knowing when a backfill seems to be missing.

text is quoted in the DDL. Backticks keep the column name safe in Hive DDL; you can select it without quotes in queries.

The raw table. For the JSONL.gz prefix, use the OpenX JSON SerDe. It expects one JSON object per line (which is what the job writes) and lowercases keys by default, so createdAt becomes createdat and author.userName becomes author.username. Declare only the fields you query; the rest of each line is ignored. The AWS docs note that the OpenX SerDe can return non-deterministic results on some inputs, which is one more reason to run day-to-day queries on the Parquet table.

sql
CREATE EXTERNAL TABLE tweets_curated (
  tweet_id string, created_at timestamp, lang string, `text` string,
  like_count bigint, retweet_count bigint, reply_count bigint, quote_count bigint,
  view_count bigint, bookmark_count bigint, is_reply boolean, conversation_id string,
  has_media boolean, media_types string, hashtags array<string>, urls array<string>,
  author_id string, author_username string, author_followers bigint, author_blue boolean
)
PARTITIONED BY (dt string)
STORED AS PARQUET
LOCATION 's3://my-tweets-archive/tweets/curated/'
TBLPROPERTIES (
  'projection.enabled' = 'true',
  'projection.dt.type' = 'date',
  'projection.dt.format' = 'yyyy-MM-dd',
  'projection.dt.range' = 'NOW-3YEARS,NOW',
  'projection.dt.interval' = '1',
  'projection.dt.interval.unit' = 'DAYS',
  'storage.location.template' = 's3://my-tweets-archive/tweets/curated/dt=${dt}/'
);

CREATE EXTERNAL TABLE tweets_raw (
  id string,
  createdat string,
  `text` string,
  lang string,
  likecount bigint,
  viewcount bigint,
  isreply boolean,
  author struct<id:string, username:string, followers:bigint, isblueverified:boolean>
)
PARTITIONED BY (dt string)
ROW FORMAT SERDE 'org.openx.data.jsonserde.JsonSerDe'
WITH SERDEPROPERTIES ('ignore.malformed.json' = 'true')
LOCATION 's3://my-tweets-archive/tweets/raw/'
TBLPROPERTIES (
  'projection.enabled' = 'true',
  'projection.dt.type' = 'date',
  'projection.dt.format' = 'yyyy-MM-dd',
  'projection.dt.range' = 'NOW-3YEARS,NOW',
  'storage.location.template' = 's3://my-tweets-archive/tweets/raw/dt=${dt}/'
);
05 — Section

Step 3: the sample query, and how many bytes it reads

The query below is written for Athena (engine version 3): posts per day, median likes and the share with media over the last seven days. We did not run it in Athena; we ran the same aggregation locally with DuckDB on the Parquet files from the study (DuckDB uses median() where Athena uses approx_percentile). The row counts matched between the Parquet and the gzip JSONL copies.

Day of the busy queryPostsMedian likesWith media
day 1140030.7%
day 2140128.6%
day 3140026.4%
day 4140136.4%
day 5140128.6%
day 6140026.4%
day 7140132.9%

Column projection is the big lever. In one week-long Parquet file, the three columns this query touches (created_at, like_count, has_media) are 6,350 of 318,236 column bytes, or 2.0%. The text column alone is 80.1%. A gzip JSONL table has no columns to skip, so the same query reads every byte of every file in the selected partitions.

Partition pruning is the other. One day of the busy query was 54 KB as Parquet against 384 KB for the week; the WHERE dt >= ... filter means Athena only opens the prefixes in range.

sql
-- Athena (engine version 3): last 7 days, three columns, partition-pruned by dt
SELECT dt,
       count(*)                                   AS posts,
       approx_percentile(like_count, 0.5)         AS median_likes,
       round(100.0 * avg(IF(has_media, 1, 0)), 1) AS pct_media
FROM tweets_curated
WHERE dt >= date_format(current_date - INTERVAL '7' DAY, '%Y-%m-%d')
GROUP BY dt
ORDER BY dt;

-- The same question, run locally with DuckDB on the files this page measured
-- SELECT dt, count(*), median(like_count), round(100.0 * avg(CASE WHEN has_media THEN 1 ELSE 0 END), 1)
-- FROM read_parquet('lake/aws_latest/dt=*/part-0000.zstd.parquet', hive_partitioning = true)
-- GROUP BY dt ORDER BY dt;
Bar chart of the share of column bytes per column in a week-long Parquet file of X posts; the text column is about 80 percent
Share of column bytes per column, 980 posts in one Parquet (zstd) file, collected in 2026.
06 — Section

What it costs: Athena, S3 and the API

Athena SQL queries are billed at $5 per TB scanned, rounded up to the nearest megabyte with a 10 MB minimum per query, per the Athena pricing page (aws.amazon.com/athena/pricing). DDL statements such as CREATE TABLE and failed queries are not charged. S3 prices below are US East (N. Virginia) from aws.amazon.com/s3/pricing.

Every query in our study hit the minimum. The full busy-query week was 875 KB as JSONL.gz and 384 KB as Parquet, both far under 10 MB, so each query bills 10 MB, about $0.00005. At the measured sizes, a week of gzip JSONL reaches 10 MB at roughly 11,463 posts and a week of Parquet at roughly 26,144. Below that, format choice changes speed, not the Athena bill.

Per 1 million postsRaw JSONLJSONL.gzParquet zstd
Size4.777 GB0.852 GB0.373 GB
S3 Standard ($0.023/GB-month)$0.1099/mo$0.0196/mo$0.0086/mo
S3 Glacier Instant Retrieval ($0.004)$0.0191/mo$0.0034/mo$0.0015/mo
One Athena full scan ($5/TB)$0.0233$0.0042$0.0018

Request counts matter more than gigabytes at this scale. One object per day is 30 PUTs a month, $0.00015 at $0.005 per 1,000. One object per minute is 43,200 PUTs, $0.216 a month, and a query over that month opens 43,200 objects at $0.0004 per 1,000 GETs ($0.0173 per full scan), plus the slower listing.

The data itself is the larger line. Reading posts through TwitterAPI.io costs 15 credits per post returned, $0.15 per 1,000 posts, so 1 million posts is $150; there is a 15-credit minimum per request ($0.00015 for an empty page). The official X API lists $0.005 per post read on its pay-per-usage plan (docs.x.com/x-api/getting-started/pricing), or $5,000 for the same million, about 33x more per 1,000 posts. New accounts get free starter credits (no card, one per person or network, expiring after 31 days); see pricing for the current amount.

07 — Section

Lifecycle rules: why daily tweet files do not move to cheaper storage

Per the S3 docs, since September 2024 S3 Lifecycle does not transition objects smaller than 128 KB to any storage class by default, because the per-object transition request can cost more than the storage saved. You can override that with an ObjectSizeGreaterThan filter, but for tiny files the math usually says leave them alone.

Our daily files were below the line. On the narrow query, all 21 daily objects were under 128 KB as JSONL.gz and as Parquet (largest: 53 KB and 34 KB); even raw JSONL was under 128 KB on 15 of 21 days. At the measured bytes per post, a daily JSONL.gz object crosses 128 KB at about 143 posts a day and a daily Parquet object at about 327.

Compact, then tier. If you keep raw data for years, have a monthly job concatenate the month's daily .jsonl.gz files into one object under tweets/raw-monthly/month=YYYY-MM/ (concatenated gzip members are still a valid gzip stream), then let a lifecycle rule move those bigger objects to Standard-IA after 30 days and Glacier Instant Retrieval later. Expire the daily raw copies once the monthly file exists.

Minimum durations apply. Per the S3 pricing page, Standard-IA has a 30-day minimum storage duration and 128 KB minimum billable object size; Glacier Instant Retrieval has 90 days and 128 KB; Glacier Flexible Retrieval has 90 days and Deep Archive 180. Glacier Flexible Retrieval and Deep Archive objects must be restored before anything can read them, so keep anything Athena queries in Standard, Standard-IA or Glacier Instant Retrieval.

Is tiering worth it at all? At 0.373 GB per million posts, a curated Parquet archive of a million posts is about $0.0086 a month in S3 Standard. Tiering pays for itself on large raw archives, not on the curated table.

json
{
  "Rules": [
    {
      "ID": "raw-monthly-files-to-ia",
      "Status": "Enabled",
      "Filter": {
        "And": {
          "Prefix": "tweets/raw-monthly/",
          "ObjectSizeGreaterThan": 131072
        }
      },
      "Transitions": [
        { "Days": 30, "StorageClass": "STANDARD_IA" },
        { "Days": 120, "StorageClass": "GLACIER_IR" }
      ]
    },
    {
      "ID": "expire-daily-raw-after-compaction",
      "Status": "Enabled",
      "Filter": { "Prefix": "tweets/raw/" },
      "Expiration": { "Days": 45 }
    }
  ]
}
Line chart of daily S3 object sizes over 21 days for raw JSONL, JSONL.gz and Parquet against the 128 KB lifecycle threshold
Daily object size for 21 complete days of a narrow S3-related search, collected in 2026.
08 — Section

Other ways in, and when to pick them

Firehose instead of PUTs. If you already stream posts (for example from a webhook filter rule or a Kafka topic of tweets), Amazon Data Firehose can buffer records and write them to S3 with a time-based prefix, and the AWS docs include a partition projection example for Firehose output. The trade-off is another managed service to pay for and configure; a daily batch job is simpler when a day of latency is fine.

A warehouse instead of a lake. If your team already queries in BigQuery, Snowflake or Databricks, the S3 Parquet prefix can be their landing zone, or you can skip S3 and load directly: see Twitter API to BigQuery, Twitter data in Snowflake and Twitter API with Databricks.

Historical backfill. The script's date argument is all you need to backfill: loop over past days and call it once per day. For larger exports, the history export guide covers how far back search goes and how to split long ranges.

09 — Section

How we collected this

Question. How big are X (Twitter) search results on S3 as raw JSONL, gzip JSONL and Parquet when written one object per UTC day, what would an Athena-style query read, and do daily objects clear the 128 KB lifecycle threshold?

Queries and window. (AWS OR "Amazon S3") lang:en -filter:retweets with queryType=Latest, newest 140 posts of each of 7 consecutive UTC days (980 posts); and ("Amazon S3" OR "AWS S3" OR "S3 bucket") lang:en -filter:retweets, every post of 21 consecutive UTC days (463 posts). Collected in 2026 through /twitter/tweet/advanced_search with since_time and until_time.

Method. 106 requests (1,503 posts billed, including 3 probe pages used to choose the queries), about $0.2286 in API credits. Files written locally with Python's gzip (level 6) and pyarrow; sizes measured on disk; queries run with DuckDB 1.4.5. No AWS resources were created and Athena itself was not run. AWS prices were taken from the AWS pricing pages for US East (N. Virginia).

What the sample cannot show. Byte sizes depend on the query: posts with long text, cards or quoted posts are bigger, and accounts that post often compress better because their profile repeats. The busy query's days are the newest 140 posts, not the whole day. Athena scan sizes are computed from Parquet column chunk sizes, not read from an Athena bill.

Privacy. Search results include private individuals, so raw pages were kept out of the repository; we publish aggregates and a de-identified sample (no post IDs, URLs, text, author IDs or handles).

python
"""Archive one UTC day of X (Twitter) search results to Amazon S3.

Writes two objects per day:
  s3://<bucket>/tweets/raw/dt=YYYY-MM-DD/part-0000.jsonl.gz      (every field the API returned)
  s3://<bucket>/tweets/curated/dt=YYYY-MM-DD/part-0000.parquet   (20 columns, zstd)
Re-running a day overwrites the same two keys, so the job is safe to retry.
pip install requests boto3 pyarrow
"""
import gzip
import io
import json
import os
import sys
import time
from datetime import datetime, timedelta, timezone

import boto3
import pyarrow as pa
import pyarrow.parquet as pq
import requests

API_KEY = os.environ["TWITTERAPI_IO_KEY"]
BUCKET = os.environ["TWEETS_BUCKET"]
BASE = "https://api.twitterapi.io"
QUERY = '("Amazon S3" OR "AWS S3" OR "S3 bucket") lang:en -filter:retweets'
s3 = boto3.client("s3")

SCHEMA = pa.schema([
    ("tweet_id", pa.string()), ("created_at", pa.timestamp("ms")), ("lang", pa.string()),
    ("text", pa.string()), ("like_count", pa.int64()), ("retweet_count", pa.int64()),
    ("reply_count", pa.int64()), ("quote_count", pa.int64()), ("view_count", pa.int64()),
    ("bookmark_count", pa.int64()), ("is_reply", pa.bool_()), ("conversation_id", pa.string()),
    ("has_media", pa.bool_()), ("media_types", pa.string()),
    ("hashtags", pa.list_(pa.string())), ("urls", pa.list_(pa.string())),
    ("author_id", pa.string()), ("author_username", pa.string()),
    ("author_followers", pa.int64()), ("author_blue", pa.bool_()),
])


def fetch_day(day_start):
    """Every post that matches QUERY between day_start and day_start + 24 h (UTC)."""
    since = int(day_start.timestamp())
    params = {"query": f"{QUERY} since_time:{since} until_time:{since + 86400}",
              "queryType": "Latest"}
    found = {}
    while True:
        r = requests.get(f"{BASE}/twitter/tweet/advanced_search", params=params,
                         headers={"X-API-Key": API_KEY}, timeout=30)
        r.raise_for_status()
        body = r.json()
        for t in body.get("tweets", []):
            found[t["id"]] = t          # de-duplicate across pages
        if not body.get("has_next_page") or not body.get("next_cursor"):
            break
        params["cursor"] = body["next_cursor"]
        time.sleep(1.0)                 # fixed pacing between pages
    return list(found.values())


def to_row(t):
    created = datetime.strptime(t["createdAt"], "%a %b %d %H:%M:%S %z %Y")
    media = (t.get("extendedEntities") or {}).get("media") or []
    ent = t.get("entities") or {}
    a = t.get("author") or {}
    return {
        "tweet_id": str(t["id"]),
        "created_at": created.astimezone(timezone.utc).replace(tzinfo=None),
        "lang": t.get("lang"),
        "text": t.get("text") or "",
        "like_count": t.get("likeCount") or 0,
        "retweet_count": t.get("retweetCount") or 0,
        "reply_count": t.get("replyCount") or 0,
        "quote_count": t.get("quoteCount") or 0,
        "view_count": t.get("viewCount") or 0,
        "bookmark_count": t.get("bookmarkCount") or 0,
        "is_reply": bool(t.get("isReply")),
        "conversation_id": str(t.get("conversationId") or ""),
        "has_media": bool(media),
        "media_types": ",".join(sorted({m.get("type", "") for m in media})),
        "hashtags": [h.get("text", "") for h in ent.get("hashtags") or []],
        "urls": [u.get("expanded_url") or u.get("url") or "" for u in ent.get("urls") or []],
        "author_id": str(a.get("id") or ""),
        "author_username": a.get("userName") or "",
        "author_followers": a.get("followers") or 0,
        "author_blue": bool(a.get("isBlueVerified")),
    }


def archive_day(day_start):
    dt = day_start.strftime("%Y-%m-%d")
    tweets = fetch_day(day_start)
    if not tweets:
        print(dt, "no posts, nothing written")
        return
    raw = "".join(json.dumps(t, ensure_ascii=False, separators=(",", ":")) + "\n"
                  for t in tweets).encode("utf-8")
    s3.put_object(Bucket=BUCKET, Key=f"tweets/raw/dt={dt}/part-0000.jsonl.gz",
                  Body=gzip.compress(raw, compresslevel=6), ContentType="application/gzip")

    table = pa.Table.from_pylist([to_row(t) for t in tweets], schema=SCHEMA)
    buf = io.BytesIO()
    pq.write_table(table, buf, compression="zstd")
    s3.put_object(Bucket=BUCKET, Key=f"tweets/curated/dt={dt}/part-0000.parquet",
                  Body=buf.getvalue(), ContentType="application/vnd.apache.parquet")
    print(dt, len(tweets), "posts,", len(raw), "raw bytes,", buf.tell(), "parquet bytes")


if __name__ == "__main__":
    # default: yesterday (UTC); or pass a day as YYYY-MM-DD to backfill
    if len(sys.argv) > 1:
        day = datetime.strptime(sys.argv[1], "%Y-%m-%d").replace(tzinfo=timezone.utc)
    else:
        today = datetime.now(timezone.utc).replace(hour=0, minute=0, second=0, microsecond=0)
        day = today - timedelta(days=1)
    archive_day(day)

Researching this?Free starter credits cover end-to-end testing — Google sign-in, no card. Get a key.

10 — Questions

Questions readers ask

How do I save tweets to Amazon S3?

Run a scheduled job that pulls posts from /twitter/tweet/advanced_search for one UTC day, writes them as gzip JSONL under tweets/raw/dt=YYYY-MM-DD/, and writes a flattened Parquet copy under tweets/curated/dt=YYYY-MM-DD/ with boto3 put_object. The full script is in Step 1. Reads need no X account, only an API key.

Should I store tweets as JSON or Parquet on S3?

Both. Keep the raw API object as gzip JSONL (915 bytes per post in our run) so you can re-derive fields later, and query a flat Parquet copy (401 bytes per post with zstd). Parquet lets Athena read only the columns a query needs; a 3-column query read 2.0% of the column bytes.

How should I partition tweets in S3?

By UTC day with a Hive-style dt=YYYY-MM-DD prefix, one object (or a few) per day. Add Athena partition projection on dt so new days are queryable without crawlers or MSCK REPAIR TABLE. Partitioning by hour only makes sense at very high volume; smaller files compress worse and cost more requests.

Can Athena query gzip-compressed JSON tweets?

Yes. For JSON, CSV and TSV, Athena detects compression from the file extension, so name the objects .jsonl.gz (lowercase). Use the OpenX JSON SerDe with one post per line. Parquet is faster for repeated queries because Athena can skip columns.

How much does it cost to store and query tweets in S3?

Very little at tweet scale. In our run 1 million posts was 0.852 GB as gzip JSONL and 0.373 GB as Parquet, about $0.0196 and $0.0086 a month in S3 Standard (US East). Athena charges $5 per TB scanned with a 10 MB minimum per query, so small tables bill about $0.00005 per query. Collecting the posts is the larger cost: $0.15 per 1,000 posts through TwitterAPI.io.

Why are my tweet files not moving to S3 Glacier with a lifecycle rule?

Since September 2024, S3 Lifecycle does not transition objects under 128 KB by default. A day of a narrow search is often far smaller than that (all 21 of our daily gzip and Parquet files were). Compact daily files into monthly objects first, or add an ObjectSizeGreaterThan filter if you accept the per-object transition charge.

Do I need AWS Lambda to send tweets to S3?

No. The job is a plain Python script, so it runs on Lambda, a cron host, a container or a CI runner. If you want it serverless on a schedule, the AWS Lambda guide shows the EventBridge and SQS setup; the S3 layout on this page stays the same.

11 — Further reading

Continue

Sources & further reading
More from this series

Writing about something you built with TwitterAPI.io? Our community rewards program pays API credits for honest tutorials, build logs and videos.

Build it

Stop reading. Start building.

Starter credits cover real testing on real data. Google sign-in, no card, no application queue.

Get an API key

Already building with TwitterAPI.io? Publish an honest tutorial or build log about it and earn up to $200 a month in API credits.