Back to Blog
tutorialpythonnode.jstwitter apisdk

Twitter API with Python & TypeScript: Complete SDK Guide

Call a Twitter API from Python or TypeScript with working SDK examples for profiles, search, pagination, retries, errors, and production setup.

TweetAPI
Published
Updated
10 min read

There is no single Python or TypeScript package named "the Twitter API SDK." Your choice depends on which API you need to call. X maintains its own Python XDK for the official X API, Tweepy wraps the official API, and third-party services such as TweetAPI have separate clients and credentials.

This guide shows the maintained TweetAPI clients from installation through production error handling. The examples fetch a profile, search posts, paginate followers, configure retries, and make the same requests in Python and TypeScript.

If you only need one working call, start with the Python or TypeScript quickstart below. If you are deciding between access methods, use the comparison first.

Last verified: August 3, 2026.

Disclaimer: TweetAPI is a third-party service. Not affiliated with X Corp.

Choose the API and Client First

An SDK only simplifies the API behind it; it does not make different APIs interchangeable.

OptionConnects toBest fitImportant boundary
Official Python XDKOfficial X APITeams that need official X developer access and first-party API capabilitiesRequires official X API credentials and uses the official API's products, limits, and pricing
TweepyOfficial X APIExisting Python projects built around Tweepy's official API wrappersCommunity library; still requires official API access
TweetAPI Python or TypeScript SDKTweetAPIPublic-data, research, monitoring, and documented account-authorized workflows using TweetAPIThird-party service with separate credentials, endpoints, and terms
Raw HTTPWhichever API URL you callUnsupported languages or applications that need full transport controlYou own URLs, headers, types, pagination, retry, and error mapping

Use an official client when an official-only feature, contract, or authentication flow is a requirement. Use the TweetAPI SDK when TweetAPI's endpoint coverage and request-based plans fit the application. Compare current providers and tradeoffs in the Twitter API alternatives guide.

What the TweetAPI SDKs Add

TweetAPI is a REST API, so an SDK is optional. The Python and Node.js/TypeScript packages call the same /tw-v2 endpoints, retain the same response shapes, and use the same X-API-Key authentication as raw HTTP.

The clients add:

  • resource-based methods instead of manual URL construction;
  • pagination helpers for cursor-based collections;
  • structured exceptions for authentication, validation, rate-limit, network, and server failures;
  • configurable retries for transient failures; and
  • TypeScript response types.

If you want zero SDK dependencies and direct transport control, use the native fetch Node.js tutorial.

Install the TweetAPI SDKs

Python

python -m pip install tweetapi

Node.js / TypeScript

npm install tweetapi-node

Current package metadata declares these minimums:

  • tweetapi: Python 3.9+ with requests
  • tweetapi-node: Node.js 18+ with no runtime dependencies

Compatibility is not the same as active runtime support. Python 3.9 and Node.js 18/20 are end-of-life as of July 2026. For a new production project, use a supported Python version and Node.js 22 or 24 LTS from the Node.js release schedule.

Python Quickstart

Create an account, copy the API key from the dashboard, and keep it in an environment variable:

export TWEETAPI_KEY="your_api_key"

Then fetch one user profile:

import os
from tweetapi import TweetAPI

client = TweetAPI(api_key=os.environ["TWEETAPI_KEY"])
user = client.user.get_by_username(username="sample_user_96991")

print(user["data"]["id"])
print(user["data"]["username"])
print(user["data"]["followerCount"])

That is one call to the user-by-username endpoint. The Python method and argument are snake_case; returned JSON fields remain camelCase.

TypeScript Quickstart

Set the same key on the server, then create the client:

import TweetAPI from "tweetapi-node";

const client = new TweetAPI({
  apiKey: process.env.TWEETAPI_KEY!,
});

const user = await client.user.getByUsername({
  username: "sample_user_96991",
});

console.log(user.data.id);
console.log(user.data.username);
console.log(user.data.followerCount);

Do not put an API key in a browser bundle. Run API calls from a server, worker, CLI, or protected serverless function.

