Back to Blog
tutorialpythonnode.jstwitter apisdk

Get Twitter Data in 5 Lines of Code: Official Python & Node.js SDKs

Official TweetAPI SDKs for Python and Node.js. Install, import, and start pulling tweets, profiles, and followers with typed methods, auto-retry, and built-in pagination.

TweetAPI
TweetAPI Team
April 9, 2026
8 min read

If you've used our API before, you know the drill. Write a fetch wrapper. Parse the JSON. Handle 429s manually. Build a cursor loop for pagination. Repeat for every new endpoint.

It works, but it's the same 30 lines of boilerplate every time. So we built SDKs to get rid of it.

Today we're releasing official SDKs for Python and Node.js/TypeScript. They cover all 70+ endpoints, handle retries and rate limits automatically, and come with full type support out of the box.

Disclaimer: TweetAPI is a third-party service and is not affiliated with, endorsed by, or connected to X Corp.

Before & After

Fetching a user profile — raw HTTP vs. SDK.

Before (Node.js, raw fetch):

const res = await fetch(
  "https://api.tweetapi.com/tw-v2/user/by-username?username=elonmusk",
  { headers: { "X-API-Key": process.env.TWEETAPI_KEY } }
);
if (!res.ok) throw new Error(`API error: ${res.status}`);
const user = await res.json();
console.log(user.data.followerCount);

After (Node.js SDK):

import TweetAPI from "tweetapi-node";

const client = new TweetAPI({ apiKey: process.env.TWEETAPI_KEY });
const user = await client.user.getByUsername({ username: "elonmusk" });
console.log(user.data.followerCount);

Three lines instead of five. But the real win isn't the line count — it's what happens when things go wrong. The SDK retries rate limits automatically, throws typed errors you can catch by name, and handles pagination so you never write another cursor loop.

Installation

Python (3.9+):

pip install tweetapi

Node.js (18+):

npm install tweetapi-node

That's it. The Python SDK depends on requests and nothing else. The Node.js SDK has zero dependencies — it uses the native fetch that shipped with Node 18.

Getting Started

Same idea in both languages: create a client, start calling methods.

Python:

from tweetapi import TweetAPI

client = TweetAPI(api_key="YOUR_API_KEY")

Node.js:

import TweetAPI from "tweetapi-node";

const client = new TweetAPI({ apiKey: "YOUR_API_KEY" });

Every endpoint is a method on the client: client.user, client.tweet, client.explore, client.interaction. It maps to the API structure you already know from the docs. No URL building, no header management.

Real Examples

Enough setup talk. Here's what it looks like in practice.

Fetch a User Profile

user = client.user.get_by_username(username="elonmusk")

print(user["data"]["name"])           # Elon Musk
print(user["data"]["followerCount"])  # 226995885
print(user["data"]["isBlueVerified"]) # True
const user = await client.user.getByUsername({ username: "elonmusk" });

console.log(user.data.name);           // Elon Musk
console.log(user.data.followerCount);  // 226995885
console.log(user.data.isBlueVerified); // true

The Node.js SDK gives you full TypeScript autocomplete on every response field. No more checking the docs to remember if it's followerCount or followers_count.

Search Tweets

results = client.explore.search(query="bitcoin", type="Latest")

for tweet in results["data"]:
    print(f"@{tweet['author']['username']}: {tweet['text'][:100]}")
const results = await client.explore.search({ query: "bitcoin", type: "Latest" });

for (const tweet of results.data) {
  console.log(`@${tweet.author.username}: ${tweet.text.slice(0, 100)}`);
}

Same search operators you'd use on Twitter: from:username, min_faves:100, "exact phrase", filter:images. The type parameter controls whether you get "Latest", "Top", "People", "Photos", or "Videos".

Paginate Through Followers

This is where the SDK really pulls its weight. Without it, you're writing a while loop, tracking cursors, and stitching pages together. With it:

Python:

from tweetapi import paginate

for user in paginate(
    lambda cursor: client.user.get_followers(user_id="44196397", cursor=cursor)
):
    print(f"@{user['username']}{user['followerCount']} followers")

Node.js:

import { paginate } from "tweetapi-node";

for await (const user of paginate(
  (cursor) => client.user.getFollowers({ userId: "44196397", cursor })
)) {
  console.log(`@${user.username}${user.followerCount} followers`);
}

That's it. No cursor tracking, no "is there a next page?" checks, no accumulator arrays. The helper fetches pages as you iterate and yields individual items. If you want to cap it, paginate_pages (Python) or paginatePages (Node.js) lets you set max_pages.

If you've read our Node.js tutorial, you saw the manual version of this — about 15 lines of cursor management. Now it's two.

