Twitter (X) Airtable Integration: Save Tweets to a Base With a Script

By TwitterAPI.io Team•17 min read
Diagram of a Twitter (X) to Airtable pipeline in four boxes. Keyword feed: /twitter/tweet/advanced_search with query plus since_time and until_time, next_cursor pages of 20, X-API-Key header at $0.15 per 1,000 posts. Your script on cron: map tweet to fields, drop ids already sent, chunk into lists of 10. Airtable Web API: PATCH /v0/baseId/table with performUpsert and fieldsToMergeOn Tweet ID, Bearer token, 5 requests per second per base. Base and table: one row per post, createdRecords and updatedRecords. Footer: one keyword feed over 7 days collected in 2026, 52.6 rows a day, 5.7 Airtable write requests a day, 335 duplicate rows absorbed by the upsert.
The whole integration: search, dedupe by tweet id, upsert in batches of 10. Diagram; the footer numbers come from the study below.
TL;DR
  • The pipeline: search X with /twitter/tweet/advanced_search (keyword plus since_time:/until_time:), map each post to fields, then PATCH /v0/{baseId}/{table} with performUpsert on a Tweet ID field, 10 records per request.
  • Airtable limits verified this session: 5 requests per second per base (a 429 means wait 30 seconds), up to 10 records per create or update request, 1 to 3 merge fields for an upsert, personal access tokens with data.records:write.
  • Real week, one keyword: 368 unique posts in 7 days, 52.6 rows a day, peak 87; 40 Airtable write requests for the whole week.
  • Why the upsert matters: two passes over each day (a scheduled run with a 1-hour overlap plus a catch-up re-read) delivered 703 posts for 368 rows; the tweet-id merge absorbed 335 repeats, and the re-read added 10 posts the first pass had not returned.
  • Cost: about $0.24 a month of X data for one pass a day ($0.46 with the re-read), versus about $7.89 for the same posts on the official X API at $0.005 per post read.
  • The real ceiling is records: at 52.6 rows a day a Free base (1,000 records) is full in 19 days, Team (50,000) lasts about 951 days, Business (125,000) about 2,378.

Search for a Twitter Airtable integration and you get a wall of connector listings: Zapier, Make, IFTTT, n8n, Pipedream and a dozen smaller automation platforms, each with a "new tweet, create record" template. They run on the platform's own schedule and connection. None of the listings shows what the data actually looks like once it lands, how many rows a feed produces, or what happens when the same post arrives twice.

This page is the code version. You get a Python script that reads posts for a keyword from X, turns each one into an Airtable row, and upserts them in batches of 10 on a Tweet ID field so a re-run never creates duplicates; an Airtable automation script that does the same job from inside Airtable; and the curl calls for both halves so you can test each side in a minute. No X developer account is needed for the read side, and the Airtable side uses a personal access token scoped to one base.

Then the part the connector pages skip: we replayed one real keyword feed, posts mentioning Airtable itself, through the pipeline for 7 days and counted everything. 52.6 rows a day, 5.7 Airtable write requests a day, 335 duplicate deliveries absorbed by the upsert, and the number that should decide your plan: how many days until the base is full. We have no Airtable base attached to this study, so the Airtable writes were built and batched locally and not sent; every X number is from real API responses.

Rows a day from one keyword feed into Airtable

52.6 rows and 5.7 Airtable write requests a day over a 7-day week (collected in 2026); at that rate a Free base hits its 1,000-record limit in 19 days.

01 — Section

What a Twitter (X) to Airtable integration does, and three ways to build it

Every version of this integration has the same four steps: get new posts from X, decide which ones are new to the table, turn each into a set of field values, and write them to Airtable without breaking its rate limit. The connector platforms hide those steps behind a template; the script on this page makes each one explicit, which is what lets you control the cost, the schema and the duplicates.

