Metadata-Version: 2.4
Name: twitterapi-io
Version: 0.2.0
Summary: Official Python SDK + CLI for twitterapi.io — Twitter/X data API. Search tweets, fetch profiles, followers, replies, trends via single API key. No OAuth, no Twitter Developer Account.
Author: twitterapi.io
License: MIT
Project-URL: Homepage, https://twitterapi.io
Project-URL: Documentation, https://twitterapi.io/docs
Keywords: twitter,twitter-api,x-api,sdk,twitter-sdk,twitter-scraper,ai-agent,twitterapi-io,no-oauth,cli
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Internet :: WWW/HTTP
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: httpx>=0.25
Dynamic: license-file

# twitterapi-io (Python)

Official **Python SDK + CLI** for [twitterapi.io](https://twitterapi.io) — Twitter/X data API. Search tweets, fetch user profiles, followers, replies, retweeters, trends. **One API key, no OAuth, no Twitter Developer Account.**

[![PyPI version](https://img.shields.io/pypi/v/twitterapi-io.svg)](https://pypi.org/project/twitterapi-io/)
[![Python 3.9+](https://img.shields.io/badge/python-3.9+-blue.svg)](https://www.python.org/downloads/)
[![MIT License](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)

## Install

```bash
pip install twitterapi-io
```

## Get an API key

Sign up at [twitterapi.io](https://twitterapi.io) — free tier available.

## Quick start (sync)

```python
from twitterapi_io import TwitterApiClient

client = TwitterApiClient(api_key="your_api_key")  # or env TWITTERAPI_TOKEN

user = client.get_user_info(user_name="elonmusk")
print(user["data"]["name"], user["data"]["followers"])

tweets = client.search_tweets(query="from:elonmusk has:images", query_type="Latest")
for t in tweets["tweets"]:
    print(t["text"])
```

## Async variant

```python
import asyncio
from twitterapi_io import AsyncTwitterApiClient

async def main():
    async with AsyncTwitterApiClient(api_key="your_api_key") as client:
        user = await client.get_user_info(user_name="elonmusk")
        print(user)

asyncio.run(main())
```

## CLI

```bash
export TWITTERAPI_TOKEN=your_api_key

twitterapi user-info elonmusk
twitterapi search "from:elonmusk has:images" Latest
twitterapi trends 1 10        # 1 = Worldwide

twitterapi help
```

Output is JSON to stdout — pipe to `jq`:

```bash
twitterapi user-info elonmusk | jq '.data.followers'
```

## API reference

12 read endpoints (v0.1.0):

| Method | Endpoint |
|---|---|
| `search_tweets(query, query_type, cursor)` | Advanced search |
| `get_user_info(user_name)` | Basic profile |
| `get_user_about(user_name)` | Extended profile |
| `get_user_followers(user_name, cursor, page_size)` | Followers |
| `get_user_followings(user_name, cursor, page_size)` | Followings |
| `get_user_last_tweets(user_name OR user_id, cursor, include_replies)` | Recent tweets |
| `get_user_mentions(user_name, since_time, until_time, cursor)` | Mentions |
| `get_tweets_by_ids(tweet_ids)` | Batch fetch (≤100) |
| `get_tweet_replies(tweet_id, cursor, query_type)` | Replies |
| `get_tweet_quotes(tweet_id, since_time, until_time, cursor)` | Quote-tweets |
| `get_tweet_retweeters(tweet_id, cursor)` | Retweeters |
| `get_trends(woeid, count)` | Trending topics |

### Low-level escape hatch

For any endpoint not yet wrapped above:

```python
result = client.get("/twitter/some/new/endpoint", {"foo": "bar"})
```

Full REST API: [twitterapi.io/docs](https://twitterapi.io/docs).

## Error handling

```python
from twitterapi_io import TwitterApiClient, TwitterApiError

try:
    client.get_user_info(user_name="nonexistent_user_xyz")
except TwitterApiError as e:
    print(f"API {e.status}: {e}")
```

Automatic retry on `429` / `5xx` (3 attempts, exponential backoff).

## Coming from tweepy

If your code uses tweepy's v2 `Client` for **reading** data, the `compat` module gives you a tweepy-style interface on top of twitterapi.io. In most scripts you change two lines:

```python
# before
# import tweepy
# client = tweepy.Client(bearer_token=X_BEARER_TOKEN)

from twitterapi_io.compat import TweepyClient
client = TweepyClient(bearer_token="YOUR_TWITTERAPI_IO_KEY")  # your twitterapi.io API key

resp = client.get_users_tweets(id="44196397", exclude=["replies"], expansions=["author_id"])
for tweet in resp.data:
    print(tweet.id, tweet.created_at, tweet.text, tweet.public_metrics["like_count"])

next_token = resp.meta.get("next_token")   # absent on the last page
```

Results come back as `Response(data, includes, errors, meta)` with `Tweet` / `User` objects: the same shape as tweepy. Each object also keeps the full twitterapi.io record in `.data`.

### Supported methods and how many API calls each makes

Every API call is billed at the normal [twitterapi.io prices](https://twitterapi.io/pricing).

| Method | API calls |
|---|---|
| `get_user(username=...)` / `get_user(id=...)` | 1 |
| `get_users(ids=[...])` (up to 100) | 1 |
| `get_users(usernames=[...])` (up to 100) | 1 per username |
| `get_tweet(id)` | 1 |
| `get_tweets(ids)` (up to 100) | 1 per 50 ids |
| `get_users_tweets(id, pagination_token=, exclude=)` | 1 per page |
| `search_recent_tweets(query, start_time=, end_time=, next_token=, sort_order=)` | 1 per page |
| `get_users_followers(id, max_results=, pagination_token=)` / `get_users_following(...)` | 1 per page, **+1 the first time** for each user id (the id is looked up once and cached in the client) |
| `get_users_mentions(id, start_time=, end_time=, pagination_token=)` | 1 per page, **+1 the first time** for each user id |
| `expansions=["author_id"]` | 0 extra (authors are already in the response) |

### Good to know

- `bearer_token` is your **twitterapi.io API key**. X credentials (`consumer_key`, `access_token`, …) are not used, and passing them raises `TypeError`.
- Read-only: write methods such as `create_tweet`, `like` and `follow_user` raise `NotImplementedError`.
- `tweet_fields`, `user_fields` and `expansions` are accepted. All fields are always returned; `expansions=["author_id"]` fills `includes["users"]`.
- `max_results` is accepted. Timeline and search pages have a fixed size (about 20). For followers and following, it sets the page size (20 to 200).
- `search_recent_tweets` is not limited to the last 7 days. `start_time` / `end_time` accept a `datetime` (naive means UTC) or an ISO-8601 string. `sort_order="relevancy"` returns top results; the default returns the latest.
- `public_metrics["impression_count"]` is the view count. `verified` is the blue-check status.
- `wait_on_rate_limit=True` retries on HTTP 429 (up to 3 times, at most 60 seconds in total). `return_type=dict` returns the raw JSON.
- Exceptions use tweepy's names and hierarchy (`TweepyException` → `HTTPException` → `Unauthorized`, `TooManyRequests`, …, plus `PaymentRequired` for 402). They are this package's own classes, so import them from here: `from twitterapi_io.compat import errors`, then `except errors.TooManyRequests:`. `except tweepy.TooManyRequests` will not catch them.

## MCP server (alternative for AI agents)

If building Claude.ai / Claude Code / Cursor integrations, use the hosted MCP:

```
URL: https://mcp.twitterapi.io/mcp
```

Or stdio: [`@twitterapi_io/mcp-server`](https://www.npmjs.com/package/@twitterapi_io/mcp-server)

## License

MIT