Initialize one client per process and reuse it. The quickstarts show the complete profile call in both languages: Python methods and arguments use snake_case, Node.js methods use camelCase, and the shared API response remains nested under data with camelCase fields.

Search Posts

The search endpoint requires a query and a title-case result type.

Python

results = client.explore.search(
    query='"climate data" lang:en',
    type="Latest",
)

for post in results["data"]:
    print(f"@{post['author']['username']}: {post['text'][:100]}")

Node.js / TypeScript

const results = await client.explore.search({
  query: '"climate data" lang:en',
  type: "Latest",
});

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

Valid result types are Latest, Top, People, Photos, and Videos. Search operators are passed in the query string.

Paginate Followers

The followers endpoint returns data and pagination.nextCursor. The SDK helpers can yield individual items across pages.

Python

from tweetapi import paginate

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

Node.js / TypeScript

import { paginate } from "tweetapi-node";

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

Always set an appropriate max_pages or maxPages when the application does not need an entire collection.

Iterate Full Pages

Use paginate_pages in Python or paginatePages in Node.js when you need page-level metadata.

Python

from tweetapi import paginate_pages

for page in paginate_pages(
    lambda cursor: client.explore.search(
        query="tweetapi",
        type="Latest",
        cursor=cursor,
    ),
    max_pages=3,
):
    print(len(page["data"]))
    print(page["pagination"].get("nextCursor"))

Node.js / TypeScript

import { paginatePages } from "tweetapi-node";

for await (const page of paginatePages(
  (cursor) => client.explore.search({
    query: "tweetapi",
    type: "Latest",
    cursor,
  }),
  { maxPages: 3 }
)) {
  console.log(page.data.length);
  console.log(page.pagination.nextCursor);
}

Handle Typed Errors

The SDKs normalize API errors into specific exception classes.

Python

from tweetapi import (
    AuthenticationError,
    ForbiddenError,
    NetworkError,
    NotFoundError,
    RateLimitError,
    ServerError,
    TweetAPIError,
    ValidationError,
)

try:
    user = client.user.get_by_username(username="missing-account-example")
except RateLimitError as error:
    print(f"Retry in about {error.retry_after} seconds")
except NotFoundError:
    print("User not found")
except AuthenticationError:
    print("Check the TweetAPI key")
except ForbiddenError:
    print("The credential cannot perform this operation")
except ValidationError as error:
    print(f"Invalid request: {error.message}")
except NetworkError:
    print("No API response was received")
except ServerError:
    print("TweetAPI returned a server error")
except TweetAPIError as error:
    print(error.code, error.status_code, error.message)

Node.js / TypeScript

import {
  AuthenticationError,
  ConnectionError,
  ForbiddenError,
  NotFoundError,
  RateLimitError,
  ServerError,
  TweetAPIError,
  ValidationError,
} from "tweetapi-node";

try {
  await client.user.getByUsername({ username: "missing-account-example" });
} catch (error) {
  if (error instanceof RateLimitError) {
    console.log(`Retry in about ${error.retryAfter} seconds`);
  } else if (error instanceof NotFoundError) {
    console.log("User not found");
  } else if (error instanceof AuthenticationError) {
    console.log("Check the TweetAPI key");
  } else if (error instanceof ForbiddenError) {
    console.log("The credential cannot perform this operation");
  } else if (error instanceof ValidationError) {
    console.log(`Invalid request: ${error.message}`);
  } else if (error instanceof ConnectionError) {
    console.log("No API response was received");
  } else if (error instanceof ServerError) {
    console.log("TweetAPI returned a server error");
  } else if (error instanceof TweetAPIError) {
    console.log(error.code, error.statusCode, error.message);
  }
}

The Python SDK exports NetworkError; the Node.js SDK exports ConnectionError. Both also expose TweetAPIError, AuthenticationError, ForbiddenError, ValidationError, NotFoundError, RateLimitError, and ServerError.

Configure Automatic Retry