Connector template (Zapier, Make, n8n)Python script on cron (this page)Airtable automation "Run a script"
Where it runsthe platformany server, laptop or CI jobinside Airtable
X accessusually your own X developer appan API key, no X accountan API key, stored as an automation secret
Duplicatesper templateupsert on Tweet ID, done by Airtableyour own id check (scripting has no upsert call)
Per-run limitstask or operation quotasAirtable's 5 requests/s per base50 fetch requests and 30 record queries per run
Good forno-code teams, low volumeany volume, custom fields, backfillssmall feeds, no server at all

Pick the script if you want backfills, more than one keyword, or a schema you control. Pick the automation if the feed is small (tens of posts an hour) and you do not want to run anything outside Airtable. Pick a connector if nobody on the team writes code; the sibling guides on Make and n8n cover those routes in detail.

Whichever you choose, the X side is one endpoint. /twitter/tweet/advanced_search takes the same query operators as X's own advanced search (lang:en, -filter:retweets, from:, min_faves:), plus since_time: and until_time: with Unix timestamps for an exact window, and returns a top-level tweets array with has_next_page and next_cursor for paging. Reads are billed per post returned: 15 credits per tweet, $0.15 per 1,000, with a 15-credit minimum when a request returns nothing.

02 — Section

Step 1: set up the base, the table and a scoped personal access token

Create a table called Tweets with one field per value you want to keep. The script on this page writes these: Tweet ID (single line text, the merge key), Text (long text), Author (single line text), Followers (number), Created (date with time, UTC), Likes, Reposts, Replies and Views (numbers), Is reply and Has media (checkboxes) and URL (URL). Store the id as text, not a number: post ids are 19 digits, which is beyond the integer precision a JavaScript number keeps, and Airtable's upsert requires the merge field to be a plain field (number, text, long text, single select, multiple select or date), never a formula, lookup or rollup.

The token. Airtable's Web API authenticates with personal access tokens (or OAuth for integrations used by other people). Create one at airtable.com/create/tokens, give it the data.records:write scope (add data.records:read if you also read rows back), and grant it access to this one base only. The token is shown once; put it in an environment variable, never in the script. Requests send it as Authorization: Bearer <token>.

The base and table ids. The base id starts with app and appears in the base's URL and in its API documentation page. The table can be addressed by name or by id (tbl...); Airtable's docs recommend the id because renaming a table then does not break the script. The examples use the name Tweets for readability.

Test the write side first. The curl request below is a complete upsert of one record. Run it twice: the first response lists the new record id in createdRecords, the second lists it in updatedRecords, and the table still has one row. That behavior is the whole reason the integration can re-read overlapping windows safely.

bash
# One upsert request: up to 10 records, matched on the "Tweet ID" field.
# 0 matches -> created, 1 match -> updated, more than 1 match -> the whole request fails.
curl -s -X PATCH "https://api.airtable.com/v0/$AIRTABLE_BASE_ID/Tweets" \
  -H "Authorization: Bearer $AIRTABLE_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "performUpsert": {"fieldsToMergeOn": ["Tweet ID"]},
    "typecast": true,
    "records": [
      {"fields": {"Tweet ID": "1234567890123456789", "Text": "example post", "Likes": 3}}
    ]
  }'
# Response: {"records": [...], "createdRecords": ["rec..."], "updatedRecords": []}
03 — Section

Step 2: read posts for a keyword window from the X API

The read side is a search for your keyword inside a time window. since_time: and until_time: take Unix timestamps in seconds, so a scheduled job can ask for exactly the interval since its last run. The response is newest first, 20 posts per page; keep requesting with cursor=<next_cursor> until has_next_page is false. A window that holds nothing returns an empty tweets array and is billed at the 15-credit minimum ($0.00015).

Which fields to keep. Each post object carries id, url, text, createdAt, lang, likeCount, retweetCount, replyCount, quoteCount, viewCount, bookmarkCount, isReply, entities (hashtags, urls, user_mentions), extendedEntities.media, quoted_tweet and an author object with userName, name, followers and more. The script maps twelve of these to fields; add lang or quoteCount the same way if your team filters on them.

