TweeterPy for Twitter (X): which calls need a login, what breaks, and how to port it to REST

By TwitterAPI.io Team•16 min read
Diagram comparing two request paths. TweeterPy lane in amber: load x.com, guest token from 1.1/guest/activate, login with an auth_token cookie (12 of 17 methods), one of 22 GraphQL query IDs, parse timeline entries. REST lane in green: API key header, GET /twitter/user/info or /twitter/user/last_tweets, flat JSON, next_cursor, billed per record at 15 credits per tweet.
TweeterPy drives X's web GraphQL API through a session; a REST read is one GET with an API key. Source census and 37 REST requests, collected in 2026.
TL;DR
  • What it is. TweeterPy is a Python wrapper around X's own web GraphQL API: a guest token, an optional logged-in session, and 22 hard-coded GraphQL operations in version 2.0.17.
  • Login is the norm. 12 of 17 data methods carry @login_decorator; get_user_tweets(with_replies=True) and get_tweet(with_tweet_replies=True) also log in. Only get_user_id, get_user_data and get_user_highlights stay guest-only.
  • Rate limits are X's. The library reads the x-rate-limit-* headers and raises RateLimitError when they hit zero; it does not wait or retry for you.
  • Maintained, but reactive. PyPI shows 2.0.17 released June 27, 2026, a fix for a missing ondemand.s file URL; a newer report about the same file and two login-failure reports are still open.
  • Port the core three. get_user_data becomes /twitter/user/info, get_user_tweets becomes /twitter/user/last_tweets, get_friends becomes /twitter/user/followers or /followings. 24 of the 30 fields on TweeterPy's Tweet class have a direct key in every post we fetched.
  • Measured cost. This study's 480 posts cost $0.072 at 15 credits each; the same posts at the official X API rate would be $2.40, and the 1,200 follower records $12.00 against $0.012 to $0.036.

This page is about one library: TweeterPy, what its own code does, where it needs an X login, and how to move its calls to a REST endpoint. It is not a general explainer of X's internal API (our Twitter GraphQL API page covers query IDs, x-client-transaction-id and what X's terms say), and it is not the twikit review, which covers an async library with a different method set and its own fork history. If you came here from twikit, the shape of the problem is the same; the method names, the login rules and the numbers below are TweeterPy's.

TweeterPy is small and readable: one 663-line tweeterpy.py, a login task handler, a GraphQL query-ID updater and two dataclasses. That makes it possible to answer the questions people actually ask about it from the source rather than from forum posts: which calls work without logging in, what happens at a rate limit, which fields come back, and what changed in recent releases. We installed version 2.0.17 from PyPI into a throwaway virtual environment, imported it and parsed it with Python's ast module. We did not run it against x.com, did not log in with it and did not feed it any cookies; every statement about its runtime behavior below is quoted from its code, its README, its docs file or its issue tracker.