Handle Errors Without Guessing

Raw API calls give you a status code and a JSON body. You parse it, switch on the code, and hope you covered every case. The SDKs throw specific exception types instead:

Python:

from tweetapi import NotFoundError, RateLimitError

try:
    user = client.user.get_by_username(username="definitelynotreal12345")
except NotFoundError:
    print("That account doesn't exist")
except RateLimitError as e:
    print(f"Slow down. Retry in {e.details.get('retry_after')} seconds")

Node.js:

import { NotFoundError, RateLimitError } from "tweetapi-node";

try {
  const user = await client.user.getByUsername({ username: "definitelynotreal12345" });
} catch (e) {
  if (e instanceof NotFoundError) {
    console.log("That account doesn't exist");
  } else if (e instanceof RateLimitError) {
    console.log(`Slow down. Retry in ${e.retryAfter} seconds`);
  }
}

Full error hierarchy: TweetAPIError (base) > AuthenticationError (401), ValidationError (400), NotFoundError (404), RateLimitError (429), ServerError (5xx). Plus NetworkError / ConnectionError for timeouts and DNS failures.

In practice you won't catch most of these yourself. The SDK already retries the ones worth retrying — 429s, 5xx, network timeouts — automatically with exponential backoff. Three attempts by default. You can change that:

Python:

client = TweetAPI(
    api_key="YOUR_API_KEY",
    max_retries=5,
    initial_retry_delay=2.0,
)

Node.js:

const client = new TweetAPI({
  apiKey: "YOUR_API_KEY",
  retry: { maxRetries: 5, initialRetryDelay: 2000 },
});

4xx client errors (bad params, wrong API key, not found) are never retried — those are bugs in your code, not transient failures.

What's Covered

Both SDKs wrap the entire API — all 70+ endpoints:

ModuleWhat it doesExample methods
userProfiles, followers, following, tweetsget_by_username, get_followers, get_tweets
tweetTweet details, quotes, retweets, translationget_details_and_conversation, get_quotes
postCreate, reply, delete tweetscreate_post, reply_post, delete_post
interactionLikes, retweets, bookmarks, followsfavorite_post, retweet, follow
exploreSearch tweets, users, mediasearch
listList details, members, tweetsget_details, get_members
communityCommunity info, posts, membershipget_tweets, join, leave
spaceSpace info and audio streamsget_by_id, get_stream_url
xchatEncrypted DMssend, get_history
dmUnencrypted DMssend_dm, get_conversation

Write operations (posting, liking, following) require an auth_token parameter — that's your Twitter account's auth token, separate from your TweetAPI API key. The interaction docs explain how this works.

SDK vs. Raw API

If you already have a working setup with raw HTTP calls, you don't need to rewrite everything. The SDK is a wrapper, not a replacement. Same endpoints, same responses, same API key.

But if you're starting something new, here's what you get:

Raw HTTPSDK
SetupBuild fetch wrapper, set headerspip install / npm install
PaginationManual cursor loop (~15 lines)paginate() helper (2 lines)
Error handlingParse status codes yourselfTyped exceptions
Rate limitsWrite retry logicAutomatic with backoff
Type safetyWrite your own interfacesBuilt-in (TypedDicts / TS types)
DependenciesNonerequests (Python) / None (Node)

The existing Node.js tutorial walks through the raw approach in detail. That's not going away — some people prefer full control, and that's fine.

FAQ

Do I need the SDK to use TweetAPI?

No. The REST API works the same as always. The SDK is a convenience layer. If you're working in a language we don't have an SDK for (Go, Ruby, PHP, etc.), the raw API is the way.

Can I use both Python and Node.js SDKs in the same project?

Sure, though it'd be unusual. More common scenario: your backend uses the Node.js SDK and a data science teammate uses the Python one. Same API key works for both.

Are the SDKs open source?

Yes. Both are on GitHub under MIT license:

Issues and PRs are welcome.

What Python/Node versions do I need?

Python 3.9+ and Node.js 18+. The Node SDK uses native fetch, which landed in Node 18. The Python SDK uses requests, which supports 3.9 and up.

How do I report a bug or request a feature?

Open an issue on the GitHub repos. For API-level issues (wrong data, endpoint errors), contact support@tweetapi.com or @tweetapi on Telegram.

Get Started

  1. Install the SDK: pip install tweetapi or npm install tweetapi-node
  2. Get your API key: Sign up at tweetapi.com — 100 free requests, no credit card
  3. Read the docs: Full API reference with examples for every endpoint
  4. See pricing: Plans from $17/month with up to 2M requests

Related posts:


TweetAPI is not affiliated with or endorsed by X Corp. Make sure your use of Twitter data complies with applicable laws and terms of service.