Get tweets with Python
Three endpoints cover most “get tweets” jobs:
| You want | Endpoint | Key params |
|---|---|---|
| A user’s latest posts | GET /twitter/user/last_tweets |
userName (or userId) |
| A user’s posts and replies | GET /twitter/user/tweet_timeline |
userId |
| Posts matching a query | GET /twitter/tweet/advanced_search |
query, queryType (Latest or Top) |
All three return tweets under the tweets key and page with
cursors.
A user’s latest tweets
Section titled “A user’s latest tweets”import requests
API = "https://api.relayxapi.com"HEADERS = {"X-API-Key": "YOUR_KEY"}
r = requests.get(f"{API}/twitter/user/last_tweets", params={"userName": "NASA"}, headers=HEADERS)for t in r.json()["tweets"]: print(t["createdAt"], t["likeCount"], t["text"][:80])Each tweet includes id, url, text, createdAt, lang, the engagement counts (likeCount,
retweetCount, replyCount, quoteCount, viewCount, bookmarkCount) and an author object.
Search, with operators
Section titled “Search, with operators”queryType=Latest returns the newest matches; Top returns the most engaged. The query uses X’s search
syntax (see the search syntax cheatsheet):
r = requests.get(f"{API}/twitter/tweet/advanced_search", headers=HEADERS, params={ "query": "from:NASA min_faves:1000 -filter:replies", "queryType": "Latest",})tweets = r.json()["tweets"]More than one page
Section titled “More than one page”def search_all(query, max_pages=3): cursor, out = None, [] for _ in range(max_pages): params = {"query": query, "queryType": "Latest", **({"cursor": cursor} if cursor else {})} body = requests.get(f"{API}/twitter/tweet/advanced_search", params=params, headers=HEADERS).json() out += body.get("tweets", []) if not body.get("has_next_page"): break cursor = body["next_cursor"] return outTweets are billed per tweet returned, with a small per-call minimum; a page that returns nothing still
costs the minimum. Check what a call cost in the X-Credits-Cost response header. See
credits in practice and the pricing table.