API reference for the Posts client - create, retrieve, search, and manage posts
The PostsClient provides methods for interacting with posts (tweets) on X. It handles authentication, pagination, and request/response management automatically.
# Search recent posts with automatic paginationfor page in client.posts.search_recent( query="python programming", max_results=100, tweet_fields=["created_at", "public_metrics"]): for post in page.data: print(f"{post.text} - Likes: {post.public_metrics.like_count}")# Get just the first pageresults = next(client.posts.search_recent(query="AI"))print(f"Found {len(results.data)} posts")# Search with time rangefrom datetime import datetime, timedeltaend_time = datetime.utcnow()start_time = end_time - timedelta(days=3)for page in client.posts.search_recent( query="#python", start_time=start_time.isoformat() + "Z", end_time=end_time.isoformat() + "Z", sort_order="relevancy"): print(f"Page has {len(page.data)} posts")
# Get all users who liked a postfor page in client.posts.get_liking_users( id="1234567890", user_fields=["username", "name", "public_metrics"]): for user in page.data: print(f"@{user.username} ({user.name}) - {user.public_metrics.followers_count} followers")# Get just the first 50 usersresults = next(client.posts.get_liking_users( id="1234567890", max_results=50))print(f"{len(results.data)} users liked this post")
Methods that return multiple results (search_recent, get_liking_users, etc.) return iterators that automatically handle pagination:
# Automatic pagination - iterate through all resultsfor page in client.posts.search_recent(query="AI"): for post in page.data: process_post(post)# Manual pagination - get specific pagespage1 = next(client.posts.search_recent(query="AI"))page2 = next(client.posts.search_recent( query="AI", pagination_token=page1.meta.next_token))# Get just first page and stopresults = next(client.posts.search_recent(query="AI"))
X API has rate limits that vary by endpoint and authentication method. The client does not automatically handle rate limiting, but you can add delays:
import timefor page in client.posts.search_recent(query="python"): for post in page.data: process_post(post) time.sleep(1) # Wait 1 second between pages
Consider implementing exponential backoff for production applications.