Then we ran the three calls TweeterPy users reach for first (a profile, a user's tweets, a follower list) through REST endpoints for six public accounts: @github, @NASA, @OpenAI, @nvidia, @Microsoft and @elonmusk. That is 37 requests, 480 posts and 1,200 follower records, collected in 2026, and it gives the field mapping, page sizes and cost figures used throughout.

TweeterPy data methods that always log in to an X account

12 of 17 in version 2.0.17 (static read of the installed package, collected in 2026); 2 more log in for reply options, and only 3 run as a guest.

01 — Section

What TweeterPy is, from its README, PyPI and source

The PyPI summary is direct: "TweeterPy is a python library to extract data from Twitter. TweeterPy API lets you scrape data from a user's profile like username, userid, bio, followers/followings list, profile media, tweets, etc." The project lives at github.com/iSarabjitDhiman/TweeterPy, is MIT-licensed, and showed about 340 stars, 52 forks and 16 open issues when we checked. There are no GitHub releases; versions ship to PyPI only, from 0.0.1 in June 2023 to 2.0.17 on June 27, 2026.

Installing it pulls six dependencies, per pip show tweeterpy on 2.0.17: curl-cffi (the HTTP client since 2.0.13), XClientTransaction (generates the X-Client-Transaction-Id header X's web app sends), beautifulsoup4 and lxml (parse the x.com home page), demjson3 (reads JavaScript objects out of X's bundles) and pyotp (time-based one-time codes for accounts with two-factor login).

What one TweeterPy() call does. The constructor builds a session, loads the x.com home page, reads the ondemand.s JavaScript file needed for the transaction header, and requests a guest token from api.x.com/1.1/guest/activate.json. It then runs ApiUpdater, which downloads X's JavaScript bundles and re-reads the current GraphQL query IDs and feature switches, falling back to a cached copy when that fails. Data calls go to https://api.x.com/graphql/<queryId>/<OperationName>, for example UserByScreenName, UserTweets, Followers and SearchTimeline.

Guest or logged in. A plain TweeterPy() is a guest session. login(username, password, email=..., phone=..., mfa_secret=...) walks X's onboarding flow; generate_session(auth_token=...) builds a session from an existing auth_token cookie; save_session() and load_session() write and restore it from disk. The README adds its own warning: "Use it on Your Own Risk", and it advises against using a personal account.

What comes back. Single-object methods return X's raw GraphQL result dict (profile fields sit under legacy, for example legacy.followers_count). Paginated methods return a dict with data (a list of timeline entries), cursor_endpoint, has_next_page and api_rate_limit. Two helper dataclasses, User and Tweet in tweeterpy.util, flatten an entry into snake_case attributes such as screen_name, favorite_count and views.

python
# The TweeterPy calls this page ports, as its docs show them (not run here).
from tweeterpy import TweeterPy

twitter = TweeterPy()                      # guest session
user = twitter.get_user_data("nasa")       # guest: raw GraphQL result, fields under legacy
user_id = twitter.get_user_id("nasa")      # guest

# login(...) or generate_session(auth_token=...) is needed below
tweets = twitter.get_user_tweets(user_id, total=40)          # guest unless with_replies=True
followers = twitter.get_friends(user_id, follower=True, total=200)  # @login_decorator
print(tweets["has_next_page"], tweets["cursor_endpoint"])
print(followers["api_rate_limit"])  # remaining / reset from x-rate-limit-* headers
02 — Section

Which TweeterPy calls work without logging in: the 17-method census

The README examples start with a guest session, which suggests the library mostly runs logged out. The code says otherwise. We parsed tweeterpy.py from 2.0.17 and classified every public data method (session helpers such as login, save_session and update_api excluded). A method counts as "always" when it is wrapped in @login_decorator, which calls self.login() (and prompts for a username and password) whenever no auth_token cookie is present. It counts as "some options" when it calls self.login() inline for a particular argument.

Login needMethodsCount
Always (@login_decorator)get_user_info, get_multiple_users_data, get_user_media, get_liked_tweets, get_user_timeline, get_list_tweets, get_topic_tweets, search, get_friends, get_profile_business_category, get_tweet_likes, get_retweeters12
Some optionsget_user_tweets (with_replies=True), get_tweet (with_tweet_replies=True)2
Guestget_user_id, get_user_data, get_user_highlights3

The project's docs/docs.md agrees: it labels the same twelve methods "LOGIN REQUIRED". So search, followers, followings, likes, list timelines and retweeters all run as an X account. Only a profile lookup by handle and the plain user timeline stay guest-only, and get_user_info (lookup by numeric ID) needs a login even though get_user_data (lookup by handle) returns the same profile without one.

That matters for two reasons. First, every logged-in call acts as that account, and X's terms and limits apply to it: X can rate-limit, lock or suspend that account, and the README itself steers users away from their personal account. Second, the login flow is the part that breaks: three of the open issues are login failures ("Error code 399 - Could not log you in now", and two titled "twitter login failed").

Grid of TweeterPy 2.0.17 data methods colored by login need: 12 always require login (get_friends, search, get_user_info, get_list_tweets and others), 2 require login for some options (get_tweet, get_user_tweets), 3 work as guest (get_user_data, get_user_highlights, get_user_id).
12 of 17 TweeterPy data methods always log in to an X account. Static read of the installed package, collected in 2026.
03 — Section

TweeterPy rate limits, RateLimitError and account locks

TweeterPy does not have rate limits of its own; it inherits X's. Every response passes through util.check_api_rate_limits, which reads three response headers, x-rate-limit-limit, x-rate-limit-remaining and x-rate-limit-reset, and stores them. Paginated methods hand them back as api_rate_limit so your loop can see how many calls remain in the window and when it resets. When a request fails and the stored remaining value is exhausted, RequestClient.request raises tweeterpy.util.RateLimitError('API Rate Limit Exceeded.').

What it does not do. There is no automatic wait, retry or account rotation. _handle_pagination catches a ConnectionError and loops again; any other exception is logged and the partial data_container is returned, so a long get_friends(..., total=5000) can come back short without raising. Check has_next_page and cursor_endpoint on every result and resume with end_cursor= rather than assuming the list is complete.

Limits are per account and per operation. Because the limit headers come from X's web endpoints, the budget belongs to the session you are using: a guest token for guest calls, the logged-in account for everything else. TweeterPy does not publish numbers for those budgets, and its docs say nothing about guest limits; we found no primary source that states them, so we do not quote any.

Locks and challenges. After login(), the library fetches the viewer profile and, if it sees a bounce_location key and no screen name, raises "Account logged in but couldn't get the user's details ! Make sure, the given account is working." That is the code path a locked or challenged account lands on. Recovering it happens on x.com, not in the library.

If your job is reading public data, the cleaner route is to remove the account from the loop. A REST endpoint that needs only an API key has no session to lock: the limit is the provider's request rate (0.2 requests per second before the first payment, 20 once paid, 50 on Scale, 500 on Business), and a page that fails can be re-requested with the same cursor.

04 — Section

Is TweeterPy still maintained? Releases and open issues

Yes, in the reactive sense that matters for a library built on X's web app: when X changes something, a release follows. The PyPI history and the commit log show the pattern.

WhenVersion or commitWhat changed
June 20230.0.1First release on PyPI
November 10, 20242.0.0 to 2.0.6Seven releases in one day for the 2.x line
October 1, 20252.0.13Fix #105, a 403 Cloudflare error: HTTP layer moved to curl-cffi
March 19, 20262.0.15XClientTransaction bumped to 1.0.2
June 27, 20262.0.17Fix #113: failed to get the ondemand.s file URL
July 10, 2026commitlxml bumped to 6.1.0 (latest commit on master)

What is open. Issue #116, "ondemand.s not found", was opened in October 2026, after the 2.0.17 fix for the same file. #115 and #112 are both "twitter login failed"; #107 is "Error code 399 - Could not log you in now. Please try again later." #108 is a roadmap checklist for a 3.0.0 stable release, opened in February 2026. #106 asks for createTweet: TweeterPy reads data and has no write methods.

Read together, the log says the maintainer responds to breakage, and the breakage keeps coming from the same two places: the files on x.com the library has to parse before it can sign a request, and the login flow. Neither is under the library's control. That is the cost of the GraphQL approach in general (our Twitter GraphQL API explainer counts how often the query IDs move), not a judgment on this maintainer.

05 — Section

The migration table: every TweeterPy method, mapped to a REST endpoint

Nine of the 17 methods have a direct REST equivalent that needs no X account, search maps onto advanced_search, and get_user_media becomes a search query. The remaining six have no published read endpoint (several are views of the logged-in account itself), and we say so instead of inventing one.

TweeterPy methodREST endpointNotes
get_user_data(username)GET /twitter/user/info?userName=Flat profile, 25 fields in our sample
get_user_info(user_id)GET /twitter/user/batch_info_by_ids?userIds=By numeric ID, comma-separated
get_multiple_users_data(ids)GET /twitter/user/batch_info_by_ids?userIds=Returns users[]
get_user_id(username)GET /twitter/user/info?userName=Read data.id
get_user_tweets(id)GET /twitter/user/last_tweets?userName=20 per page; includeReplies=true for replies
get_friends(follower=True)GET /twitter/user/followers?userName=Up to 200 per page with pageSize
get_friends(following=True)GET /twitter/user/followings?userName=Up to 200 per page
get_tweet(id)GET /twitter/tweets?tweet_ids=Comma-separated IDs
get_tweet(with_tweet_replies=True)GET /twitter/tweet/advanced_searchQuery conversation_id:<id>
get_retweeters(id)GET /twitter/tweet/retweeters?tweetId=Paged
get_list_tweets(list_id)GET /twitter/list/tweets?listId=Paged
search(query)GET /twitter/tweet/advanced_searchqueryType=Latest or Top
get_user_media(id)GET /twitter/tweet/advanced_searchQuery from:<handle> filter:media
get_friends(mutual_follower=True)noneDepends on the viewer's own graph
get_user_timeline(), get_liked_tweets, get_tweet_likesnoneViewer home feed and likes lists
get_topic_tweets, get_user_highlights, get_profile_business_categorynoneNo published read endpoint

Search operators carry over. TweeterPy's search() sends your raw query string to X's SearchTimeline with a product of Top, Latest, People, Photos or Videos. advanced_search takes the same operator syntax (from:, to:, lang:, min_faves:, filter:media) with queryType=Latest or Top; date windows use since_time:<unix> and until_time:<unix> inside the query. For people search, GET /twitter/user/search?query= returns users[].

Pagination translates one to one. TweeterPy's end_cursor argument and cursor_endpoint result become a cursor parameter and a next_cursor field; has_next_page keeps its name. The compat module at the end of this page returns TweeterPy's dict shape, so loops written against result["data"] keep working.

06 — Section

Field mapping: TweeterPy's Tweet and User classes against the REST objects

TweeterPy's Tweet dataclass declares 30 attributes. We mapped each one to a key on the REST tweet object and checked the key in all 480 posts we fetched. 24 have a direct equivalent that was present in every post (for hashtags and user_mentions, the entities container is always present and the list appears when the post has any). The other six are viewer state or derived: favorited, retweeted and bookmarked describe what the logged-in account did, possibly_sensitive_editable and is_translatable are web-app flags, and original_tweet is a URL TweeterPy builds from in_reply_to_screen_name and in_reply_to_status_id_str, which you can build the same way from inReplyToUsername and inReplyToId.

TweeterPy TweetREST tweet keyTweeterPy UserREST user key
rest_id, id_stridrest_idid
full_texttextscreen_nameuserName
favorite_countlikeCountfollowers_countfollowers
retweet_count, quote_countretweetCount, quoteCountfriends_countfollowing
reply_count, bookmark_countreplyCount, bookmarkCountstatuses_countstatusesCount
views (dict)viewCount (integer)favourites_countfavouritesCount
created_atcreatedAtmedia_countmediaCount
conversation_id_strconversationIdprofile_image_url_httpsprofilePicture
in_reply_to_status_id_strinReplyToIdprofile_banner_urlcoverPicture
screen_name, name, user_id_strauthor.userName, author.name, author.idis_blue_verified, verified_typeisBlueVerified, verifiedType
is_quote_statusisQuote (+ quoted_tweet)can_dm, pinned_tweet_ids_strcanDm, pinnedTweetIds
tweet_urlurlcreated_atcreatedAt

Fill rates in the sample. viewCount, bookmarkCount, lang and conversationId were populated on 100.0% of the 480 posts. 46.0% carried media in extendedEntities.media, 35.6% had a link in entities.urls, 14.2% had hashtags, 39.2% were reposts (retweeted_tweet holds the original) and 6.0% were quotes. Reposts carry the original post's full object, so you do not need a second lookup the way you would to expand a GraphQL entry.

Two differences to code for. TweeterPy's views is the dict X's GraphQL returns, while viewCount is a plain integer. TweeterPy's created_at is X's legacy timestamp string, and the REST tweet createdAt uses the same Thu Oct 16 12:34:56 +0000 2026 layout, so date parsing code carries over unchanged. Profile createdAt from /twitter/user/info is ISO 8601 instead.

07 — Section

The three core calls over REST: what six public accounts returned

We ran the REST version of TweeterPy's three workhorse calls for each account: one /twitter/user/info, four pages of /twitter/user/last_tweets and one page of /twitter/user/followers with pageSize=200, plus a single /twitter/user/batch_info_by_ids call for all six IDs. Every timeline page held exactly 20 posts and reported has_next_page: true; every follower page held 200 records. The batch call returned all 6 profiles in one response.

AccountPosts fetchedMedian viewsMedian likesFollowers
@github80 in 4 pages43,7571892,748,255
@NASA80 in 4 pages543,2662,25592,013,469
@OpenAI80 in 4 pages944,0144,9545,580,465
@nvidia80 in 4 pages103,0717532,788,778
@Microsoft80 in 4 pages69,06125213,058,247
@elonmusk80 in 4 pages588,8025,560239,274,519

Profiles. /twitter/user/info returned a median of 25 top-level fields per account, flat and camelCase, including isAutomated, canDm, verifiedType and pinnedTweetIds. The equivalent TweeterPy result nests the counts under legacy and the verification state in separate keys, which is why the library ships the User dataclass to flatten it.

Followers. The follower records are private individuals, so we kept only aggregates: of the 1,200 records, 35.2% had a bio, 23.2% a location, 10.4% a profile link, and 9.0% were protected accounts. Each record carries screen_name, followers_count, following_count, statuses_count, created_at and can_dm in snake_case, close to TweeterPy's User attribute names.

Replies. TweeterPy needs a login for get_user_tweets(with_replies=True). Over REST it is the same last_tweets call with includeReplies=true; for a whole reply tree, search conversation_id:<id> with advanced_search.

python
import os
import requests

BASE = "https://api.twitterapi.io"
H = {"X-API-Key": os.environ["TWITTERAPI_IO_KEY"]}

# get_user_data("github")
profile = requests.get(f"{BASE}/twitter/user/info", headers=H,
                       params={"userName": "github"}, timeout=30).json()["data"]
print(profile["id"], profile["followers"], profile["verifiedType"])

# get_user_tweets(user_id): one page, then follow next_cursor
page = requests.get(f"{BASE}/twitter/user/last_tweets", headers=H,
                    params={"userName": "github"}, timeout=30).json()
for t in page["data"]["tweets"]:
    print(t["id"], t["likeCount"], t["viewCount"], t["isReply"])
print(page["has_next_page"], page["next_cursor"])

# get_friends(user_id, follower=True): up to 200 per page
fol = requests.get(f"{BASE}/twitter/user/followers", headers=H,
                   params={"userName": "github", "pageSize": 200}, timeout=30).json()
print(len(fol["followers"]), fol["has_next_page"])
08 — Section

Cost: TweeterPy is free, so what does the REST route cost, and what would the official X API charge?

TweeterPy costs nothing to install. What it spends is an X account (or several), the time to keep logins working, and the risk that the account is limited or locked. The REST route turns that into a per-record bill, and the official X API is the other priced option, so here are both rate cards against the volume of this study.

Volume in this studyTwitterAPI.ioOfficial X API
480 posts$0.072 (15 credits each)$2.40 ($0.005 per post read)
12 profile reads$0.00216 (18 credits each)$0.12 ($0.010 per user read)
1,200 follower records$0.012 to $0.036 (1 to 3 credits each)$12.00 ($0.010 per follower read)

Per 1,000 posts. Tweet endpoints are billed at 15 credits per post returned, $0.15 per 1,000 posts, with a minimum of 15 credits ($0.00015) per request, so a full 20-post page costs $0.003 and an empty result costs the minimum. The official X API pay-per-usage card at docs.x.com/x-api/getting-started/pricing lists $0.005 per post read, $5 per 1,000, about 33 times more, and caps pay-per-usage at 3 million post reads a month before Enterprise. X also offers $20 in API credits when you save a first eligible card and make a first credit purchase.

Profiles and followers. Profiles are 18 credits each, $0.18 per 1,000; the official card lists $0.010 per user read. Follower and following lists are 1 to 3 credits per user returned depending on page tier, against $0.010 per record on the official card. For follower-heavy jobs that gap is the one that decides the bill, as the chart shows.

Getting started. Reads need no X account. 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. Purchased credits never expire. Monthly plans run from Starter at $29 to Business at $1,499.

Horizontal bar chart comparing costs for the study volume. 480 posts: $2.40 on the official X API versus $0.072 on TwitterAPI.io. 12 profile reads: $0.12 versus $0.00216. 1,200 follower records: $12.00 versus $0.012 to $0.036.
What this study's 37 REST requests would cost on each published rate card. Volumes collected in 2026.
09 — Section

Writes, a compat module, and how we collected this

Writes. TweeterPy has no write methods; issue #106 asks for createTweet and is open. If your project also needs to post, writes on our side run through an authenticated session: one /twitter/user_login_v2 login ($0.10, with a proxy you supply) returns login_cookies, and each post, like, follow or DM (/twitter/create_tweet_v2, /twitter/follow_user_v2, ...) is 60 credits ($0.0006) per successful call; calls that return status: error are not charged. The call acts as that account, so X can rate-limit, lock or suspend it; keep a normal human pace, and expect the session to need a fresh login from time to time.

The compat module. The full example at the end of this page, tweeterpy_compat.py, keeps TweeterPy's method names (get_user_data, get_user_tweets, get_friends) and its return shape (data, cursor_endpoint, has_next_page) while calling REST endpoints underneath. Swap the import, set TWITTERAPI_IO_KEY, and loops that read result["data"] keep running. The difference you will notice is the item shape: flat REST objects instead of GraphQL timeline entries, so code that went through tweeterpy.util.Tweet(entry) reads the keys in the mapping table directly.

How we collected this. Question: which TweeterPy calls need a logged-in X account, and what do its three core calls return and cost over REST? Part A: we installed tweeterpy==2.0.17 from PyPI into a throwaway virtual environment, imported it and parsed tweeterpy.py and constants.py with Python's ast module; no TweeterPy call was made to x.com. Part B: through our rate-limited read client, one /twitter/user/info, four /twitter/user/last_tweets pages and one /twitter/user/followers page per account for @github, @NASA, @OpenAI, @nvidia, @Microsoft and @elonmusk, plus one /twitter/user/batch_info_by_ids call, collected in 2026.

Sample. 37 requests: 480 posts, 12 profile reads and 1,200 follower records. Window: the latest posts of each account at collection time and the first follower page.

What the sample cannot show. It does not measure TweeterPy's own speed, success rate or how fast an account gets limited, because we did not run it against X. Six large accounts are not a random sample of X, so the fill rates describe these timelines, not the platform. One follower page per account covers 200 records, a sliver of these accounts' audiences, so the follower aggregates describe that page only.

Privacy. Aggregates only. The named accounts are organizations and one public figure. Follower records belong to private individuals: their raw pages stayed in temporary storage, were never published, and were only counted (fill rates), never examined person by person.

python
"""tweeterpy_compat.py: the three TweeterPy calls people use, served by REST endpoints.

Returns the same dict shape TweeterPy's paginated methods return
(data, cursor_endpoint, has_next_page), so a script that loops over
result["data"] keeps working. No X account, no session file, no query ids.
"""
import os
import time

import requests

BASE = "https://api.twitterapi.io"
HEADERS = {"X-API-Key": os.environ["TWITTERAPI_IO_KEY"]}
# Fixed pacing. Before your first payment the limit is 0.2 requests/s (one call every 5 s);
# once paid it is 20 requests/s, so 0.05 s is enough.
PACE_SECONDS = 5.0


def _get(url, params):
    time.sleep(PACE_SECONDS)
    r = requests.get(url, headers=HEADERS, params=params, timeout=30)
    r.raise_for_status()
    body = r.json()
    if body.get("status") == "error":
        raise RuntimeError(body.get("msg"))
    return body


def get_user_data(username):
    """TweeterPy get_user_data / get_user_info: one profile, flat keys."""
    body = _get(f"{BASE}/twitter/user/info", {"userName": username})
    return body["data"]  # id, userName, followers, following, statusesCount, createdAt, ...


def get_user_tweets(username, with_replies=False, end_cursor=None, total=100):
    """TweeterPy get_user_tweets: newest first, 20 per page."""
    out, cursor, has_next = [], end_cursor or "", True
    while has_next and len(out) < total:
        params = {"userName": username, "cursor": cursor}
        if with_replies:
            params["includeReplies"] = "true"
        body = _get(f"{BASE}/twitter/user/last_tweets", params)
        out.extend(body["data"]["tweets"])
        has_next = bool(body.get("has_next_page"))
        cursor = body.get("next_cursor") or ""
        if not cursor:
            has_next = False
    return {"data": out[:total], "cursor_endpoint": cursor, "has_next_page": has_next}


def get_friends(username, follower=False, following=False, end_cursor=None, total=400):
    """TweeterPy get_friends: follower=True or following=True, up to 200 per page."""
    if follower == following:
        raise ValueError("set exactly one of follower / following")
    url = f"{BASE}/twitter/user/followers" if follower else f"{BASE}/twitter/user/followings"
    key = "followers" if follower else "followings"
    out, cursor, has_next = [], end_cursor or "", True
    while has_next and len(out) < total:
        body = _get(url, {"userName": username, "cursor": cursor, "pageSize": 200})
        out.extend(body.get(key, []))
        has_next = bool(body.get("has_next_page"))
        cursor = body.get("next_cursor") or ""
        if not cursor:
            has_next = False
    return {"data": out[:total], "cursor_endpoint": cursor, "has_next_page": has_next}


if __name__ == "__main__":
    user = get_user_data("nasa")
    print(user["userName"], user["followers"], user["statusesCount"])

    tweets = get_user_tweets("nasa", total=40)
    for t in tweets["data"][:5]:
        print(t["createdAt"], t["likeCount"], t["viewCount"], t["text"][:60])
    print("next page:", tweets["has_next_page"])

    fans = get_friends("nasa", follower=True, total=200)
    print(len(fans["data"]), "followers, first:", fans["data"][0]["screen_name"])

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

10 — Questions

Questions readers ask

What is TweeterPy?

TweeterPy is an MIT-licensed Python library by Sarabjit Dhiman, installed with pip install tweeterpy, that reads Twitter (X) data through the internal GraphQL endpoints the x.com web app uses. It returns profiles, user tweets, followers and followings, search results, lists, likes and retweeters. It has no write methods.

Does TweeterPy work without logging in?

Partly. In version 2.0.17, 3 data methods run as a guest (get_user_id, get_user_data, get_user_highlights), get_user_tweets and get_tweet run as a guest unless you ask for replies, and the other 12 (including search, get_friends and get_user_info) carry @login_decorator and will prompt for an X login.

How do I log in with TweeterPy?

Per its docs, use one of three methods: twitter.login(username, password, email=..., mfa_secret=...), twitter.generate_session(auth_token=...) with an existing auth_token cookie, or twitter.load_session(path) for a session saved earlier with save_session(). Every logged-in call then acts as that account under X's terms, and X can limit or lock it.

What are TweeterPy's rate limits?

TweeterPy has none of its own. It reads X's x-rate-limit-limit, x-rate-limit-remaining and x-rate-limit-reset headers, returns them as api_rate_limit on paginated results, and raises RateLimitError when the remaining budget is exhausted. It does not wait or retry automatically, and its docs do not publish the budget numbers.

Is TweeterPy still maintained?

Yes. PyPI lists 2.0.17, released June 27, 2026, which fixed a failure to find the ondemand.s file URL, and the latest commit on master is a dependency bump from July 10, 2026. Open issues include a newer "ondemand.s not found" report, two "twitter login failed" reports and a 3.0.0 roadmap.

Why does TweeterPy fail with "ondemand.s" or login errors?

Before it can sign a request, TweeterPy parses the x.com home page and a JavaScript file (ondemand.s) to build the X-Client-Transaction-Id header, and its login walks X's web onboarding flow. When X changes either, the library breaks until a release catches up. Upgrade with pip install -U tweeterpy and check the issue tracker for the current report.

What is a good TweeterPy alternative that needs no X account?

For reading public data, a REST API that takes an API key: get_user_data maps to /twitter/user/info, get_user_tweets to /twitter/user/last_tweets, get_friends to /twitter/user/followers or /twitter/user/followings, and search to /twitter/tweet/advanced_search. Posts are $0.15 per 1,000; the official X API lists $0.005 per post read. Other open-source libraries (twikit, twscrape) use the same logged-in GraphQL approach as TweeterPy.

Can I keep my TweeterPy code when I migrate?

Mostly. The tweeterpy_compat.py example on this page keeps the method names and the data / cursor_endpoint / has_next_page return shape. What changes is each item: flat REST keys such as likeCount and viewCount instead of GraphQL entries read through tweeterpy.util.Tweet.

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.