Twitter (X) API + Streamlit: Build a Live Hashtag Dashboard

By TwitterAPI.io Team•14 min read
Layout diagram of the Streamlit hashtag dashboard built on this page, drawn as a diagram rather than a screenshot. A sidebar holds st.text_input with the hashtag F1, st.slider for 24 hours, st.selectbox for a 300-second refresh and st.secrets with TWITTERAPI_KEY. The main area has four st.metric tiles with values from the #F1 sample: about 1,253 posts per 24 hours, 52.2 posts per hour, 55.5% with media and 63 pages to fill the window; an st.line_chart of posts per hour; an st.dataframe of top posts by likes; an st.bar_chart of top authors by post count; and an st.download_button labeled Download CSV. Footer: data from /twitter/tweet/advanced_search with query #tag and queryType Latest, study of 2,000 posts across 10 hashtags collected in 2026.
The app this page builds, as a layout diagram: every box is one Streamlit call. Metric values are from the #F1 sample in our study.
TL;DR
  • The app is one file: st.secrets for the key, /twitter/tweet/advanced_search with #tag and queryType=Latest, a pandas frame, four st.metric tiles, an hourly st.line_chart, a top-posts st.dataframe, a top-authors st.bar_chart and a CSV st.download_button.
  • Hashtag volume varies 73x: across 10 public tags we measured 5.3 posts an hour (#JavaScript) to 384.8 (#NFL); a rolling 24-hour view needs 7 to 462 pages of 20.
  • Fetch only what is new: with since_time: an always-on #F1 dashboard costs $5.64 a month at a 5-minute refresh; re-fetching the full window instead costs $1,623.46.
  • Share one store across viewers: st.cache_resource holds the rolling window once for every session, so 50 open tabs still make one fetch per refresh interval.
  • Expect a long tail: 66.8% of the 2,000 hashtag posts had zero likes and 54.6% carried media, so a top-posts table is a handful of rows above a flat floor.
  • Official X API comparison: $0.005 per post read on X's pay-per-usage rate card vs $0.15 per 1,000 tweets here, about 33x apart per 1,000 posts.

Streamlit turns a Python script into a web app: widgets in, charts and tables out, rerun on every interaction. That makes it a natural front end for X (Twitter) data. A hashtag dashboard is the classic first project: type a tag, see how many posts it gets per hour, which posts are taking off, which accounts post it repeatedly, and export the lot to CSV.

The Streamlit half is short. The part that tutorials skip is the data half: how many posts a tag really produces, how many API pages a 24-hour view needs, and what each refresh costs once the app stays open all day. We measured that on 2,000 posts from 10 public hashtags, then wrote the app so the expensive mistake (re-downloading the whole window on every refresh) cannot happen. Everything below runs as is on a laptop or on Streamlit Community Cloud.

Monthly cost of an always-on #NFL dashboard refreshed every 60 seconds

$41.56 fetching only new posts with since_time, vs $59,849 re-loading the 24-hour window each refresh (384.8 posts an hour, measured on 2,000 hashtag posts collected in 2026).

01 — Section

What you are building, plus Step 1: project files and secrets

The finished app has a sidebar (hashtag, hours to show, refresh interval) and a main area with four st.metric tiles, a posts-per-hour st.line_chart, a top-posts st.dataframe with clickable links, a top-authors st.bar_chart, and a st.download_button that exports the visible posts as CSV. It is one file, app.py, plus requirements.txt and a secrets file.

Python and Streamlit. The current Streamlit release on PyPI is 1.67.0 and it requires Python 3.11 or newer (pypi.org/project/streamlit). Every call used here (st.cache_data, st.cache_resource, st.fragment, st.secrets, st.metric, st.line_chart, st.dataframe, st.download_button) is documented on docs.streamlit.io for that version.

An API key, no X account. Reads go to https://api.twitterapi.io with an X-API-Key header. You do not need an X developer account, an approved project or OAuth. New accounts that pass the automatic bot check get free starter credits (no card, one per person or network, expiring after 31 days); see the pricing page for the amount. Purchased credits never expire.

One endpoint. /twitter/tweet/advanced_search takes query (X search operators such as from:, -filter:replies and since_time:, up to 512 characters), queryType (Latest or Top) and cursor (empty for the first page). It returns top-level tweets[], has_next_page and next_cursor, up to 20 posts per page (docs.twitterapi.io). Every one of our 100 study pages came back with exactly 20.

Streamlit's own sample gallery has a tweet analyzer (github.com/streamlit/example-app-twitter-analyzer) that expects a consumer key and secret from the X Developer Portal in .streamlit/secrets.toml, and its README warns it relies on early Streamlit features. The app here uses only stable APIs and a single key.

Create a folder with app.py, requirements.txt and .streamlit/secrets.toml. Streamlit reads secrets from .streamlit/secrets.toml in the folder you launch from (or next to the entry file, or a global ~/.streamlit/secrets.toml), exposes them as st.secrets["KEY"], and also exposes root-level secrets as environment variables. Add the file to .gitignore: the docs are explicit that it should never be committed.

On Streamlit Community Cloud you paste the same TOML into the Secrets field under Advanced settings when you deploy, or later through the app's settings in your workspace (docs.streamlit.io/deploy/streamlit-community-cloud/deploy-your-app/secrets-management). The code does not change between local and cloud.

One caution for public apps. Anyone who can open the app can type a hashtag, and each new tag triggers a first load. The app caps that first load at 10 pages (200 posts), validates the input, and has an ALLOWED_TAGS set you can fill in to restrict a public deployment to the tags you chose.

toml
# .streamlit/secrets.toml  (add .streamlit/secrets.toml to .gitignore)
TWITTERAPI_KEY = "paste-your-key-here"

# requirements.txt (Streamlit Community Cloud installs these)
streamlit
pandas
requests
02 — Section

Step 2: fetch hashtag posts with cursor paging

The fetch function is a generator. It sends query="#F1" with queryType=Latest, yields each post in tweets[], and follows next_cursor while has_next_page is true, up to a page cap you pass in. On HTTP 429 (rate limit) or 503 it waits and retries a few times; per the endpoint reference, a 503 is not charged.

Rate limits. Before your first payment the API allows 0.2 requests per second, so set PAUSE_S = 5.0 and a 10-page first load takes about 50 seconds. After a payment the limit is 20 requests per second (50 on Scale, 500 on Business, up to 1,000 on request), which no single dashboard approaches.

Field names. Each post carries id, url, text, createdAt (a string like Thu Oct 16 12:34:56 +0000 2026, parsed with %a %b %d %H:%M:%S %z %Y), likeCount, retweetCount, replyCount, viewCount, isReply, extendedEntities.media[] and an author object with userName and followers. to_row() flattens just those into a dict, so the DataFrame stays small: the full post object weighed a median of 5,615 bytes in our sample (12,360 at the 90th percentile), and the app keeps none of the bulk.

Before wiring up the UI, measure your tag. One page of 20 is enough to estimate posts per hour, and therefore how many pages a 24-hour window needs. The probe below does exactly that for the cost of the 20 tweets it returns.

python
# probe.py - how busy is a hashtag? One 20-post page answers it.
import requests
from datetime import datetime

BASE = "https://api.twitterapi.io"
KEY = "your-api-key"
TS_FMT = "%a %b %d %H:%M:%S %z %Y"

r = requests.get(
    f"{BASE}/twitter/tweet/advanced_search",
    headers={"X-API-Key": KEY},
    params={"query": "#F1", "queryType": "Latest", "cursor": ""},
    timeout=30,
)
r.raise_for_status()
body = r.json()
tweets = body.get("tweets", [])
if len(tweets) >= 2:
    times = [datetime.strptime(t["createdAt"], TS_FMT) for t in tweets]
    hours = (max(times) - min(times)).total_seconds() / 3600 or 1 / 60
    rate = len(tweets) / hours
    print(f"{rate:,.1f} posts/hour -> {rate * 24 / 20:,.0f} pages for 24 h "
          f"-> ${rate * 24 * 0.00015:,.2f} to fill the window once")
print("has_next_page:", body.get("has_next_page"))
03 — Section

Step 3: refresh without paying twice (since_time, cache_resource, fragment)

Streamlit reruns the whole script on every widget change. Without caching, every slider move would call the API. There are two documented tools, and the app uses both on purpose.

st.cache_resource for the shared store. It returns one object shared across all users, sessions and reruns, not copied, so it can be mutated; the docs require it to be thread-safe, which is why the store carries a threading.Lock. The store holds, per tag, the rows of the last 24 hours, the newest timestamp seen, the time of the last fetch and a running count of billed tweets. Fifty open tabs still produce one fetch per refresh interval.

Incremental fetch with since_time:. The first load of a tag asks for #F1; every later refresh asks for #F1 since_time:<newest unix seconds>, so it only receives posts you do not have. Rows are keyed by tweet id, which removes any overlap at the boundary. The endpoint reference lists since_time and until_time in Unix seconds and notes that date-style since:YYYY-MM-DD is not supported.

st.fragment(run_every=ttl) for the timer. A fragment reruns only its own function on an interval while the session is open, leaving the sidebar alone (docs.streamlit.io/develop/api-reference/execution-flow/st.fragment). The alternative is to cache the search result itself with st.cache_data(ttl=300): simpler, but st.cache_data stores a pickled copy per argument set and returns a new copy each call, and a cache that expires re-runs the whole fetch, which is the expensive pattern measured in the cost section below.

python
# First load of a tag: up to BACKFILL_PAGES pages (20 posts each), newest first.
query = "#F1"
# Every later refresh: only posts at or after the newest one already stored.
query = f"#F1 since_time:{newest_unix_seconds}"
# The overlap at the boundary is removed by keying rows on the tweet id.
rows[tweet["id"]] = to_row(tweet)

@st.fragment(run_every=ttl)          # reruns only this function every `ttl` seconds
def live():
    e = refresh(tag, ttl)               # no API call unless the shared store is older than ttl
    df = pd.DataFrame(list(e["rows"].values()))
    ...

# Alternative without a timer: cache the search result itself for ttl seconds.
@st.cache_data(ttl=300, show_spinner="Fetching posts...")
def latest_posts(tag: str) -> list:
    return [to_row(t) for t in search(f"#{tag}", BACKFILL_PAGES)]
04 — Section

Step 4: metrics, hourly chart, top posts, top authors, CSV

Inside the fragment the rows become a DataFrame filtered to the hours selected in the sidebar. The four tiles are st.metric calls: posts in view, posts per hour, the share with media, and the share with zero likes. st.metric also accepts chart_data for a sparkline and border=True if you want framed tiles.

Posts per hour. df.set_index("created_at").resample("1h").size() gives a Series indexed by UTC hour that st.line_chart plots directly. The use_container_width argument on charts is deprecated in current releases in favor of width="stretch", which is already the default, so the app passes neither.

Top posts. df.nlargest(10, "likes") feeds st.dataframe with hide_index=True and column_config={"url": st.column_config.LinkColumn("post", display_text="open")}, so each row links to the post on X.

Top authors. df["author"].value_counts().head(10) into st.bar_chart. On a public tag this chart can be dominated by a few accounts that post the tag repeatedly: in our sample, authors who appeared more than once accounted for 54.0% of #JavaScript posts and 55.0% of #MachineLearning posts. If you show it publicly, consider listing only organization accounts or showing counts without names.

CSV. st.download_button(..., on_click="ignore") exports the filtered frame; the ignore option downloads the file without rerunning the app, which matters inside a timer-driven fragment.

05 — Section

How busy is a hashtag? 2,000 posts from 10 tags

We searched 10 public hashtags with queryType=Latest and read 200 of the latest posts for each (10 pages of 20). The time between the newest and oldest post gives the rate. #NFL and #AI filled 200 posts in about half an hour; #Python, #NASA and #MachineLearning took 15 to 17 hours, and #JavaScript about a day and a half.

HashtagPosts per hourPages for 24 hCost to fill 24 h (ours)X API, same posts
#NFL384.8462$1.39$46.18
#AI354.2425$1.27$42.50
#NBA193.5233$0.70$23.23
#Bitcoin159.5192$0.57$19.14
#F152.263$0.19$6.26
#NASA13.216$0.05$1.58
#Python1316$0.05$1.55
#MachineLearning11.514$0.04$1.38
#ClimateChange7.710$0.03$0.93
#JavaScript5.37$0.02$0.64

The spread is 73x. For #JavaScript, a full 24-hour window is 7 pages and $0.02; for #NFL it is 462 pages and $1.39. The page count matters as much as the cost: before your first payment (0.2 requests per second), 462 pages take over half an hour, which is why the app's first load stops at 10 pages and shows where the window starts.

The last column applies X's pay-per-usage price of $0.005 per post read to the same posts. X's rate card also states that a resource already charged in the same UTC day is not charged again (described as a soft guarantee), so on X a repeated read within the day is free while here every tweet returned is billed. That is one more reason to fetch incrementally on either API.

Horizontal bar chart on a log scale of posts per hour matching each of 10 hashtags in Latest search, 200 posts per tag. #NFL 384.8 per hour, 462 pages and $1.39 to fill 24 hours, #AI 354.2 per hour, 425 pages and $1.27 to fill 24 hours, #NBA 193.5 per hour, 233 pages and $0.70 to fill 24 hours, #Bitcoin 159.5 per hour, 192 pages and $0.57 to fill 24 hours, #F1 52.2 per hour, 63 pages and $0.19 to fill 24 hours, #NASA 13.2 per hour, 16 pages and $0.05 to fill 24 hours, #Python 13 per hour, 16 pages and $0.05 to fill 24 hours, #MachineLearning 11.5 per hour, 14 pages and $0.04 to fill 24 hours, #ClimateChange 7.7 per hour, 10 pages and $0.03 to fill 24 hours, #JavaScript 5.3 per hour, 7 pages and $0.02 to fill 24 hours.
Posts per hour per hashtag, with the 20-post pages and cost needed to fill a rolling 24-hour window at $0.15 per 1,000 tweets. 2,000 posts, collected in 2026.
06 — Section

What each refresh costs: cache TTL vs bill

Every refresh is one search. What it costs depends on how many new posts arrived since the last one, and on one billing floor: each request costs at least 15 credits ($0.00015), which is what a check that finds nothing costs. Polling every 60 seconds for a month is 43,200 checks, so a quiet tag refreshed every minute costs $6.48 a month even if it returns almost nothing; every 5 minutes, that floor is $1.30.

For #F1 (52.2 posts an hour in our sample), an always-on dashboard costs:

Refresh (TTL)Requests per refreshCost per refresh30 days, incremental30 days, full re-fetch
60 s1$0.00015$6.48$8,117.28
5 min1$0.00065$5.64$1,623.46
15 min1$0.00196$5.64$541.15
1 hour3$0.00783$5.64$135.29

Incremental cost hardly moves with the TTL, because you pay per post and the posts are the same; only the 60-second row rises to the per-request floor. Full re-fetch is the trap: re-loading 63 pages every 5 minutes is $1,623.46 a month for the same dashboard. For #NFL at a 60-second refresh the gap is $59,849 vs $41.56.

Pick the TTL for the reader, not the bill. With incremental fetches, 5 minutes and 1 hour cost nearly the same, so choose the freshness the dashboard needs. A plain st.cache_data(ttl=...) on the full search only refreshes when someone visits after expiry, so a low-traffic app costs less than these always-on figures; a run_every fragment with an open tab is the always-on case.

Compared with the official X API. For the same unique posts over a month, using X's pay-per-usage rate card ($0.005 per post read, capped at 3 million post reads a month before Enterprise):

Monthly volumeTwitterAPI.io ($0.15 per 1,000 tweets)Official X API ($0.005 per post read)
#NFL: 277,071 posts$41.56$1,385.36
#F1: 37,590 posts$5.64$187.95
#Python: 9,330 posts$1.40$46.65

Subscriptions are available too (Starter $29, Builder $99, Pro $199, Scale $499, Business $1,499 a month); the pricing page has the details.

Line chart on a log scale of USD per 30 days for an always-on dashboard at refresh intervals of 60 seconds, 5 minutes, 15 minutes and 1 hour. Dashed lines show full re-fetch of the 24-hour window: #NFL falls from $59,849 to $997, #F1 from $8,117 to $135, #Python from $2,013 to $34. Solid lines show incremental fetches with since_time: #NFL flat at $41.56, #F1 $6.48 at 60 seconds then $5.64, #Python $6.48 at 60 seconds then $1.40.
Monthly cost of an always-on hashtag dashboard by refresh interval: incremental (solid) vs full re-fetch (dashed). From the study's measured posts-per-hour, collected in 2026.
07 — Section

What hashtag posts look like in a dashboard

Beyond volume, the sample shows what the tiles and tables will actually display. Shares are of the 200 posts per tag:

HashtagRepliesQuotesWith mediaZero likes
#NFL3.5%9.0%55.5%73.5%
#AI7.0%10.0%45.5%76.5%
#NBA6.5%11.0%64.0%74.0%
#Bitcoin4.5%10.5%50.5%64.5%
#F19.5%11.0%55.5%60.0%
#NASA6.0%7.0%56.5%74.5%
#Python5.0%4.5%51.0%62.0%
#MachineLearning5.0%0.5%49.5%67.0%
#ClimateChange8.0%13.0%54.5%68.0%
#JavaScript5.5%2.0%63.5%47.5%

Native reposts did not appear. None of the 2,000 Latest results was a native repost, so a hashtag dashboard counts original posts, replies and quotes; reposts of those posts show up only as retweetCount on the original. Replies were 6.0% and quotes 7.8% overall.

Engagement is a long tail. 66.8% of posts had zero likes, and the median like count was 0 for 9 of the 10 tags. A top-posts table is a few rows that matter above a flat floor, so sort by likes or views and cap at 10 rather than paginating through everything.

Media and links are common. 54.6% of posts carried photos or video and 41.1% carried links. If you add thumbnails, put extendedEntities.media[].media_url_https in a column configured with st.column_config.ImageColumn, which renders inline thumbnails from URLs, instead of downloading images yourself.

Language is mixed. English was the top language for every tag, from 49.0% of #F1 posts to 90.0% of #NFL posts. Add lang:en to the query if the dashboard is for one audience; it also lowers the bill because fewer posts come back.

08 — Section

Deploy, extend and troubleshoot

Deploy. Push app.py and requirements.txt to a GitHub repository (not the secrets file), create the app on Streamlit Community Cloud, paste the TOML into Secrets under Advanced settings, and deploy. The shared store lives in the app process, so it resets when the app restarts or sleeps; the first visitor after that triggers a fresh 10-page load.

Track several tags. Use a st.multiselect and loop refresh() over the selection, or combine tags in one query with OR (#F1 OR #Formula1), which costs one stream of posts instead of two overlapping ones.

Keep history beyond 24 hours. Append each refresh to SQLite or a Parquet file instead of trimming, and read the frame back in the fragment. For a fixed list of accounts rather than a hashtag, a filter rule that pushes matches to a webhook avoids polling entirely.

Empty chart. Check the hashtag spelling and remember that since_time takes Unix seconds, not a date. A tag with no recent posts returns an empty tweets[] and costs the 15-credit minimum.

HTTP 429. You are above your rate limit: 0.2 requests per second before the first payment. Raise PAUSE_S, lower BACKFILL_PAGES, or add credits.

KeyError or FileNotFoundError on st.secrets. Streamlit raises FileNotFoundError when no secrets file exists and KeyError when the key is missing; check the file path relative to where you ran streamlit run, or the Secrets field on Community Cloud.

Numbers jump after a restart. The billed counter and the store are in memory. That is expected; persist them if you need an audit trail.

09 — Section

How we collected this

Question. How many posts does a public hashtag produce per hour, how many 20-post search pages does a rolling 24-hour dashboard need, and what does each refresh cost at different cache TTLs, fetching incrementally or re-fetching the whole window?

Query. /twitter/tweet/advanced_search with query=#<tag> and queryType=Latest for 10 hashtags: #AI, #Python, #NASA, #F1, #NFL, #JavaScript, #Bitcoin, #MachineLearning, #NBA and #ClimateChange.

Window and sample. The latest 200 posts per tag (10 pages each) at collection time, collected in 2026: 2,000 posts from 100 requests, about $0.30 in API cost. Each tag's window runs from its oldest to its newest sampled post, from about half an hour (#NFL, #AI) to about a day and a half (#JavaScript).

Method. Rate = posts divided by the sample's time span. Pages for 24 hours = rate x 24 / 20, rounded up. Incremental refresh cost = new posts per interval x $0.00015, with the $0.00015 per-request minimum; full re-fetch = a whole 24-hour window per refresh; 30 days of refreshes. Payload size = the UTF-8 JSON length of each post object as returned.

What the sample cannot show. One snapshot per tag: rates swing with game days, launches and news, so a tag can be several times busier or quieter on another day. Latest-mode search results are what the dashboard sees, not every post that exists on X. Costs exclude subscriptions and assume the page's price of $0.15 per 1,000 tweets.

Privacy. Hashtag searches return posts by private individuals, so raw pages were kept outside the repository and never published. The page reports aggregates only and names no individual author; the de-identified sample (tag, hour, type flags, counts, payload bytes) has no ids, text, links or handles.

python
"""app.py - a live hashtag dashboard for X (Twitter) posts, built with Streamlit.

    pip install streamlit pandas requests
    # .streamlit/secrets.toml  ->  TWITTERAPI_KEY = "your key from twitterapi.io/dashboard"
    streamlit run app.py

Data: GET https://api.twitterapi.io/twitter/tweet/advanced_search (query "#tag", queryType=Latest),
20 posts per page, paged with next_cursor. Billing: $0.15 per 1,000 tweets returned.
"""
import re
import threading
import time
from datetime import datetime, timezone

import pandas as pd
import requests
import streamlit as st

BASE = "https://api.twitterapi.io"
API_KEY = st.secrets["TWITTERAPI_KEY"]
WINDOW_H = 24            # the shared store keeps a rolling 24-hour window per tag
BACKFILL_PAGES = 10      # first load of a tag: up to 200 posts, so a busy tag cannot run up a bill
CATCHUP_PAGES = 50       # later refreshes: only posts newer than the newest one already stored
PAUSE_S = 0.0            # set to 5.0 before your first payment (0.2 requests per second)
ALLOWED_TAGS = None      # e.g. {"F1", "NASA", "Python"} on a public deployment
TS_FMT = "%a %b %d %H:%M:%S %z %Y"   # createdAt, e.g. "Thu Oct 16 12:34:56 +0000 2026"

st.set_page_config(page_title="Hashtag dashboard", layout="wide")


def search(query, max_pages):
    """Yield posts for an advanced_search query, newest first, following next_cursor."""
    cursor, pages, retries = "", 0, 0
    while pages < max_pages:
        r = requests.get(
            f"{BASE}/twitter/tweet/advanced_search",
            headers={"X-API-Key": API_KEY},
            params={"query": query, "queryType": "Latest", "cursor": cursor},
            timeout=30,
        )
        if r.status_code in (429, 503) and retries < 3:
            retries += 1
            time.sleep(5 * retries)
            continue
        r.raise_for_status()
        body = r.json()
        pages += 1
        yield from body.get("tweets", [])
        if not body.get("has_next_page") or not body.get("next_cursor"):
            break
        cursor = body["next_cursor"]
        time.sleep(PAUSE_S)


def to_row(t):
    a = t.get("author") or {}
    return {
        "id": t["id"],
        "created_at": datetime.strptime(t["createdAt"], TS_FMT),
        "author": a.get("userName"),
        "followers": a.get("followers", 0),
        "text": t.get("text", ""),
        "likes": t.get("likeCount", 0),
        "reposts": t.get("retweetCount", 0),
        "replies": t.get("replyCount", 0),
        "views": t.get("viewCount", 0),
        "is_reply": bool(t.get("isReply")),
        "has_media": bool((t.get("extendedEntities") or {}).get("media")),
        "url": t.get("url"),
    }


@st.cache_resource
def store():
    """One store for every viewer: a refresh made for one session serves all of them."""
    return {"lock": threading.Lock(), "tags": {}}


def refresh(tag, ttl):
    s = store()
    with s["lock"]:
        e = s["tags"].setdefault(tag, {"rows": {}, "newest": 0, "last": 0.0, "billed": 0})
        now = time.time()
        if now - e["last"] < ttl:
            return e                                   # fresh enough: no API call
        if e["newest"]:
            query, pages = f"#{tag} since_time:{e['newest']}", CATCHUP_PAGES
        else:
            query, pages = f"#{tag}", BACKFILL_PAGES
        for t in search(query, pages):
            row = to_row(t)
            e["billed"] += 1                           # every tweet returned is billed
            e["rows"][row["id"]] = row                 # dedupe the since_time overlap by id
            e["newest"] = max(e["newest"], int(row["created_at"].timestamp()))
        cutoff = now - WINDOW_H * 3600
        e["rows"] = {k: v for k, v in e["rows"].items() if v["created_at"].timestamp() >= cutoff}
        e["last"] = now
        return e


# ---------------------------------------------------------------- sidebar
st.sidebar.title("Hashtag dashboard")
raw = st.sidebar.text_input("Hashtag", value="F1").strip().lstrip("#")
hours = st.sidebar.slider("Hours to show", 1, WINDOW_H, WINDOW_H)
ttl = st.sidebar.selectbox("Refresh every (seconds)", [60, 300, 900, 3600], index=1)

if not re.fullmatch(r"\w{1,50}", raw) or (ALLOWED_TAGS and raw not in ALLOWED_TAGS):
    st.error("Enter one hashtag: letters, digits or underscores.")
    st.stop()
tag = raw


@st.fragment(run_every=ttl)
def live():
    e = refresh(tag, ttl)
    df = pd.DataFrame(list(e["rows"].values()))
    st.caption(f"#{tag}: last fetch {datetime.fromtimestamp(e['last'], timezone.utc):%H:%M:%S} UTC, "
               f"{e['billed']:,} tweets billed so far (about ${e['billed'] * 0.00015:.2f})")
    if df.empty:
        st.info("No posts with this hashtag in the window yet.")
        return
    since = pd.Timestamp.now(tz="UTC") - pd.Timedelta(hours=hours)
    df = df[df["created_at"] >= since].sort_values("created_at", ascending=False)
    if df.empty:
        st.info("No posts in the selected hours.")
        return
    span_h = max((df["created_at"].max() - df["created_at"].min()).total_seconds() / 3600, 1 / 60)

    c1, c2, c3, c4 = st.columns(4)
    c1.metric("Posts in view", f"{len(df):,}")
    c2.metric("Posts per hour", f"{len(df) / span_h:,.1f}")
    c3.metric("With media", f"{df['has_media'].mean():.0%}")
    c4.metric("Zero likes", f"{(df['likes'] == 0).mean():.0%}")
    if df["created_at"].min() > since + pd.Timedelta(minutes=5):
        st.caption(f"Window starts {df['created_at'].min():%H:%M} UTC: the first load stops at "
                   f"{BACKFILL_PAGES * 20} posts; later refreshes fill forward.")

    per_hour = df.set_index("created_at").resample("1h").size().rename("posts")
    st.subheader("Posts per hour (UTC)")
    st.line_chart(per_hour)

    left, right = st.columns([3, 2])
    with left:
        st.subheader("Top posts by likes")
        top = df.nlargest(10, "likes")[["created_at", "author", "likes", "reposts", "views", "text", "url"]]
        st.dataframe(top, hide_index=True,
                     column_config={"url": st.column_config.LinkColumn("post", display_text="open")})
    with right:
        st.subheader("Top authors by posts")
        st.bar_chart(df["author"].value_counts().head(10))

    st.download_button("Download CSV", df.to_csv(index=False).encode("utf-8"),
                       file_name=f"{tag}-{hours}h.csv", mime="text/csv", on_click="ignore")


live()

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

10 — Questions

Questions readers ask

Can I use the Twitter (X) API with Streamlit?

Yes. Streamlit is plain Python, so any HTTP API works. Keep the key in st.secrets, call the API with requests, cache with st.cache_data or st.cache_resource, and render with st.metric, st.line_chart and st.dataframe. With twitterapi.io you send one X-API-Key header and need no X developer account.

How do I store my API key in Streamlit Community Cloud?

Locally, put it in .streamlit/secrets.toml (and in .gitignore) and read it with st.secrets["TWITTERAPI_KEY"]. On Community Cloud, paste the same TOML into the Secrets field under Advanced settings when deploying, or edit it later in the app's settings. The code is identical in both places.

How do I auto-refresh a Streamlit dashboard?

Wrap the live part in @st.fragment(run_every=300): Streamlit reruns just that function every 300 seconds while the session is open. Alternatively cache the data with st.cache_data(ttl=300) so it refreshes on the next interaction after expiry. Either way, fetch only posts newer than the newest you hold (since_time:).

How much does a Streamlit Twitter dashboard cost to run?

It depends on the tag's volume and on fetching incrementally. In our study an always-on #F1 dashboard (about 52.2 posts an hour) costs $5.64 a month at a 5-minute refresh when it fetches only new posts, and $1,623.46 if it re-loads the 24-hour window each time. Reads are $0.15 per 1,000 tweets returned, with a $0.00015 minimum for a check that finds nothing.

Why does my hashtag dashboard only show the last half hour?

Busy tags fill a page of 20 in seconds. #NFL ran at 384.8 posts an hour in our sample, so 200 posts cover about half an hour and a full day needs 462 pages. The app caps the first load at 10 pages to bound cost and then fills forward; raise BACKFILL_PAGES if you need the whole day at once.

Does the search return retweets?

In our 2,000-post Latest sample, none of the results was a native repost; replies and quotes did appear. Reposts are reflected as retweetCount on the original post. Add -filter:replies to the query to drop replies as well.

Can I use the official X API instead?

Yes: X's recent search (GET /2/tweets/search/recent, last seven days, 10 to 100 results per page, next_token paging) works with the same Streamlit code once you swap the request and field names. It needs a developer account and bills $0.005 per post read on the pay-per-usage rate card, compared with $0.15 per 1,000 tweets here.

Can the dashboard post replies or likes back to X?

Reads need no X account. Write actions such as posting or liking run through an authenticated session: one /twitter/user_login_v2 login ($0.10, with a proxy you supply) returns login_cookies, then each action like /twitter/create_tweet_v2 is 60 credits ($0.0006), billed per HTTP 200 call. The call acts as that account, so X can rate-limit, lock or suspend it; keep a human pace and expect occasional re-login. For a read-only dashboard you need none of this.

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.