### Execute API Examples Source: https://github.com/xdevplatform/samples/blob/main/README.md Commands to install dependencies and run search examples for various languages. ```bash # Python cd python && pip install -r requirements.txt python posts/search_recent.py # JavaScript cd javascript node posts/search_recent.js # Ruby cd ruby && bundle install ruby posts/search_recent.rb # Java cd java javac -cp ".:lib/*" posts/RecentSearchDemo.java java -cp ".:lib/*" RecentSearchDemo ``` -------------------------------- ### Install JavaScript (Node.js) Dependencies Source: https://github.com/xdevplatform/samples/blob/main/llms.txt Install the necessary Node.js packages for JavaScript examples, including 'needle', 'got', and 'oauth-1.0a'. These are used for making API requests and managing OAuth. ```bash npm install needle got oauth-1.0a ``` -------------------------------- ### Run Java Examples Source: https://github.com/xdevplatform/samples/blob/main/java/README.md Commands to execute the compiled Java classes. ```bash # Run a single example java -cp ".:lib/*" posts.SearchRecent # Or with package structure java -cp ".:lib/*" posts/RecentSearchDemo ``` -------------------------------- ### Install X API v2 dependencies Source: https://github.com/xdevplatform/samples/blob/main/python/README.md Install the required X Developer Kit for Python. ```bash pip install -r requirements.txt ``` -------------------------------- ### Install Dependencies Source: https://github.com/xdevplatform/samples/blob/main/ruby/README.md Install required Ruby gems using Bundler or manually via the command line. ```bash bundle install ``` ```bash gem install typhoeus gem install oauth # For OAuth 1.0a examples ``` -------------------------------- ### Install Ruby Dependencies Source: https://github.com/xdevplatform/samples/blob/main/llms.txt Install the required Ruby gems, 'typhoeus' and 'oauth', using the gem command. These are essential for making HTTP requests and handling OAuth in Ruby. ```bash gem install typhoeus oauth ``` -------------------------------- ### Compile Java Examples Source: https://github.com/xdevplatform/samples/blob/main/java/README.md Commands to compile individual Java files or the entire project directory. ```bash # Compile a single file javac -cp ".:lib/*" posts/SearchRecent.java # Or compile all files find . -name "*.java" -exec javac -cp ".:lib/*" {} \; ``` -------------------------------- ### Run API Example Source: https://github.com/xdevplatform/samples/blob/main/ruby/README.md Execute a specific Ruby script after ensuring environment variables are configured. ```bash # Make sure environment variables are set ruby posts/search_recent.rb ``` -------------------------------- ### Install Python Dependencies Source: https://github.com/xdevplatform/samples/blob/main/llms.txt Install the required Python libraries, 'requests' and 'requests-oauthlib', using pip. These libraries are necessary for making HTTP requests and handling OAuth authentication. ```bash pip install requests requests-oauthlib ``` -------------------------------- ### Verify Ruby Version Source: https://github.com/xdevplatform/samples/blob/main/ruby/README.md Check the installed version of Ruby to ensure compatibility. ```bash ruby --version ``` -------------------------------- ### Create a New Post Source: https://github.com/xdevplatform/samples/blob/main/javascript/README.md Example of creating a new post. Requires CLIENT_ID and CLIENT_SECRET for authentication. ```javascript // posts/create_post.js - Create a new post (requires CLIENT_ID, CLIENT_SECRET) ``` -------------------------------- ### Check Node.js Version Source: https://github.com/xdevplatform/samples/blob/main/javascript/README.md Verify that Node.js version 14 or higher is installed. ```bash node --version ``` -------------------------------- ### Verify Java Version Source: https://github.com/xdevplatform/samples/blob/main/java/README.md Check the installed Java version to ensure compatibility with the API requirements. ```bash java --version ``` -------------------------------- ### Set Environment Variables for Authentication Source: https://github.com/xdevplatform/samples/blob/main/llms.txt Before running examples, set the necessary environment variables for authentication. This includes BEARER_TOKEN for app-only authentication and CONSUMER_KEY/CONSUMER_SECRET for user context authentication. ```bash export BEARER_TOKEN='your_token' export CONSUMER_KEY='your_key' export CONSUMER_SECRET='your_secret' ``` -------------------------------- ### GET /2/spaces Source: https://context7.com/xdevplatform/samples/llms.txt Retrieves details for specific Spaces by their IDs. ```APIDOC ## GET https://api.x.com/2/spaces ### Description Look up Spaces by their IDs. ### Method GET ### Endpoint https://api.x.com/2/spaces ### Parameters #### Query Parameters - **ids** (array) - Required - List of Space IDs to look up - **space_fields** (array) - Optional - Fields to return for the space - **expansions** (array) - Optional - Related objects to expand ### Response #### Success Response (200) - **data** (array) - List of space objects #### Response Example { "data": [ { "id": "1DXxyRYNejbKM", "state": "live", "title": "Tech Talk", "participant_count": 150 } ] } ``` -------------------------------- ### Get Home Timeline Source: https://github.com/xdevplatform/samples/blob/main/javascript/README.md Retrieve the home timeline for the authenticated user. Requires CLIENT_ID and CLIENT_SECRET for user context authentication. ```javascript // users/timeline/get_home_timeline.js - Get home timeline (requires CLIENT_ID, CLIENT_SECRET) ``` -------------------------------- ### Create X List using Python Source: https://context7.com/xdevplatform/samples/llms.txt Use this snippet to create a new list on X. Ensure you have set the CLIENT_ID and CLIENT_SECRET environment variables. The script will guide you through the OAuth 2.0 authorization flow. ```python """ Endpoint: POST https://api.x.com/2/lists Authentication: OAuth 2.0 (User Context) Required env vars: CLIENT_ID, CLIENT_SECRET """ import os import json from xdk import Client from xdk.oauth2_auth import OAuth2PKCEAuth client_id = os.environ.get("CLIENT_ID") client_secret = os.environ.get("CLIENT_SECRET") redirect_uri = "https://example.com" scopes = ["tweet.read", "users.read", "list.read", "list.write", "offline.access"] payload = { "name": "My Tech List", "description": "Tech news and developers I follow", "private": False } def main(): auth = OAuth2PKCEAuth( client_id=client_id, client_secret=client_secret, redirect_uri=redirect_uri, scope=scopes ) auth_url = auth.get_authorization_url() print("Visit:", auth_url) callback_url = input("Paste callback URL: ") tokens = auth.fetch_token(authorization_response=callback_url) client = Client(access_token=tokens["access_token"]) response = client.lists.create(body=payload) print("Response code: 201") print(json.dumps(response.data, indent=4, sort_keys=True)) if __name__ == "__main__": main() # Expected output: # { # "data": { # "id": "1234567890123456789", # "name": "My Tech List" # } # } ``` -------------------------------- ### Delete a Post Source: https://github.com/xdevplatform/samples/blob/main/javascript/README.md Example of deleting a post. Requires CLIENT_ID and CLIENT_SECRET for authentication. ```javascript // posts/delete_post.js - Delete a post (requires CLIENT_ID, CLIENT_SECRET) ``` -------------------------------- ### Lookup X Spaces by IDs using Python Source: https://context7.com/xdevplatform/samples/llms.txt Retrieve details for multiple Spaces using their IDs. This example requires the BEARER_TOKEN environment variable for authentication and specifies which Space fields and expansions to include in the response. ```python """ Endpoint: GET https://api.x.com/2/spaces Authentication: Bearer Token (App-only) or OAuth (User Context) Required env vars: BEARER_TOKEN """ import os import json from xdk import Client bearer_token = os.environ.get("BEARER_TOKEN") client = Client(bearer_token=bearer_token) space_ids = ["1DXxyRYNejbKM", "1nAJELYEEPvGL"] def main(): response = client.spaces.get_by_ids( ids=space_ids, space_fields=["title", "created_at", "state", "participant_count"], expansions=["creator_id"] ) print(json.dumps(response.data, indent=4, sort_keys=True)) if __name__ == "__main__": main() # Expected output: # { # "data": [ # { # "id": "1DXxyRYNejbKM", # "state": "live", # "title": "Tech Talk", # "participant_count": 150 # } # ] # } ``` -------------------------------- ### GET /users/:id/timelines/reverse_chronological Source: https://context7.com/xdevplatform/samples/llms.txt Retrieves the home timeline for the authenticated user in reverse chronological order. ```APIDOC ## GET https://api.x.com/2/users/:id/timelines/reverse_chronological ### Description Retrieve the home timeline (reverse chronological) for the authenticated user. ### Method GET ### Endpoint https://api.x.com/2/users/:id/timelines/reverse_chronological ### Parameters #### Path Parameters - **id** (string) - Required - The user ID of the authenticated user. #### Query Parameters - **max_results** (integer) - Optional - The maximum number of results to return. - **tweet_fields** (array) - Optional - List of fields to include in the response (e.g., created_at, author_id). ``` -------------------------------- ### Get Home Timeline with Python Source: https://context7.com/xdevplatform/samples/llms.txt Retrieves the authenticated user's home timeline in reverse chronological order using OAuth 2.0. ```python """ Endpoint: GET https://api.x.com/2/users/:id/timelines/reverse_chronological Authentication: OAuth 2.0 (User Context) Required env vars: CLIENT_ID, CLIENT_SECRET """ import os import json from xdk import Client from xdk.oauth2_auth import OAuth2PKCEAuth client_id = os.environ.get("CLIENT_ID") client_secret = os.environ.get("CLIENT_SECRET") redirect_uri = "https://example.com" scopes = ["tweet.read", "users.read", "offline.access"] def main(): auth = OAuth2PKCEAuth( client_id=client_id, client_secret=client_secret, redirect_uri=redirect_uri, scope=scopes ) auth_url = auth.get_authorization_url() print("Visit:", auth_url) callback_url = input("Paste callback URL: ") tokens = auth.fetch_token(authorization_response=callback_url) client = Client(access_token=tokens["access_token"]) me_response = client.users.get_me() user_id = me_response.data["id"] all_posts = [] for page in client.users.get_timeline( user_id, max_results=100, tweet_fields=["created_at", "author_id"] ): page_data = getattr(page, 'data', []) or [] all_posts.extend(page_data) print(f"Fetched {len(page_data)} posts (total: {len(all_posts)})") print(f"\nTotal Posts: {len(all_posts)}") print(json.dumps({"data": all_posts[:5]}, indent=4, sort_keys=True)) if __name__ == "__main__": main() ``` -------------------------------- ### Get User's Bookmarks Source: https://github.com/xdevplatform/samples/blob/main/javascript/README.md Retrieve a list of posts that the user has bookmarked. Requires CLIENT_ID and CLIENT_SECRET for user context authentication. ```javascript // users/bookmark/get_bookmarks.js - Get user's bookmarks (requires CLIENT_ID, CLIENT_SECRET) ``` -------------------------------- ### Get User Followers with Pagination Source: https://context7.com/xdevplatform/samples/llms.txt Retrieve a list of users following a specified account, handling pagination automatically. Requires BEARER_TOKEN environment variable. ```python """ Endpoint: GET https://api.x.com/2/users/:id/followers Authentication: Bearer Token (App-only) or OAuth (User Context) Required env vars: BEARER_TOKEN """ import os import json from xdk import Client bearer_token = os.environ.get("BEARER_TOKEN") client = Client(bearer_token=bearer_token) user_id = "2244994945" # @XDevelopers def main(): all_users = [] for page in client.users.get_followers( user_id, max_results=100, user_fields=["created_at", "description"] ): page_data = getattr(page, 'data', []) or [] all_users.extend(page_data) print(f"Fetched {len(page_data)} users (total: {len(all_users)})") print(f"\nTotal Followers: {len(all_users)}") print(json.dumps({"data": all_users[:5]}, indent=4, sort_keys=True)) if __name__ == "__main__": main() # Expected output: # Fetched 100 users (total: 100) # Fetched 100 users (total: 200) # Total Followers: 200 ``` -------------------------------- ### GET /tweets/search/stream Source: https://context7.com/xdevplatform/samples/llms.txt Streams posts matching predefined filter rules in real-time. ```APIDOC ## GET https://api.x.com/2/tweets/search/stream ### Description Stream posts matching filter rules in real-time. Requires setting up rules before connecting. ### Method GET ### Endpoint https://api.x.com/2/tweets/search/stream ### Response #### Success Response (200) - **id** (string) - The ID of the post. - **text** (string) - The content of the post. - **author_id** (string) - The ID of the author. #### Response Example { "id": "1234567890123456789", "text": "Look at my cute dog! #puppylove", "author_id": "9876543210" } ``` -------------------------------- ### Get List Memberships Source: https://github.com/xdevplatform/samples/blob/main/javascript/README.md Retrieve lists that a user is a member of. No specific authentication mentioned, likely uses Bearer Token. ```javascript // users/lists/get_list_memberships.js - Get list memberships ``` -------------------------------- ### Stream Filtered Posts with Python Source: https://context7.com/xdevplatform/samples/llms.txt Connects to the real-time filtered stream using App-only Bearer Token authentication. Requires rule management before starting the stream. ```python """ Endpoint: GET https://api.x.com/2/tweets/search/stream Authentication: Bearer Token (App-only) Required env vars: BEARER_TOKEN """ import os import json from xdk import Client bearer_token = os.environ.get("BEARER_TOKEN") client = Client(bearer_token=bearer_token) def get_rules(): response = client.stream.get_rules() rules_data = getattr(response, 'data', None) if rules_data: print(json.dumps(rules_data, indent=4, sort_keys=True)) return rules_data def delete_all_rules(rules): if rules is None or not rules: return None ids = [rule["id"] for rule in rules] payload = {"delete": {"ids": ids}} response = client.stream.update_rules(body=payload) def set_rules(): sample_rules = [ {"value": "dog has:images", "tag": "dog pictures"}, {"value": "cat has:images -grumpy", "tag": "cat pictures"}, ] payload = {"add": sample_rules} response = client.stream.update_rules(body=payload) print(json.dumps(getattr(response, 'data', None), indent=4, sort_keys=True)) def get_stream(): try: for post in client.stream.posts(): post_data = getattr(post, 'data', None) if post_data: print(json.dumps(post_data, indent=4, sort_keys=True)) except Exception as e: print(f"Error streaming posts: {e}") raise def main(): rules = get_rules() delete_all_rules(rules) set_rules() get_stream() if __name__ == "__main__": main() # Expected output (streaming): # { # "id": "1234567890123456789", # "text": "Look at my cute dog! #puppylove", # "author_id": "9876543210" # } ``` -------------------------------- ### Get Blocked Users Source: https://github.com/xdevplatform/samples/blob/main/javascript/README.md Retrieve a list of users that a specific user has blocked. Requires CLIENT_ID and CLIENT_SECRET for user context authentication. ```javascript // users/block/get_blocking.js - Get users blocked by a user (requires CLIENT_ID, CLIENT_SECRET) ``` -------------------------------- ### Get Lists Followed by a User Source: https://github.com/xdevplatform/samples/blob/main/javascript/README.md Retrieve a list of lists that a specific user is following. No specific authentication mentioned, likely uses Bearer Token. ```javascript // users/lists/get_followed_lists.js - Get lists followed by a user ``` -------------------------------- ### Get Authenticated User (Me) Source: https://github.com/xdevplatform/samples/blob/main/javascript/README.md Retrieve information about the currently authenticated user. Requires CLIENT_ID and CLIENT_SECRET for OAuth 2.0 authentication. ```javascript // users/get_users_me.js - Get authenticated user (me) (requires CLIENT_ID, CLIENT_SECRET) ``` -------------------------------- ### Get Post Counts (Full Archive) Source: https://github.com/xdevplatform/samples/blob/main/javascript/README.md Retrieve post counts for the full archive. No specific authentication mentioned, likely uses Bearer Token. ```javascript // posts/get_post_counts_all.js - Get post counts (full archive) ``` -------------------------------- ### Get Users Who Liked a Post Source: https://github.com/xdevplatform/samples/blob/main/javascript/README.md Retrieve a list of users who have liked a specific post. Requires user context authentication (CLIENT_ID, CLIENT_SECRET). ```javascript // posts/get_liking_users.js - Get users who liked a post (requires CLIENT_ID, CLIENT_SECRET for user context) ``` -------------------------------- ### Get Quoted Posts Source: https://github.com/xdevplatform/samples/blob/main/javascript/README.md Retrieve posts that quote a specific post. No specific authentication mentioned, likely uses Bearer Token. ```javascript // posts/get_quoted_posts.js - Get posts that quote a post ``` -------------------------------- ### Get Users a User is Following (Paginated) Source: https://github.com/xdevplatform/samples/blob/main/javascript/README.md Retrieve a paginated list of users that a specific user is following. No specific authentication mentioned, likely uses Bearer Token. ```javascript // users/follow/get_following_paginated.js - Get users a user is following (paginated) ``` -------------------------------- ### Get User's Followers Source: https://github.com/xdevplatform/samples/blob/main/javascript/README.md Retrieve a list of users who are following a specific user. No specific authentication mentioned, likely uses Bearer Token. ```javascript // users/follow/get_followers.js - Get user's followers ``` -------------------------------- ### Get User Mentions Timeline Source: https://github.com/xdevplatform/samples/blob/main/javascript/README.md Retrieve a timeline of posts that mention the authenticated user. No specific authentication mentioned, likely uses Bearer Token. ```javascript // users/timeline/get_mentions.js - Get user mentions timeline ``` -------------------------------- ### Get Muted Users Source: https://github.com/xdevplatform/samples/blob/main/javascript/README.md Retrieve a list of users that a specific user has muted. Requires CLIENT_ID and CLIENT_SECRET for user context authentication. ```javascript // users/mute/get_muting.js - Get users muted by a user (requires CLIENT_ID, CLIENT_SECRET) ``` -------------------------------- ### Get Posts Liked by a User Source: https://github.com/xdevplatform/samples/blob/main/javascript/README.md Retrieve a list of posts that a specific user has liked. Requires CLIENT_ID and CLIENT_SECRET for user context authentication. ```javascript // users/like/get_liked_posts.js - Get posts liked by a user (requires CLIENT_ID, CLIENT_SECRET) ``` -------------------------------- ### Get Lists Owned by a User Source: https://github.com/xdevplatform/samples/blob/main/javascript/README.md Retrieve a list of lists that a specific user owns. No specific authentication mentioned, likely uses Bearer Token. ```javascript // users/lists/get_owned_lists.js - Get lists owned by a user ``` -------------------------------- ### Get Users Who Reposted a Post Source: https://github.com/xdevplatform/samples/blob/main/javascript/README.md Retrieve a list of users who have reposted a specific post. No specific authentication mentioned, likely uses Bearer Token. ```javascript // posts/get_reposted_by.js - Get users who reposted a post ``` -------------------------------- ### Get User's Posts Timeline Source: https://github.com/xdevplatform/samples/blob/main/javascript/README.md Retrieve a timeline of posts created by a specific user. No specific authentication mentioned, likely uses Bearer Token. ```javascript // users/timeline/get_posts.js - Get user's posts timeline ``` -------------------------------- ### Get User's Followers (Paginated) Source: https://github.com/xdevplatform/samples/blob/main/javascript/README.md Retrieve a paginated list of users who are following a specific user. No specific authentication mentioned, likely uses Bearer Token. ```javascript // users/follow/get_followers_paginated.js - Get user's followers (paginated) ``` -------------------------------- ### Get Post Counts (Recent) Source: https://github.com/xdevplatform/samples/blob/main/javascript/README.md Retrieve post counts for recent posts (last 7 days). No specific authentication mentioned, likely uses Bearer Token. ```javascript // posts/get_post_counts_recent.js - Get post counts (recent) ``` -------------------------------- ### Get User's Posts Timeline (Paginated) Source: https://github.com/xdevplatform/samples/blob/main/javascript/README.md Retrieve a paginated timeline of posts created by a specific user. No specific authentication mentioned, likely uses Bearer Token. ```javascript // users/timeline/get_posts_paginated.js - Get user's posts timeline (paginated) ``` -------------------------------- ### Run API Sample Source: https://github.com/xdevplatform/samples/blob/main/javascript/README.md Execute a JavaScript sample file using Node.js after ensuring environment variables are configured. ```bash # Make sure environment variables are set node posts/search_recent.js ``` -------------------------------- ### Repository Structure Overview Source: https://github.com/xdevplatform/samples/blob/main/README.md Displays the directory layout of the sample code repository. ```text ├── python/ # 65 Python examples ├── javascript/ # 59 JavaScript examples ├── ruby/ # 58 Ruby examples ├── java/ # 19 Java examples ├── r/ # 5 R examples ├── llms.txt # LLM-friendly documentation └── api-index.json # Machine-readable endpoint catalog ``` -------------------------------- ### Create Post with OAuth 2.0 PKCE in JavaScript Source: https://context7.com/xdevplatform/samples/llms.txt Uses the @xdevplatform/xdk package to authenticate via OAuth 2.0 PKCE and create a new post. Requires CLIENT_ID and CLIENT_SECRET environment variables. ```javascript /** * Endpoint: POST https://api.x.com/2/posts * Authentication: OAuth 2.0 (User Context) * Required env vars: CLIENT_ID, CLIENT_SECRET */ const { Client, OAuth2, generateCodeVerifier, generateCodeChallenge } = require('@xdevplatform/xdk'); const readline = require('readline').createInterface({ input: process.stdin, output: process.stdout }); const clientId = process.env.CLIENT_ID; const clientSecret = process.env.CLIENT_SECRET; const data = { text: "Hello world from JavaScript!" }; (async () => { try { const oauth2Config = { clientId: clientId, clientSecret: clientSecret, redirectUri: 'https://example.com', scope: ['tweet.read', 'users.read', 'tweet.write', 'offline.access'] }; const oauth2 = new OAuth2(oauth2Config); const state = 'example-state'; const codeVerifier = generateCodeVerifier(); const codeChallenge = await generateCodeChallenge(codeVerifier); oauth2.setPkceParameters(codeVerifier, codeChallenge); const authUrl = await oauth2.getAuthorizationUrl(state); console.log('Please go here and authorize:', authUrl); const redirectCallback = await new Promise(resolve => { readline.question('Paste the redirected callback URL: ', resolve); }); readline.close(); const urlParams = new URLSearchParams(new URL(redirectCallback).search); const code = urlParams.get('code'); const tokens = await oauth2.exchangeCode(code, codeVerifier); const client = new Client({ accessToken: tokens.access_token }); const response = await client.posts.create(data); console.dir(response, { depth: null }); } catch (e) { console.log(e); process.exit(-1); } process.exit(); })(); ``` -------------------------------- ### Create Bookmark with Python Source: https://context7.com/xdevplatform/samples/llms.txt Uses OAuth 2.0 PKCE flow to authenticate and bookmark a specific post for the authenticated user. ```python """ Endpoint: POST https://api.x.com/2/users/:id/bookmarks Authentication: OAuth 2.0 (User Context) Required env vars: CLIENT_ID, CLIENT_SECRET """ import os import json from xdk import Client from xdk.oauth2_auth import OAuth2PKCEAuth client_id = os.environ.get("CLIENT_ID") client_secret = os.environ.get("CLIENT_SECRET") redirect_uri = "https://example.com" scopes = ["tweet.read", "users.read", "bookmark.write", "offline.access"] post_id = "1234567890123456789" # Post to bookmark def main(): auth = OAuth2PKCEAuth( client_id=client_id, client_secret=client_secret, redirect_uri=redirect_uri, scope=scopes ) auth_url = auth.get_authorization_url() print("Visit:", auth_url) callback_url = input("Paste callback URL: ") tokens = auth.fetch_token(authorization_response=callback_url) client = Client(access_token=tokens["access_token"]) me_response = client.users.get_me() user_id = me_response.data["id"] payload = {"tweet_id": post_id} response = client.users.create_bookmark(user_id, body=payload) print(json.dumps(response.data, indent=4, sort_keys=True)) if __name__ == "__main__": main() # Expected output: # { # "data": { # "bookmarked": true # } # } ``` -------------------------------- ### Create Bookmark Source: https://github.com/xdevplatform/samples/blob/main/javascript/README.md Create a bookmark for a post. Requires CLIENT_ID and CLIENT_SECRET for user context authentication. ```javascript // users/bookmark/create_bookmark.js - Create a bookmark (requires CLIENT_ID, CLIENT_SECRET) ``` -------------------------------- ### Configure environment variables for X API v2 Source: https://github.com/xdevplatform/samples/blob/main/python/README.md Set authentication credentials for read-only or user-action operations. ```bash export BEARER_TOKEN='your_bearer_token' ``` ```bash export CLIENT_ID='your_client_id' export CLIENT_SECRET='your_client_secret' ``` -------------------------------- ### Upload Video Media with Python Source: https://context7.com/xdevplatform/samples/llms.txt Implements a chunked upload process for video files, followed by status polling and posting the media to X. ```python """ Endpoint: POST https://api.x.com/2/media/upload Authentication: OAuth 2.0 (User Context) Required env vars: CLIENT_ID, CLIENT_SECRET """ import os import time import requests from xdk.oauth2_auth import OAuth2PKCEAuth MEDIA_ENDPOINT_URL = 'https://api.x.com/2/media/upload' POST_TO_X_URL = 'https://api.x.com/2/tweets' VIDEO_FILENAME = 'video.mp4' client_id = os.environ.get("CLIENT_ID") client_secret = os.environ.get("CLIENT_SECRET") scopes = ["media.write", "users.read", "tweet.read", "tweet.write", "offline.access"] # Authenticate auth = OAuth2PKCEAuth( client_id=client_id, client_secret=client_secret, redirect_uri="https://example.com", scope=scopes ) auth_url = auth.get_authorization_url() print("Visit:", auth_url) callback_url = input("Paste callback URL: ") tokens = auth.fetch_token(authorization_response=callback_url) access_token = tokens["access_token"] headers = {"Authorization": f"Bearer {access_token}"} class VideoPost: def __init__(self, file_name): self.video_filename = file_name self.total_bytes = os.path.getsize(file_name) self.media_id = None def upload_init(self): data = { 'command': 'INIT', 'media_type': 'video/mp4', 'total_bytes': self.total_bytes, 'media_category': 'tweet_video' } req = requests.post(MEDIA_ENDPOINT_URL, params=data, headers=headers) self.media_id = req.json()['data']['id'] print(f'Media ID: {self.media_id}') def upload_append(self): segment_id = 0 with open(self.video_filename, 'rb') as f: while chunk := f.read(4 * 1024 * 1024): files = {'media': ('chunk', chunk, 'application/octet-stream')} data = {'command': 'APPEND', 'media_id': self.media_id, 'segment_index': segment_id} requests.post(MEDIA_ENDPOINT_URL, data=data, files=files, headers=headers) segment_id += 1 def upload_finalize(self): data = {'command': 'FINALIZE', 'media_id': self.media_id} req = requests.post(MEDIA_ENDPOINT_URL, params=data, headers=headers) processing_info = req.json()['data'].get('processing_info') while processing_info and processing_info['state'] not in ['succeeded', 'failed']: time.sleep(processing_info['check_after_secs']) status_req = requests.get(MEDIA_ENDPOINT_URL, params={'command': 'STATUS', 'media_id': self.media_id}, headers=headers) processing_info = status_req.json()['data'].get('processing_info') def post(self): payload = { 'text': 'Video uploaded via X API v2!', 'media': {'media_ids': [self.media_id]} } req = requests.post(POST_TO_X_URL, json=payload, headers=headers) print(req.json()) # Usage video = VideoPost(VIDEO_FILENAME) video.upload_init() video.upload_append() video.upload_finalize() video.post() ``` -------------------------------- ### Set Environment Variables Source: https://github.com/xdevplatform/samples/blob/main/ruby/README.md Configure authentication credentials as environment variables for API access. ```bash export BEARER_TOKEN='your_bearer_token' ``` ```bash export CLIENT_ID='your_client_id' export CLIENT_SECRET='your_client_secret' ``` ```bash export CONSUMER_KEY='your_consumer_key' export CONSUMER_SECRET='your_consumer_secret' ``` -------------------------------- ### Add Maven Dependencies Source: https://github.com/xdevplatform/samples/blob/main/java/README.md Include the necessary Apache HttpClient and Gson libraries in your project's pom.xml file. ```xml org.apache.httpcomponents httpclient 4.5.13 com.google.code.gson gson 2.9.1 ``` -------------------------------- ### Set User Action Authentication Source: https://github.com/xdevplatform/samples/blob/main/java/README.md Configure client credentials for user-specific actions like posting or liking. ```bash export CLIENT_ID='your_client_id' export CLIENT_SECRET='your_client_secret' ``` -------------------------------- ### Follow a List Source: https://github.com/xdevplatform/samples/blob/main/javascript/README.md Follow a specific list. Requires CLIENT_ID and CLIENT_SECRET for user context authentication. ```javascript // users/lists/follow_list.js - Follow a list (requires CLIENT_ID, CLIENT_SECRET) ``` -------------------------------- ### POST /2/lists Source: https://context7.com/xdevplatform/samples/llms.txt Creates a new list on the user's account. ```APIDOC ## POST https://api.x.com/2/lists ### Description Create a new list on X. ### Method POST ### Endpoint https://api.x.com/2/lists ### Request Body - **name** (string) - Required - The name of the list - **description** (string) - Optional - The description of the list - **private** (boolean) - Optional - Whether the list is private ### Request Example { "name": "My Tech List", "description": "Tech news and developers I follow", "private": false } ### Response #### Success Response (201) - **id** (string) - The ID of the created list - **name** (string) - The name of the created list #### Response Example { "data": { "id": "1234567890123456789", "name": "My Tech List" } } ``` -------------------------------- ### Look Up Users by Username (User Context) Source: https://github.com/xdevplatform/samples/blob/main/javascript/README.md Retrieve user information by their usernames with user context. Requires CLIENT_ID and CLIENT_SECRET for authentication. ```javascript // users/get_users_by_usernames_user_context.js - Look up users by username (user context) (requires CLIENT_ID, CLIENT_SECRET) ``` -------------------------------- ### Retrieve API Usage Statistics with Python Source: https://context7.com/xdevplatform/samples/llms.txt Fetches usage data for the last 7 days. Requires the BEARER_TOKEN environment variable to be set. ```python """ Endpoint: GET https://api.x.com/2/usage/tweets Authentication: Bearer Token (App-only) Required env vars: BEARER_TOKEN """ import os import json from xdk import Client bearer_token = os.environ.get("BEARER_TOKEN") client = Client(bearer_token=bearer_token) def main(): # Get usage statistics for tweets (default: last 7 days) response = client.usage.get(days=7) response_data = getattr(response, 'data', None) if response_data: print(json.dumps(response_data, indent=4, sort_keys=True)) else: print(json.dumps(response, indent=4, sort_keys=True)) if __name__ == "__main__": main() # Expected output: # { # "daily_project_usage": [ # {"date": "2024-01-15", "usage": {"tweet_cap": 500000, "tweets_read": 15234}}, # ... # ] # } ``` -------------------------------- ### Like a Post Source: https://context7.com/xdevplatform/samples/llms.txt Like a post on behalf of the authenticated user using OAuth 2.0 PKCE flow. Requires CLIENT_ID and CLIENT_SECRET environment variables. ```python """ Endpoint: POST https://api.x.com/2/users/:id/likes Authentication: OAuth 2.0 (User Context) Required env vars: CLIENT_ID, CLIENT_SECRET """ import os import json from xdk import Client from xdk.oauth2_auth import OAuth2PKCEAuth client_id = os.environ.get("CLIENT_ID") client_secret = os.environ.get("CLIENT_SECRET") redirect_uri = "https://example.com" scopes = ["tweet.read", "tweet.write", "users.read", "offline.access", "like.write"] post_id = "1234567890123456789" # Post to like def main(): auth = OAuth2PKCEAuth( client_id=client_id, client_secret=client_secret, redirect_uri=redirect_uri, scope=scopes ) auth_url = auth.get_authorization_url() print("Visit:", auth_url) callback_url = input("Paste callback URL: ") tokens = auth.fetch_token(authorization_response=callback_url) client = Client(access_token=tokens["access_token"]) # Get authenticated user's ID user_me = client.users.get_me() user_id = user_me.data["id"] # Like the post payload = {"tweet_id": post_id} response = client.users.like_post(user_id, body=payload) print(json.dumps(response.data, indent=4, sort_keys=True)) if __name__ == "__main__": main() # Expected output: # { # "data": { # "liked": true # } # } ``` -------------------------------- ### Create a New Post Source: https://context7.com/xdevplatform/samples/llms.txt Creates a new post on X. Requires OAuth 2.0 user authentication with write permissions. This involves obtaining an authorization URL, handling the callback, and exchanging a code for tokens. ```Python """ Endpoint: POST https://api.x.com/2/tweets Authentication: OAuth 2.0 (User Context) Required env vars: CLIENT_ID, CLIENT_SECRET """ import os import json from xdk import Client from xdk.oauth2_auth import OAuth2PKCEAuth client_id = os.environ.get("CLIENT_ID") client_secret = os.environ.get("CLIENT_SECRET") redirect_uri = "https://example.com" scopes = ["tweet.read", "tweet.write", "users.read", "offline.access"] payload = {"text": "Hello world!"} def main(): # Step 1: Create PKCE instance auth = OAuth2PKCEAuth( client_id=client_id, client_secret=client_secret, redirect_uri=redirect_uri, scope=scopes ) # Step 2: Get authorization URL auth_url = auth.get_authorization_url() print("Visit the following URL to authorize:") print(auth_url) # Step 3: Handle callback callback_url = input("Paste the full callback URL here: ") # Step 4: Exchange code for tokens tokens = auth.fetch_token(authorization_response=callback_url) access_token = tokens["access_token"] # Step 5: Create client and post client = Client(access_token=access_token) response = client.posts.create(body=payload) print("Response code: 201") print(json.dumps(response.data, indent=4, sort_keys=True)) if __name__ == "__main__": main() # Expected output: # { # "data": { # "id": "1234567890123456789", # "text": "Hello world!" # } # } ``` -------------------------------- ### Filtered Stream with Rules Source: https://github.com/xdevplatform/samples/blob/main/javascript/README.md Set up and manage a filtered stream of posts based on defined rules. No specific authentication mentioned, likely uses Bearer Token. ```javascript // streams/stream_posts_filtered.js - Filtered stream with rules ``` -------------------------------- ### Look Up Posts by ID (User Context) Source: https://github.com/xdevplatform/samples/blob/main/javascript/README.md Retrieve posts by their IDs with user context. Requires CLIENT_ID and CLIENT_SECRET for authentication. ```javascript // posts/get_posts_by_ids_user_context.js - Look up posts by ID (user context) (requires CLIENT_ID, CLIENT_SECRET) ``` -------------------------------- ### Lookup Users by Username Source: https://context7.com/xdevplatform/samples/llms.txt Retrieve profile information for multiple users by their usernames. Requires BEARER_TOKEN environment variable. ```python """ Endpoint: GET https://api.x.com/2/users/by Authentication: Bearer Token (App-only) or OAuth (User Context) Required env vars: BEARER_TOKEN """ import os import json from xdk import Client bearer_token = os.environ.get("BEARER_TOKEN") client = Client(bearer_token=bearer_token) usernames = ["XDevelopers", "API"] def main(): response = client.users.get_by_usernames( usernames=usernames, user_fields=["description", "created_at", "public_metrics"] ) response_data = getattr(response, 'data', None) if response_data: print(json.dumps(response_data, indent=4, sort_keys=True)) if __name__ == "__main__": main() # Expected output: # [ # { # "created_at": "2013-12-14T04:35:55.000Z", # "description": "The voice of the X Platform developer community", # "id": "2244994945", # "name": "X Developers", # "public_metrics": {"followers_count": 570000, "following_count": 2000, ...}, # "username": "XDevelopers" # }, # ... # ] ``` -------------------------------- ### Like a Post Source: https://github.com/xdevplatform/samples/blob/main/javascript/README.md Like a specific post. Requires CLIENT_ID and CLIENT_SECRET for user context authentication. ```javascript // users/like/like_post.js - Like a post (requires CLIENT_ID, CLIENT_SECRET) ``` -------------------------------- ### Create Compliance Job with Python Source: https://context7.com/xdevplatform/samples/llms.txt Initiates a batch compliance job for tweets or users. Modify the payload type to switch between tweet and user compliance. ```python """ Endpoint: POST https://api.x.com/2/compliance/jobs Authentication: Bearer Token (App-only) Required env vars: BEARER_TOKEN """ import os import json from xdk import Client bearer_token = os.environ.get("BEARER_TOKEN") client = Client(bearer_token=bearer_token) # For User Compliance Job, change type to "users" payload = {"type": "tweets", "name": "my_batch_compliance_job"} def main(): response = client.compliance.create_job(body=payload) print(json.dumps(response.data, indent=4, sort_keys=True)) if __name__ == "__main__": main() # Expected output: # { # "data": { # "id": "1234567890123456789", # "name": "my_batch_compliance_job", # "status": "created", # "type": "tweets", # "upload_url": "https://storage.googleapis.com/..." # } # } ``` -------------------------------- ### Pin a List Source: https://github.com/xdevplatform/samples/blob/main/javascript/README.md Pin a specific list. Requires CLIENT_ID and CLIENT_SECRET for user context authentication. ```javascript // users/lists/pin_list.js - Pin a list (requires CLIENT_ID, CLIENT_SECRET) ``` -------------------------------- ### Sampled Stream Source: https://github.com/xdevplatform/samples/blob/main/javascript/README.md Connect to a sampled stream of posts. No specific authentication mentioned, likely uses Bearer Token. ```javascript // streams/stream_posts_sample.js - Sampled stream ``` -------------------------------- ### Search Recent Posts with JavaScript Source: https://context7.com/xdevplatform/samples/llms.txt Performs a paginated search for recent posts using the PostPaginator. Requires the BEARER_TOKEN environment variable. ```javascript /** * Endpoint: GET https://api.x.com/2/posts/search/recent * Authentication: Bearer Token (App-only) * Required env vars: BEARER_TOKEN */ const { Client, PostPaginator } = require('@xdevplatform/xdk'); const bearerToken = process.env.BEARER_TOKEN; const client = new Client({ bearerToken: bearerToken }); const query = 'from:x -is:retweet'; const searchRecent = async () => { console.log("Searching recent posts..."); const searchResults = new PostPaginator( async (token) => { const res = await client.posts.searchRecent(query, { maxResults: 100, nextToken: token, tweetFields: ['author_id', 'created_at'] }); return { data: res.data ?? [], meta: res.meta, includes: res.includes, errors: res.errors }; } ); await searchResults.fetchNext(); while (!searchResults.done) { await searchResults.fetchNext(); } console.dir(searchResults.posts, { depth: null }); console.log(`Got ${searchResults.posts.length} posts for query: ${query}`); } searchRecent().catch(err => { console.error('Error:', err); process.exit(-1); }); ``` -------------------------------- ### Search Recent Posts with Pagination Source: https://context7.com/xdevplatform/samples/llms.txt Searches for posts from the last 7 days using a query string and automatically paginates to retrieve all matching results. Requires a Bearer Token for authentication. ```Python """ Endpoint: GET https://api.x.com/2/tweets/search/recent Authentication: Bearer Token (App-only) Required env vars: BEARER_TOKEN """ import os import json from xdk import Client bearer_token = os.environ.get("BEARER_TOKEN") client = Client(bearer_token=bearer_token) query = '(from:XDevelopers -is:retweet) OR #XDevelopers' def main(): # Search with automatic pagination all_posts = [] for page in client.posts.search_recent( query=query, max_results=100, # Per page tweet_fields=["author_id", "created_at"] ): page_data = getattr(page, 'data', []) or [] all_posts.extend(page_data) print(f"Fetched {len(page_data)} Posts (total: {len(all_posts)})") print(f"\nTotal Posts: {len(all_posts)}") print(json.dumps({"data": all_posts[:5]}, indent=4, sort_keys=True)) if __name__ == "__main__": main() # Expected output: # Fetched 100 Posts (total: 100) # Fetched 85 Posts (total: 185) # Total Posts: 185 # { # "data": [ # {"author_id": "2244994945", "created_at": "2024-01-15T...", "id": "...", "text": "..."}, # ... # ] # } ``` -------------------------------- ### Look Up Posts by ID (Bearer Token) Source: https://github.com/xdevplatform/samples/blob/main/javascript/README.md Retrieve posts by their IDs using a Bearer Token for authentication. Suitable for read-only operations. ```javascript // posts/get_posts_by_ids.js - Look up posts by ID (bearer token) ``` -------------------------------- ### Look Up Users by Username (Bearer Token) Source: https://github.com/xdevplatform/samples/blob/main/javascript/README.md Retrieve user information by their usernames using a Bearer Token for authentication. Suitable for read-only operations. ```javascript // users/get_users_by_usernames.js - Look up users by username (bearer token) ``` -------------------------------- ### Repost a Post Source: https://context7.com/xdevplatform/samples/llms.txt Repost a post on behalf of the authenticated user using OAuth 2.0 PKCE flow. Requires CLIENT_ID and CLIENT_SECRET environment variables. ```python """ Endpoint: POST https://api.x.com/2/users/:id/retweets Authentication: OAuth 2.0 (User Context) Required env vars: CLIENT_ID, CLIENT_SECRET """ import os import json from xdk import Client from xdk.oauth2_auth import OAuth2PKCEAuth client_id = os.environ.get("CLIENT_ID") client_secret = os.environ.get("CLIENT_SECRET") redirect_uri = "https://example.com" scopes = ["tweet.read", "tweet.write", "users.read", "offline.access"] post_id = "1234567890123456789" # Post to repost def main(): auth = OAuth2PKCEAuth( client_id=client_id, client_secret=client_secret, redirect_uri=redirect_uri, scope=scopes ) auth_url = auth.get_authorization_url() print("Visit:", auth_url) callback_url = input("Paste callback URL: ") tokens = auth.fetch_token(authorization_response=callback_url) client = Client(access_token=tokens["access_token"]) user_me = client.users.get_me() user_id = user_me.data["id"] payload = {"tweet_id": post_id} response = client.users.repost_post(user_id, body=payload) print(json.dumps(response.data, indent=4, sort_keys=True)) if __name__ == "__main__": main() # Expected output: # { # "data": { # "retweeted": true # } # } ``` -------------------------------- ### Set Read-Only Authentication Source: https://github.com/xdevplatform/samples/blob/main/java/README.md Configure the bearer token environment variable for read-only API operations. ```bash export BEARER_TOKEN='your_bearer_token' ``` -------------------------------- ### Send Direct Message on X using Python Source: https://context7.com/xdevplatform/samples/llms.txt Send a one-to-one direct message to a specified user. This script requires CLIENT_ID and CLIENT_SECRET environment variables and involves an OAuth 2.0 authorization flow. Replace '1234567890' with the target user's ID. ```python """ Endpoint: POST https://api.x.com/2/dm_conversations/with/:participant_id/messages Authentication: OAuth 2.0 (User Context) Required env vars: CLIENT_ID, CLIENT_SECRET """ import os import json from xdk import Client from xdk.oauth2_auth import OAuth2PKCEAuth client_id = os.environ.get("CLIENT_ID") client_secret = os.environ.get("CLIENT_SECRET") redirect_uri = "https://example.com" scopes = ["dm.read", "dm.write", "tweet.read", "users.read", "offline.access"] participant_id = "1234567890" # User ID to send DM to text_message = "Hi! This is a DM sent via the X API v2." def main(): auth = OAuth2PKCEAuth( client_id=client_id, client_secret=client_secret, redirect_uri=redirect_uri, scope=scopes ) auth_url = auth.get_authorization_url() print("Visit:", auth_url) callback_url = input("Paste callback URL: ") tokens = auth.fetch_token(authorization_response=callback_url) client = Client(access_token=tokens["access_token"]) payload = {"text": text_message} response = client.direct_messages.create_by_participant_id(participant_id, body=payload) print("Response code: 201") print(json.dumps(response.data, indent=4, sort_keys=True)) if __name__ == "__main__": main() # Expected output: # { # "data": { # "dm_conversation_id": "1234567890-0987654321", # "dm_event_id": "1234567890123456789" # } # } ```