FetchLayer fetchlayer.dev Sign in

+ Integration Guide

Twitter/X API with Python: Complete Guide

How to scrape Twitter/X data with Python using the FetchLayer API. Search tweets, get profiles, fetch replies, and pull follower lists — no Tweepy or X credentials needed.

Written by Alex P.

  • Python
  • twitter scraping
  • X API
  • Twitter API
  • Tweepy alternative
  • API integration

This guide shows how to use the FetchLayer Twitter/X API with Python. Unlike Tweepy, you don’t need X credentials, OAuth setup, or a Twitter developer account. Just an API key and the requests library.


Setup

  1. Get a free API key (no credit card)
  2. Install requests: pip install requests

API Client

import os
import requests

API_KEY = os.environ["FETCHLAYER_API_KEY"]
BASE_URL = "https://api.fetchlayer.dev/twitter"

def twitter(endpoint: str, **kwargs) -> dict:
    res = requests.post(
        f"{BASE_URL}/{endpoint}",
        headers={"Authorization": f"Bearer {API_KEY}"},
        json=kwargs,
    )
    res.raise_for_status()
    return res.json()

Search Twitter/X

data = twitter("search", query="best Python web framework", product="Latest", count=10)

for tweet in data["results"]:
    print(f"[{tweet['likeCount']} likes] @{tweet['author']['handle']}: {tweet['text'][:100]}")
# Search for people/accounts
data = twitter("search", query="Python developer", product="People", count=20)

# Search with pagination
page1 = twitter("search", query="FastAPI", product="Top", count=25)
page2 = twitter("search", query="FastAPI", product="Top", count=25, cursor=page1.get("cursor"))

Get a Tweet by ID

tweet = twitter("tweet-detail", tweetId="1942939879222220800")

print(f"@{tweet['author']['handle']}: {tweet['text']}")
print(f"{tweet['likeCount']} likes · {tweet['retweetCount']} retweets · {tweet['replyCount']} replies")

Get Replies to a Tweet

replies = twitter("tweet-replies", tweetId="1942939879222220800")

for reply in replies["replies"]:
    print(f"  @{reply['author']['handle']}: {reply['text'][:100]}")

Get a User Profile

profile = twitter("user-profile-details", handle="openai")

print(f"{profile['displayName']} (@{profile['handle']})")
print(f"Followers: {profile['followersCount']:,}")
print(f"Following: {profile['followingCount']:,}")
print(f"Tweets: {profile['tweetsCount']:,}")
print(f"Bio: {profile['description']}")

Get a User’s Tweets

data = twitter("user-tweets", handle="rauchg", count=20)

for tweet in data.get("tweets", []):
    print(f"[{tweet.get('likeCount', 0)} likes] {tweet['text'][:120]}")

Get Followers and Following

# Who a user follows
following = twitter("following", handle="openai", count=50)
for account in following.get("accounts", []):
    print(f"@{account['handle']}{account.get('followersCount', 0):,} followers")

# Who follows a user
followers = twitter("followers", handle="openai", count=50)

# Verified followers only
verified = twitter("verified-followers", handle="openai", count=20)

Tweepy vs FetchLayer

If you’re coming from Tweepy, here’s the comparison:

TweepyFetchLayer
X account requiredYes (developer account)No
OAuth setupYes (API key, secret, access token)No
Rate limitsVary by endpoint, strict capsHandled by API
Pricing$100/mo Basic, $5K/mo ProFree tier + pay-per-use
LanguagePython onlyAny (REST API)
MCP supportNoYes
Authentication4 keys (key, secret, token, token secret)Single API key

Tweepy equivalent vs FetchLayer:

# Tweepy (requires X developer account + OAuth)
import tweepy
client = tweepy.Client(bearer_token="...")
tweets = client.search_recent_tweets(query="python", max_results=10)

# FetchLayer (just an API key)
data = twitter("search", query="python", product="Latest", count=10)

Full Example: Twitter Keyword Monitor

import os
import requests
from datetime import datetime

API_KEY = os.environ["FETCHLAYER_API_KEY"]
BASE_URL = "https://api.fetchlayer.dev/twitter"

def twitter(endpoint: str, **kwargs) -> dict:
    res = requests.post(
        f"{BASE_URL}/{endpoint}",
        headers={"Authorization": f"Bearer {API_KEY}"},
        json=kwargs,
    )
    res.raise_for_status()
    return res.json()

def monitor_keyword(keyword: str, count: int = 25):
    """Search Twitter for a keyword and summarize results."""
    data = twitter("search", query=keyword, product="Latest", count=count)

    results = data.get("results", [])
    print(f"\nFound {len(results)} tweets for '{keyword}'")

    # Engagement summary
    total_likes = sum(t.get("likeCount", 0) for t in results)
    total_retweets = sum(t.get("retweetCount", 0) for t in results)
    print(f"Total engagement: {total_likes:,} likes, {total_retweets:,} retweets")

    # Top tweets
    top = sorted(results, key=lambda t: t.get("likeCount", 0), reverse=True)[:5]
    print(f"\nTop 5 tweets:")
    for tweet in top:
        print(f"  [{tweet['likeCount']}] @{tweet['author']['handle']}: {tweet['text'][:120]}")
        print(f"  {tweet.get('url', '')}\n")

if __name__ == "__main__":
    monitor_keyword("your-product-name")
FETCHLAYER_API_KEY=sk-your-key python monitor.py

What’s Next