How to find and rank X posts with Python and TwitterAPI.io
Disclosure: This post is part of TwitterAPI.io's Community Rewards program. If approved, I will receive API credits. The link below is a referral link, so I may also earn a commission if you sign up and pay through it.
Disclosure: This post is part of TwitterAPI.io's Community Rewards program. If approved, I will receive API credits. The link below is a referral link, so I may also earn a commission if you sign up and pay through it.
Finding a post about a topic is easy. Finding the posts that actually got attention is a little more interesting.
Suppose you want to look at what people are saying about AI coding agents. You could search on X, scroll for a while, and open anything that looks relevant. That works for a quick look, but it gets old if you want to compare results or repeat the search later.
A more useful approach is to collect a set of posts with an API, keep their engagement counts, and sort the results yourself. This tutorial uses Python and TwitterAPI.io to do exactly that.
There is an important distinction here: the script ranks the posts it receives, not every post that exists. Search results can be incomplete, and collecting the latest results is not the same thing as collecting the most-liked posts of all time. More on that later.
What you need
You need Python 3, the requests library, and a TwitterAPI.io API key. Create an account using the link above, then copy your API key from the dashboard. New accounts may receive free credits, subject to the provider's signup checks.
Install the library:
python -m pip install requests
Set your API key as an environment variable in your terminal:
export TWITTERAPI_IO_KEY='your-api-key'
Replace the value with your actual key. Don't put the key in your script, share screenshots containing it, or commit it to a repository. Environment variables aren't perfect secret storage, but they keep the key out of the example file.
Start with a useful query
TwitterAPI.io has an advanced search endpoint that accepts search operators. Here is an example:
("AI agents" OR "coding agents") min_faves:100 lang:en -filter:replies
This looks for either phrase, requires at least 100 likes, limits results to English, and excludes replies. You can change the phrases and thresholds to fit your own research.
Other useful operators include from:username to search posts from an account, min_retweets:50 to set a minimum repost count, and since:2026-01-01 until:2026-02-01 to select a date range. The end date is exclusive, so this example covers January but not February 1.
One detail worth knowing: a keyword can match more than the visible post text, including an author's name or expanded links. If you need an exact text match, check the returned text before counting it as relevant.
Fetch the posts
Save this as search_posts.py:
import os
import requests
API_URL = "https://api.twitterapi.io/twitter/tweet/advanced_search"
API_KEY = os.environ["TWITTERAPI_IO_KEY"]
QUERY = '("AI agents" OR "coding agents") min_faves:100 lang:en -filter:replies'
MAX_PAGES = 3
def search_posts():
posts_by_id = {}
cursor = ""
for _ in range(MAX_PAGES):
response = requests.get(
API_URL,
headers={"X-API-Key": API_KEY},
params={"query": QUERY, "queryType": "Latest", "cursor": cursor},
timeout=30,
)
response.raise_for_status()
page = response.json()
for post in page.get("tweets") or []:
posts_by_id[post["id"]] = post
if not page.get("has_next_page") or not page.get("next_cursor"):
break
cursor = page["next_cursor"]
return sorted(
posts_by_id.values(),
key=lambda post: post.get("likeCount") or 0,
reverse=True,
)
if __name__ == "__main__":
posts = search_posts()
print(f"Collected {len(posts)} unique posts.\n")
for post in posts:
author = post.get("author") or {}
print(f"@{author.get('userName', 'unknown')}")
print(f"Likes: {post.get('likeCount', 0)}")
print(post.get("text", ""))
print(post.get("url", ""))
print("-" * 60)
Run it:
python search_posts.py
The script makes up to three requests. It follows the cursor returned by the API, stores posts by ID to avoid showing duplicates, and sorts the collected posts by their like count. Each result prints the author, likes, text, and link.
The endpoint returns up to 20 posts per page, so this example collects at most around 60 posts before deduplication. You can raise MAX_PAGES if you need a larger sample, but doing so can use more credits. Start small and check that the query returns what you actually want.
Latest vs Top
The example uses queryType: Latest. That means the API returns a recent set of matching posts, then the script ranks that set by likes.
You can change Latest to Top to request X's ranked selection instead. That can be useful for finding prominent posts quickly, but Top is not necessarily a strict sort by likes. It can also return a different and more selective set of results.
Neither option guarantees a complete ranking of all posts on the topic. If you need a more useful sample, narrow the date range and try a few searches with different minimum-like thresholds. Save the query and collection date alongside your results. Otherwise, it's hard to tell later what the ranking actually represents.
Cost and next steps
At the published pay-as-you-go rate, advanced search costs $0.15 per 1,000 posts returned. There is a $0.00015 minimum per request, including an empty search. A full 20-post page therefore costs about $0.003 at the listed rate. Prices can change, so check the pricing page before running a large collection.
From here, you could export the results to CSV, compare several date ranges, or inspect the authors' public profiles. You could also take an interesting post and collect its public quote posts to see how people responded. Separate requests, profile lookups, and any AI analysis can add cost.
The main takeaway is simple: an API gives you something you can sort and inspect, but the query decides what goes into that dataset in the first place. A clean ranking of a narrow sample is still a ranking of a narrow sample. Keep that limitation in mind when drawing conclusions.
Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.