Skip to main content

Overview

This guide walks you through creating and posting your first tweet using XDK Python. You’ll learn how to authenticate, create a post, and handle the response.
Make sure you’ve completed the installation and have your API credentials ready.

Your First Tweet in 3 Steps

1

Install and Import

First, ensure XDK is installed and import the required modules:
pip install xdk python-dotenv
from xdk import Client
from xdk.posts.models import CreateRequest
import os
from dotenv import load_dotenv

# Load environment variables
load_dotenv()
2

Initialize the Client

Create a client instance with your authentication credentials:
# If you already have an access token
client = Client(
    access_token=os.getenv("X_ACCESS_TOKEN")
)
3

Post a Tweet

Create and send your tweet:
# Create a post request
request = CreateRequest(text="Hello from XDK Python! 🚀")

# Post the tweet
response = client.posts.create(body=request)

# Print the result
print(f"Success! Tweet ID: {response.data.id}")
print(f"Tweet text: {response.data.text}")

Complete Working Example

Here’s a complete script that posts a tweet:
example.py
#!/usr/bin/env python3
"""Post a tweet using XDK Python SDK."""

from xdk import Client
from xdk.posts.models import CreateRequest
import os
from dotenv import load_dotenv

# Load environment variables from .env file
load_dotenv()

def main():
    """Post a tweet using XDK."""
    # Initialize client with access token
    client = Client(
        access_token=os.getenv("X_ACCESS_TOKEN")
    )
    
    # Create the tweet
    request = CreateRequest(
        text="Just posted this using the XDK Python SDK! 🐍✨"
    )
    
    try:
        # Send the request
        response = client.posts.create(body=request)
        
        # Handle success
        print("✅ Tweet posted successfully!")
        print(f"   Tweet ID: {response.data.id}")
        print(f"   Text: {response.data.text}")
        
    except Exception as e:
        # Handle errors
        print(f"❌ Error posting tweet: {e}")

if __name__ == "__main__":
    main()
Create a .env file in your project directory with your credentials:
X_ACCESS_TOKEN="your_access_token_here"

Advanced Examples

Post with Media

Create a tweet with attached images:
from xdk.posts.models import CreateRequest, CreateRequestMedia

# First, upload media (assuming you have media IDs)
request = CreateRequest(
    text="Check out this image! 📸",
    media=CreateRequestMedia(
        media_ids=["1234567890", "0987654321"]
    )
)

response = client.posts.create(body=request)
print(f"Posted tweet with media: {response.data.id}")

Reply to a Tweet

Post a reply to an existing tweet:
from xdk.posts.models import CreateRequest, CreateRequestReply

request = CreateRequest(
    text="@username Great post! Thanks for sharing.",
    reply=CreateRequestReply(
        in_reply_to_tweet_id="1234567890123456789"
    )
)

response = client.posts.create(body=request)
print(f"Posted reply: {response.data.id}")

Post with a Poll

Create a tweet with a poll:
from xdk.posts.models import CreateRequest, CreateRequestPoll

request = CreateRequest(
    text="What's your favorite Python feature?",
    poll=CreateRequestPoll(
        options=["Type hints", "List comprehensions", "Decorators", "f-strings"],
        duration_minutes=1440  # 24 hours
    )
)

response = client.posts.create(body=request)
print(f"Posted poll: {response.data.id}")

Quote Tweet

Quote an existing tweet:
request = CreateRequest(
    text="This is exactly what I was looking for! 💯",
    quote_tweet_id="1234567890123456789"
)

response = client.posts.create(body=request)
print(f"Posted quote tweet: {response.data.id}")

Reading Tweets

Get Tweet by ID

# Fetch a specific tweet
tweet = client.posts.get_by_id(
    id="1234567890123456789",
    tweet_fields=["created_at", "author_id", "public_metrics"]
)

print(f"Tweet: {tweet.data.text}")
print(f"Created: {tweet.data.created_at}")

Search Recent Tweets

# Search for tweets (automatically paginates)
for page in client.posts.search_recent(
    query="python programming",
    max_results=10
):
    for tweet in page.data or []:
        print(f"@{tweet.author_id}: {tweet.text}")

Get Multiple Tweets

# Fetch multiple tweets by ID
response = client.posts.get_by_ids(
    ids=["1234567890", "0987654321", "1111222233"],
    tweet_fields=["created_at", "public_metrics"]
)

for tweet in response.data or []:
    print(f"Tweet {tweet.id}: {tweet.text}")

Delete a Tweet

# Delete a tweet you own
response = client.posts.delete(id="1234567890123456789")

if response.data.get("deleted"):
    print("Tweet deleted successfully")

Error Handling

Always handle potential errors when making API requests:
import requests
from xdk.posts.models import CreateRequest

try:
    request = CreateRequest(text="My tweet")
    response = client.posts.create(body=request)
    print(f"Success: {response.data.id}")
    
except requests.HTTPError as e:
    print(f"HTTP Error: {e.response.status_code}")
    print(f"Details: {e.response.text}")
    
except ValueError as e:
    print(f"Validation Error: {e}")
    
except Exception as e:
    print(f"Unexpected error: {e}")

Common Response Fields

When you create a post, the response contains:
  • response.data.id - The unique ID of the created tweet
  • response.data.text - The text content of the tweet
  • response.errors - Any errors that occurred (if applicable)

Rate Limits

The X API has rate limits. For posting tweets:
  • User context: Limited number of tweets per 24 hours
  • App context: Different limits apply
Check the X API documentation for current rate limits.

Next Steps

Now that you’ve posted your first tweet, explore more features:

Authentication

Learn about OAuth flows and token management

API Reference

Explore all available endpoints and methods

Users API

Work with user profiles and relationships

Streaming

Set up real-time tweet streaming

Troubleshooting

If you get authentication errors:
  1. Verify your credentials are correct
  2. Check that your access token hasn’t expired
  3. Ensure your app has the correct permissions
  4. For OAuth1, verify all four credentials (API key, secret, token, token secret)
If you hit rate limits:
  1. Check the response headers for rate limit info
  2. Implement exponential backoff
  3. Consider upgrading your API access level
If your request is rejected:
  1. Check tweet text length (max 280 characters)
  2. Verify media IDs are valid
  3. Ensure poll options meet requirements (2-4 options)
  4. Check that referenced tweet IDs exist

Build docs developers (and LLMs) love