Both SDKs retry transient 429, 5xx, timeout, and connection failures. Client errors such as 400, 401, 403, and 404 are not retried.

The default max_retries or maxRetries value is 3. That means one initial request plus up to three retries, for at most four attempts.

Python

client = TweetAPI(
    api_key=os.environ["TWEETAPI_KEY"],
    max_retries=5,
    initial_retry_delay=2.0,
    backoff_multiplier=2.0,
    max_retry_delay=30.0,
)

Node.js / TypeScript

const client = new TweetAPI({
  apiKey: process.env.TWEETAPI_KEY!,
  retry: {
    maxRetries: 5,
    initialRetryDelay: 2_000,
    backoffMultiplier: 2,
    maxRetryDelay: 30_000,
  },
});

The clients respect rate-limit delay information when it is available and otherwise use bounded backoff. Automatic retry does not replace a shared concurrency queue or request budget.

TweetAPI SDK Endpoint Coverage

Both SDKs group methods by API resource:

ResourcePython exampleNode.js example
Usersclient.user.get_by_username(...)client.user.getByUsername(...)
Postsclient.tweet.get_details_and_conversation(...)client.tweet.getDetailsAndConversation(...)
Searchclient.explore.search(...)client.explore.search(...)
Create postsclient.post.create_post(...)client.post.createPost(...)
Engagementclient.interaction.favorite_post(...)client.interaction.favoritePost(...)
Listsclient.list.get_details(...)client.list.getDetails(...)
Communitiesclient.community.get_tweets(...)client.community.getTweets(...)
Spacesclient.space.get_by_id(...)client.space.getById(...)
Encrypted DMsclient.xchat.send(...)client.xchat.send(...)
DMsclient.dm.get_conversation(...)client.dm.getConversation(...)

See the package READMEs for the complete method list:

Account-Authorized Operations

Posting, engagement, profile, DM, and related account operations require an authToken plus the fields documented for that endpoint. Some media or account workflows require additional parameters such as a proxy or media object.

Do not assume authToken is the only extra field. Start from the exact endpoint page, such as favorite post, and protect account tokens as sensitive credentials.

SDK vs Raw HTTP

ConcernRaw HTTPSDK
Request URLs and headersYour codeClient handles them
Response typesDefine your ownIncluded
PaginationCursor loopIterator helpers
Error mappingCheck status/bodyTyped errors
Transient retryImplement and testBuilt in and configurable
Runtime dependencyNative client onlyrequests for Python; none for Node.js
Custom transport controlMaximumLess direct

Use raw HTTP when you want full control or work in an unsupported language. Use an SDK when consistent retries, types, and pagination reduce application code. The raw Node.js tutorial shows the non-SDK approach.

FAQ

Do I need an SDK to use TweetAPI?

No. TweetAPI is a REST API. Any HTTP client that can send the X-API-Key header and parse JSON can use it.

Are the SDKs open source?

Yes. Both repositories use the MIT License and accept issue reports through GitHub.

Do the SDKs change the API response fields?

No. Responses retain the API's camelCase JSON fields. Python method arguments use snake_case, while Node.js method arguments use camelCase objects.

Does automatic retry prevent rate limits?

No. It handles a transient failure after it happens. You still need to control concurrency and choose a plan that fits peak request volume.

Can I disable retries?

Yes. Use max_retries=0 in Python or retry: false in Node.js.

Where should I report a problem?

Open an issue in the relevant GitHub repository for SDK behavior. For API response or endpoint issues, contact support@tweetapi.com or use TweetAPI on Telegram.

Choose the Integration Style You Want to Maintain

Use raw HTTP if transport details are part of your application's design or if you work in another language. Use an SDK if typed methods, shared retry behavior, and pagination helpers remove code your team would otherwise have to own.

The raw Node.js tutorial shows the first approach. To turn the SDK into a complete application, follow the Python follower-to-CSV exporter or build the Python Twitter brand monitor.

For the SDK route, create a TweetAPI account, make a call with the 100-request trial, and inspect the response before building abstractions around it. You can then browse the full API reference and compare current plans.