Dates. createdAt comes as "Sun Nov 22 23:36:40 +0000 2026", not ISO 8601. Airtable date fields want ISO 8601, so the script converts with strptime("%a %b %d %H:%M:%S %z %Y") and writes UTC. Set the Created field's time zone display to your own; the stored value stays UTC.

Long posts. In our week 38.9% of the posts were longer than 280 characters, because long-form posts return their full text in text; the longest was 11,126 characters. Use a long text field for Text, not single line text.

The curl call below is the same request the scripts send. Replace the two timestamps with your window (they are the start and end of one UTC day in the example).

bash
# The read side: posts that match a keyword in a time window, 20 per page, newest first.
curl -s -G "https://api.twitterapi.io/twitter/tweet/advanced_search" \
  -H "X-API-Key: $TWITTERAPI_IO_API_KEY" \
  --data-urlencode "query=airtable lang:en -filter:retweets since_time:1764201600 until_time:1764288000" \
  --data-urlencode "queryType=Latest"
# -> {"tweets": [{"id": "...", "text": "...", "createdAt": "...", "likeCount": 0,
#                 "author": {"userName": "...", "followers": 0, ...}, ...}],
#     "has_next_page": true, "next_cursor": "..."}
# Next page: add --data-urlencode "cursor=<next_cursor>" and repeat until has_next_page is false.
04 — Section

Step 3: dedupe by tweet id and upsert in batches of 10

This is where hand-rolled integrations usually go wrong, and where Airtable's API does the heavy lifting. Three rules from the Airtable documentation shape the write loop.

Ten records per request. Airtable's support documentation on API limits states that batching handles up to 10 records per create, update or delete request. The script slices the mapped rows into lists of 10 and sends one PATCH per list, so a day with 87 posts is 9 requests, not 87.

Five requests per second per base. Airtable's rate-limit page: the API is limited to 5 requests per second per base, and a client over the limit gets a 429 and must wait 30 seconds before requests succeed again. A separate limit of 50 requests per second covers all traffic from one user's personal access tokens. The script sleeps a fixed 0.25 seconds between requests (4 a second) and, on a 429, waits the documented 30 seconds and retries. At the volumes in our study a whole day of writes takes under 2 seconds of request time.

Upsert, not create. With performUpsert: {"fieldsToMergeOn": ["Tweet ID"]} Airtable looks up each record by the merge field: no match creates a row, one match updates it, and more than one match fails the request. That last rule is why the Tweet ID column must stay unique; never paste rows into the table by hand. Use PATCH, which updates only the fields you send; PUT is a destructive update that clears the fields you leave out. The response adds createdRecords and updatedRecords so the script can log what happened.

Dedupe before you send, too. Two copies of the same post inside one batch would both match nothing and both try to create, so the script collapses the fetched posts to one per id first (keeping the later copy, which has the fresher like and view counts). After that, overlap between runs costs nothing extra: a post that was already stored simply comes back in updatedRecords with updated counts. That also makes the integration a cheap way to refresh engagement numbers for recent posts.

Typecast. typecast: true asks Airtable to convert string values into the right cell type on a best-effort basis. It is off by default; the script turns it on so a select field can gain new options and a URL string lands in a URL field without fuss.

05 — Section

Running it inside Airtable: an automation "Run a script" action

If you would rather not run anything outside Airtable, an automation can do the same job on a schedule. Airtable's scripting reference confirms that automation scripts can call external URLs with fetch (they do not run in the browser, so the CORS restrictions of the scripting extension do not apply there), with a 4.5 MB limit on each response.

