Tweepy - Python client for X API

4.16.0 · active · verified Thu Apr 09

Tweepy is a popular, easy-to-use Python library for accessing the X API (formerly Twitter API). It provides a Pythonic way to interact with both v1.1 and v2 of the API, handling authentication, requests, and response parsing. The current version is 4.16.0, and it generally releases new versions frequently, often tied to changes or additions in the X API.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use `tweepy.Client` for accessing the Twitter API v2. It fetches the user ID for a specified username and then retrieves their latest tweets. For public data access, a Bearer Token (Developer Portal > Projects & Apps > your_app > Keys and tokens) is typically sufficient. For user-specific actions (like posting tweets), more complex OAuth 2.0 PKCE or OAuth 1.0a authentication is required.

import os
import tweepy

# For Twitter API v2, using a Bearer Token (read-only for public data)
bearer_token = os.environ.get("TWITTER_BEARER_TOKEN", "YOUR_BEARER_TOKEN")

if not bearer_token or bearer_token == "YOUR_BEARER_TOKEN":
    print("Warning: TWITTER_BEARER_TOKEN environment variable not set or is default. Quickstart may fail.")
    print("To run this example, set TWITTER_BEARER_TOKEN or replace 'YOUR_BEARER_TOKEN' with an actual key.")

try:
    client = tweepy.Client(bearer_token)

    # Example: Get recent tweets by a user
    username = "tweepy"
    response = client.get_user(username=username)
    user_data = response.data

    if user_data:
        user_id = user_data.id
        print(f"User ID for @{username}: {user_id}")

        response = client.get_users_tweets(user_id, tweet_fields=["created_at", "author_id"], max_results=5)
        if response.data:
            print(f"Latest tweets from @{username}:")
            for tweet in response.data:
                print(f"- [{tweet.created_at.strftime('%Y-%m-%d %H:%M')}] {tweet.text}")
        else:
            print(f"No tweets found for @{username}.")
    else:
        print(f"User @{username} not found or error occurred.")

except tweepy.TweepyException as e:
    print(f"An error occurred with Tweepy: {e}")
except Exception as e:
    print(f"An unexpected error occurred: {e}")

view raw JSON →