Skip to main content

Overview

The Client class is the main entry point for interacting with the X API. It handles authentication, session management, and provides access to all API endpoints through specialized sub-clients.

Client Initialization

The Client supports multiple authentication methods:

Bearer Token (App-Only Auth)

from xdk import Client

client = Client(
    bearer_token="your_bearer_token_here"
)

OAuth2 PKCE Flow

client = Client(
    client_id="your_client_id",
    client_secret="your_client_secret",
    redirect_uri="https://yourapp.com/callback",
    scope=["tweet.read", "users.read", "follows.read"]
)

OAuth2 with Access Token

client = Client(
    access_token="your_access_token"
)

OAuth2 with Token Dictionary

token = {
    "access_token": "your_access_token",
    "token_type": "bearer",
    "expires_in": 7200,
    "refresh_token": "your_refresh_token"
}

client = Client(
    client_id="your_client_id",
    token=token
)

OAuth 1.0a

from xdk import OAuth1

auth = OAuth1(
    consumer_key="your_consumer_key",
    consumer_secret="your_consumer_secret",
    access_token="your_access_token",
    access_token_secret="your_access_token_secret"
)

client = Client(auth=auth)

Client Signature

class Client:
    def __init__(
        self,
        base_url: str = "https://api.x.com",
        bearer_token: str = None,
        access_token: str = None,
        client_id: str = None,
        client_secret: str = None,
        redirect_uri: str = None,
        token: Dict[str, Any] = None,
        scope: Union[str, List[str]] = None,
        authorization_base_url: str = "https://x.com/i",
        auth: OAuth1 = None,
    )

Parameters

base_url
str
default:"https://api.x.com"
The base URL for the X API
bearer_token
str
Bearer token for app-only authentication
access_token
str
OAuth2 access token for user context (can be used directly as bearer token)
client_id
str
Client ID for OAuth2 PKCE flow
client_secret
str
Client secret for OAuth2
redirect_uri
str
Redirect URI for OAuth2 authorization
token
Dict[str, Any]
Existing OAuth2 token dictionary (if available). If provided, access_token will be extracted
scope
Union[str, List[str]]
Space-separated string or list of strings for OAuth2 authorization scopes
authorization_base_url
str
default:"https://x.com/i"
Base URL for OAuth2 authorization
auth
OAuth1
OAuth1 instance for OAuth1.0a authentication

Sub-Clients

The Client provides access to all API endpoints through specialized sub-clients:
client.posts          # Posts/Tweets operations
client.users          # User operations
client.lists          # List operations
client.direct_messages # DM operations
client.spaces         # Spaces operations
client.media          # Media upload
client.stream         # Filtered stream
client.connections    # Follows, blocks, mutes
client.trends         # Trending topics
client.communities    # Communities
client.webhooks       # Webhook management
# ... and more

OAuth2 PKCE Flow

For user authentication, use the OAuth2 PKCE flow:

Step 1: Get Authorization URL

client = Client(
    client_id="your_client_id",
    redirect_uri="https://yourapp.com/callback",
    scope=["tweet.read", "users.read"]
)

auth_url = client.get_authorization_url(state="random_state")
print(f"Visit this URL to authorize: {auth_url}")

Step 2: Exchange Authorization Code

# After user authorizes, you'll receive a callback with the code
code = "authorization_code_from_callback"

token = client.exchange_code(code)
print(f"Access token: {token['access_token']}")

Step 3: Use the Client

# The client is now authenticated
me = client.users.find_user_by_username("username")
print(me.data.name)

Token Management

Access Token Property

# Get current access token
current_token = client.access_token

# Set access token
client.access_token = "new_access_token"

Token Refresh

# Check if token is expired
if client.is_token_expired():
    # Refresh the token
    new_token = client.refresh_token()
    print(f"New access token: {new_token['access_token']}")

Token Property

# Get full token dictionary
token_dict = client.token
print(token_dict)
# {
#     "access_token": "...",
#     "token_type": "bearer",
#     "expires_in": 7200,
#     "refresh_token": "..."
# }

Session Management

The Client uses a requests.Session internally for connection pooling and header management:
# Session is automatically configured
client.session.headers
# {'User-Agent': 'xdk-python/0.9.0'}

# You can add custom headers
client.session.headers.update({
    "Custom-Header": "value"
})

Best Practices

Store Tokens Securely

Never hardcode tokens in your source code. Use environment variables or secure credential storage.

Handle Token Expiration

Check token expiration and refresh tokens before they expire to maintain uninterrupted access.

Use Appropriate Scopes

Request only the OAuth2 scopes your application needs to minimize security risks.

Reuse Client Instances

Create one Client instance and reuse it throughout your application for better connection pooling.

Build docs developers (and LLMs) love