The limits that shape the script (Airtable's "Run a script" support article): 50 fetch requests and 30 selectRecords queries per run, 512 MB of memory, up to 15 mutations a second with up to 50 records each, and a run timeout that the article currently lists as 120 seconds. The action is available on every plan type, with different limits, but not on Team plan trials. Every automation run also counts against the plan's monthly automation runs (100 on Free, 25,000 on Team, 100,000 on Business, per Airtable's plan documentation), so an hourly trigger is about 720 runs a month: too many for Free.

Secrets. Store the twitterapi.io key as an automation secret and read it with input.secret("TWITTERAPI_IO_API_KEY"); Airtable's scripting reference documents the call, and secrets are redacted from console output. Do not paste the key into the script body.

No upsert in scripting. The scripting API has createRecordsAsync and updateRecordsAsync (50 records per call) but no upsert, so the script reads the existing Tweet IDs once, skips posts it already has, and creates only the new ones. That full-table read is fine for a few thousand rows; past that, filter it to a view of recent rows or move to the Python version, where Airtable does the matching.

The script below assumes an hourly scheduled trigger and reads the last two hours, so every run overlaps the previous one by an hour. It has not been run inside an Airtable base for this page (we had none attached to the study); the fetch logic matches the Python script that was tested against real responses, and the JavaScript passes a syntax check.

javascript
// Airtable automation > "Run a script" action, on a scheduled trigger (for example every hour).
// Secrets: add TWITTERAPI_IO_API_KEY under the automation's secrets; input.secret() reads it.
// Limits per run (support.airtable.com): 50 fetch requests, 30 selectRecords queries,
// up to 50 records per createRecordsAsync call. Scripting has no upsert, so we dedupe ourselves.
const table = base.getTable("Tweets");
const key = input.secret("TWITTERAPI_IO_API_KEY");
const QUERY = "airtable lang:en -filter:retweets";
const since = Math.floor(Date.now() / 1000) - 2 * 3600;   // hourly trigger + 1 hour of overlap

// 1. Tweet IDs already in the table (fine for a few thousand rows; archive old rows past that)
const existing = await table.selectRecordsAsync({ fields: ["Tweet ID"] });
const seen = new Set(existing.records.map((r) => r.getCellValueAsString("Tweet ID")));

// 2. Page through the search with next_cursor; a cap of 40 pages keeps us under 50 fetches
const fresh = [];
let cursor = "";
for (let page = 0; page < 40; page++) {
  const q = encodeURIComponent(`${QUERY} since_time:${since}`);
  const url = `https://api.twitterapi.io/twitter/tweet/advanced_search?query=${q}&queryType=Latest`
    + (cursor ? `&cursor=${encodeURIComponent(cursor)}` : "");
  const res = await fetch(url, { headers: { "X-API-Key": key } });
  if (!res.ok) throw new Error(`twitterapi.io HTTP ${res.status}: ${await res.text()}`);
  const body = await res.json();
  for (const t of body.tweets || []) {
    const id = String(t.id);
    if (!seen.has(id)) { seen.add(id); fresh.push(t); }
  }
  if (!body.has_next_page || !body.next_cursor) break;
  cursor = body.next_cursor;
}

// 3. createRecordsAsync takes up to 50 records per call
const rows = fresh.map((t) => ({
  fields: {
    "Tweet ID": String(t.id),
    "Text": t.text || "",
    "Author": (t.author && t.author.userName) || "",
    "Created": new Date(t.createdAt).toISOString(),
    "Likes": t.likeCount || 0,
    "Views": t.viewCount || 0,
    "URL": t.url || t.twitterUrl || "",
  },
}));
for (let i = 0; i < rows.length; i += 50) {
  await table.createRecordsAsync(rows.slice(i, i + 50));
}
output.set("added", rows.length);
06 — Section

One keyword feed, one week: 52.6 rows a day

To size the integration with real data we replayed the feed airtable lang:en -filter:retweets (English posts that mention Airtable, reposts excluded) for 7 consecutive UTC days, collected in 2026. Each day was read twice, the way a careful pipeline would: pass A is the scheduled run, a since_time:/until_time: window that starts one hour before midnight (the overlap), and pass B is a catch-up re-read of the same day with the since:/until: date operators. Both passes go through the same id-based upsert. 56 requests in total returned 703 posts, $0.11 of API reads.

DayRows stored (unique posts)Only in pass A / only in pass BAirtable write requestsX data cost, both passes
Day 1446 / 15$0.0124
Day 25310 / 06$0.0147
Day 3598 / 06$0.0169
Day 4411 / 45$0.0120
Day 5380 / 04$0.0117
Day 6870 / 49$0.0258
Day 7463 / 15$0.0140
Week36828 / 1040$0.1076

Volume is small and lumpy. The feed produced 38 to 87 rows a day, 52.6 on average; the busiest day was more than twice the quietest. For a brand-sized keyword, Airtable's request limits are irrelevant: 5.7 write requests a day on average, 9 on the busiest day, under 2 seconds of writes at 5 requests a second.

Two reads of the same day did not return identical sets. Pass A alone found 97.3% of the week's unique posts and pass B alone 92.4%; 28 posts appeared only in pass A and 10 only in pass B. Search results for a window can differ slightly between queries and over time, so a single pass is not a guaranteed complete archive. The cheap fix is exactly what the upsert enables: re-read yesterday once, and let the tweet-id merge turn the 335 repeated deliveries into updates instead of duplicate rows. Without deduplication the week would have needed 74 write requests and left 335 duplicate rows.

What the rows look like. 38.9% of the posts were replies, 12.0% quotes, 33.4% carried a photo or video and 31.0% a link. 54.1% had no likes at all when collected, the median view count was 63.5, and 57.6% came from accounts with fewer than 1,000 followers. If the table feeds a sales or support queue, add -filter:replies or min_faves: to the query rather than filtering rows inside Airtable: you pay only for the posts returned, and you keep the record count down.

Stacked bar chart of unique posts stored per day for the keyword airtable over 7 days. Day 1: 44 rows, 5 writes. Day 2: 53 rows, 6 writes. Day 3: 59 rows, 6 writes. Day 4: 41 rows, 5 writes. Day 5: 38 rows, 4 writes. Day 6: 87 rows, 9 writes. Day 7: 46 rows, 5 writes. Blue segments are posts found by both passes, orange only by the since_time pass, purple only by the date re-read. Footnote: the since_time pass alone found 97.3% of the week's rows, the re-read alone 92.4%.
Rows per day for one keyword feed, split by which read found them, collected in 2026. 52.6 rows and 5.7 Airtable write requests a day on average.
07 — Section

Cost, API quotas and the record limit that actually binds

Three meters run when tweets flow into Airtable: the X data you read, the Airtable API calls you make, and the records you keep. Using the week above (52.6 rows a day, 30-day months):

MeterPrice or limit (source)This feed per monthVerdict
X data via twitterapi.io$0.15 per 1,000 posts returned, 15-credit minimum per empty requestabout $0.24 (one pass a day), $0.46 with the daily re-readnegligible
X data via the official X API$0.005 per post read (docs.x.com pay-per-usage rate card)about $7.89 for the same posts, one passabout 33x more per 1,000 posts ($5 vs $0.15)
Airtable Web API callsFree: 1,000 a month per workspace; Team: 100,000; Business: no monthly capabout 172 write calls (17.1% of Free, 0.2% of Team)fine on every plan
Airtable records per baseFree: 1,000; Team: 50,000; Business: 125,000about 1,578 new rowsFree is full in 19 days

The record limit is the real ceiling. At 52.6 rows a day a Free base fills in 19 days, a Team base (50,000 records) in about 951 days and a Business base (125,000) in about 2,378 days. A keyword ten times busier fills Team in about three months. Plan for it from the start: archive rows older than N days to CSV, keep one base per quarter, or write only posts that pass a min_faves: threshold.

What happens at the API limits. Per Airtable's API limits article, calls are counted per workspace per calendar month (UTC), metadata calls included. On Free, going over starts a one-time 30-day grace period, after which calls over the limit are blocked until the month resets; on Team, calls slow to 2 requests a second for the rest of the month. A daily batch job at this volume never gets close.

Airtable seat prices for context (Airtable's plan documentation): Team is $20 per collaborator a month billed annually or $24 monthly; Business $45 annually or $54 monthly; Enterprise Scale is priced by sales. On twitterapi.io, reads are pay-as-you-go: $1 buys 100,000 credits, purchased credits never expire, and new accounts that pass the automatic bot check get free starter credits (no card, one per person or network, expiring after 31 days); the current amount is on the pricing page.

Horizontal bar chart of days until one Airtable base reaches its record limit at 52.6 rows a day: Free plan with 1,000 records, 19 days; Team with 50,000 records, 951 days, about 2.6 years; Business with 125,000 records, 2,378 days, about 6.5 years.
Days until a base hits its plan's record limit at the measured rate. Limits from Airtable's plan documentation; rows a day from the keyword feed, collected in 2026.
08 — Section

Troubleshooting a Twitter to Airtable sync

422 INVALID_MULTIPLE_CHOICE_OPTIONS or a field type error. A value does not fit the field type, for example text sent to a number field or a new option for a single select. Turn on typecast: true or fix the field type; check that every field name in the script matches the table exactly, including capitals.

The upsert request fails with a multiple-match error. Two rows in the table share the same Tweet ID, usually from a manual paste or an earlier create-only script. Find the duplicates with a grouped view on Tweet ID, delete the extras, and keep the field unique from then on.

429 from Airtable. More than 5 requests a second hit the base, often because two jobs write to it at the same time. Wait 30 seconds as the docs require, then retry; the script's fixed pause and single writer keep it under the limit.

401 or 403 from Airtable. The token lacks data.records:write, was not granted this base, or the user who owns it is no longer a base editor.

HTTP 400 from twitterapi.io. A parameter is missing or invalid; the scripts print the response body, which names it. A malformed operator in the query is the usual cause; test the query in a single curl call first. HTTP 429 means the key went over its rate limit: 0.2 requests a second before the first payment, 20 once paid.

Rows look one day off. createdAt is UTC. The script writes UTC; the Created field displays in the time zone you set on the field, so a post from 23:30 UTC can show under the next day locally.

A post you saw on X is missing. Check the query: -filter:retweets drops reposts, lang:en drops untagged posts. Then let the next re-read catch it; in our week the second pass added 10 posts the first had not returned.

The automation fails on large tables. The full selectRecordsAsync read grows with the table; past a few thousand rows, read a filtered view or move to the Python script, where Airtable's upsert does the lookup server-side.

09 — Section

How we collected this

Question: if one keyword feed from X is piped into an Airtable base for a week, how many rows does it produce per day, how many duplicate deliveries does an id-based upsert absorb when reads overlap, how many Airtable write requests does that take (at 10 records per request), what does the X data cost, and how many days until each plan's record limit is reached.

Query: airtable lang:en -filter:retweets, queryType=Latest, through /twitter/tweet/advanced_search. Each of 7 consecutive UTC days was read twice: once with since_time:/until_time: starting one hour before midnight, once with since:/until: dates. Up to 14 pages per read were allowed; no read needed more than 6.

Sample: 56 requests, 703 posts returned, 368 unique posts, collected in 2026 through a rate-limited, read-only client. Airtable requests per day = ceil(new rows / 10). X cost = 15 credits per post returned, with the 15-credit minimum for the 14 empty final pages. Record-limit days = plan limit / mean rows per day. The Airtable writes were built, deduplicated and batched locally from the real responses (the Python script's mapping and batching ran on them in dry-run mode) but not sent: no Airtable base was attached to this study, so Airtable's responses and timings were not measured.

What the sample cannot show: one keyword for one week is a snapshot; a product launch or an outage would multiply the volume for a few days. The two-pass comparison shows that results for a window can differ between reads; it does not measure how complete either pass is against everything posted on X. Airtable limits are quoted from Airtable's documentation, not tested.

Aggregates only. The posts in this sample are mostly from private individuals, so no handles, texts or post ids are published, and the raw responses were not kept with the study; the de-identified rows, the analysis script and the results are.

python
"""tweets_to_airtable.py - save every new X (Twitter) post that matches a keyword search into an
Airtable table, one row per post, upserted on the post id so re-runs never create duplicates.

    pip install requests
    export TWITTERAPI_IO_API_KEY=...        # twitterapi.io dashboard (no X account needed for reads)
    export AIRTABLE_TOKEN=pat...            # personal access token: data.records:write, this base only
    export AIRTABLE_BASE_ID=app...  AIRTABLE_TABLE=Tweets
    python tweets_to_airtable.py            # one run; schedule it hourly or daily with cron
    DRY_RUN=1 python tweets_to_airtable.py  # fetch + map + batch, print the Airtable payloads, write nothing

Table fields (create them first): Tweet ID (single line text, the merge key), Text (long text),
Author (single line text), Followers (number), Created (date and time), Likes, Reposts, Replies,
Views (number), Is reply (checkbox), Has media (checkbox), URL (URL).
"""
import json
import os
import sys
import time
from datetime import datetime, timezone

import requests

X_API = "https://api.twitterapi.io"
X_KEY = os.environ.get("TWITTERAPI_IO_API_KEY", "")
AT_TOKEN = os.environ.get("AIRTABLE_TOKEN", "")
AT_BASE = os.environ.get("AIRTABLE_BASE_ID", "")
AT_TABLE = os.environ.get("AIRTABLE_TABLE", "Tweets")
QUERY = os.environ.get("X_QUERY", "airtable lang:en -filter:retweets")
STATE_FILE = "airtable-feed-state.json"
OVERLAP = 3600       # re-read the last hour of the previous window; the upsert absorbs the repeats
BATCH = 10           # Airtable Web API: up to 10 records per create/update request
PAUSE = 0.25         # fixed pause between Airtable requests: stays under 5 requests/s per base
MAX_PAGES = 50       # safety cap per run (one page = up to 20 posts)
DRY_RUN = bool(os.environ.get("DRY_RUN"))


def load_state():
    if os.path.exists(STATE_FILE):
        with open(STATE_FILE) as f:
            return json.load(f)
    return {"since_time": int(time.time()) - 86400}          # first run: the last 24 hours


def fetch_window(since_time, until_time):
    """All posts in [since_time, until_time), newest first, following next_cursor."""
    q = f"{QUERY} since_time:{since_time} until_time:{until_time}"
    tweets, cursor = [], None
    for _ in range(MAX_PAGES):
        params = {"query": q, "queryType": "Latest"}
        if cursor:
            params["cursor"] = cursor
        r = requests.get(f"{X_API}/twitter/tweet/advanced_search",
                         headers={"X-API-Key": X_KEY}, params=params, timeout=30)
        if not r.ok:                      # 400: missing/invalid parameter, 429: over your rate limit
            raise RuntimeError(f"twitterapi.io HTTP {r.status_code}: {r.text[:300]}")
        body = r.json()
        page = body.get("tweets") or []
        tweets.extend(page)
        if not page or not body.get("has_next_page") or not body.get("next_cursor"):
            break
        cursor = body["next_cursor"]
    return tweets


def iso(created_at):
    # createdAt looks like "Sun Nov 22 23:36:40 +0000 2026", not ISO 8601; Airtable wants ISO 8601
    return datetime.strptime(created_at, "%a %b %d %H:%M:%S %z %Y").astimezone(timezone.utc).isoformat()


def to_fields(t):
    a = t.get("author") or {}
    media = (t.get("extendedEntities") or {}).get("media") or []
    return {
        "Tweet ID": str(t["id"]),
        "Text": t.get("text") or "",
        "Author": a.get("userName") or "",
        "Followers": a.get("followers") or 0,
        "Created": iso(t["createdAt"]),
        "Likes": t.get("likeCount") or 0,
        "Reposts": t.get("retweetCount") or 0,
        "Replies": t.get("replyCount") or 0,
        "Views": t.get("viewCount") or 0,
        "Is reply": bool(t.get("isReply")),
        "Has media": bool(media),
        "URL": t.get("url") or t.get("twitterUrl") or "",
    }


def dedupe(tweets):
    """One row per post id; a later copy (fresher counts) replaces an earlier one."""
    by_id = {}
    for t in tweets:
        by_id[str(t["id"])] = t
    return list(by_id.values())


def batches(records, size=BATCH):
    for i in range(0, len(records), size):
        yield records[i:i + size]


def upsert(chunk):
    payload = {
        "performUpsert": {"fieldsToMergeOn": ["Tweet ID"]},
        "typecast": True,
        "records": [{"fields": f} for f in chunk],
    }
    if DRY_RUN:
        print(json.dumps(payload)[:300], "...")
        return 0, 0
    url = f"https://api.airtable.com/v0/{AT_BASE}/{requests.utils.quote(AT_TABLE)}"
    headers = {"Authorization": f"Bearer {AT_TOKEN}", "Content-Type": "application/json"}
    for _ in range(4):
        r = requests.patch(url, headers=headers, json=payload, timeout=30)
        if r.status_code == 429:          # over 5 requests/s on this base: Airtable asks for a 30 s wait
            time.sleep(30)
            continue
        r.raise_for_status()
        body = r.json()
        return len(body.get("createdRecords", [])), len(body.get("updatedRecords", []))
    raise RuntimeError("Airtable kept returning 429")


def run():
    state = load_state()
    until_time = int(time.time())
    tweets = dedupe(fetch_window(state["since_time"] - OVERLAP, until_time))
    rows = [to_fields(t) for t in tweets]
    created = updated = calls = 0
    for chunk in batches(rows):
        c, u = upsert(chunk)
        created, updated, calls = created + c, updated + u, calls + 1
        time.sleep(PAUSE)
    if not DRY_RUN:
        state["since_time"] = until_time
        with open(STATE_FILE, "w") as f:
            json.dump(state, f)
    print(f"{len(rows)} posts, {calls} Airtable requests, {created} created, {updated} updated",
          file=sys.stderr)


if __name__ == "__main__":
    run()

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

10 — Questions

Questions readers ask

Can Airtable pull tweets from X (Twitter) by itself?

Not natively. Airtable has no built-in X source, so you either use a connector platform, an Airtable automation with a "Run a script" action that calls an X data API with fetch, or an external script that writes through Airtable's Web API. The automation and the Python script are both on this page.

How do I avoid duplicate tweets in Airtable?

Store the post id in a text field and upsert on it: PATCH /v0/{baseId}/{table} with performUpsert and fieldsToMergeOn ["Tweet ID"]. A post that is already in the table is updated instead of created. Also collapse repeats inside one batch before sending, and keep the field unique, because an upsert that matches more than one row fails.

How many records can I send to Airtable in one request?

Up to 10 per create, update or delete request through the Web API, at up to 5 requests per second per base (a 429 means wait 30 seconds). Inside Airtable scripting, createRecordsAsync and updateRecordsAsync take up to 50 records per call.

Can an Airtable automation script call an external API?

Yes. Airtable's scripting reference says automation scripts can use fetch to reach external URLs, with a 4.5 MB response limit. The Run a script action allows 50 fetch requests and 30 selectRecords queries per run, and API keys can be stored as secrets and read with input.secret().

How many tweets a day does a keyword feed add to Airtable?

It depends on the keyword. For posts mentioning Airtable in English, without reposts, we measured 52.6 a day on average over a week (between 38 and 87), collected in 2026. That needs about 5.7 Airtable write requests a day.

Will the Airtable Free plan be enough?

For API calls yes, for records no: the measured feed used about 17.1% of Free's 1,000 monthly API calls but would fill the 1,000-record base limit in 19 days. Team (50,000 records per base) would last about 951 days at the same rate. Archive old rows or tighten the query if you stay on Free.

What does it cost to save tweets to Airtable?

On twitterapi.io the reads cost $0.15 per 1,000 posts returned, so the measured feed is about $0.24 a month for one pass a day. The official X API pay-per-usage rate card is $0.005 per post read, about $7.89 for the same posts. Airtable's own plan price is separate.

Do I need an X developer account?

No. Reads on twitterapi.io need only an API key sent in the X-API-Key header; there is no X app or OAuth setup. On the Airtable side you need a personal access token with data.records:write for the base.

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.