Sample code for the X API v2 endpoints
X API v2 Sample Code
Working code samples for the X API v2 in Python, JavaScript, Ruby, Java, and R.
๐ Repository Structure
โโโ 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
๐ Quick Start
1. Get API Credentials
Sign up at the X Developer Portal.
2. Set Environment Variables
For read-only operations (search, lookup):
export BEARERTOKEN='yourbearer_token'
For user actions (post, like, repost, bookmark, etc.):
export CLIENTID='yourclient_id' export CLIENTSECRET='yourclient_secret'
For OAuth 1.0a (legacy endpoints):
export C export C
3. Run an Example
# 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
๐ Examples by Category
| Category | Python | JavaScript | Ruby | Java | R | |----------|--------|------------|------|------|---| | Posts (search, create, delete, likes, reposts) | โ | โ | โ | โ | โ | | Users (lookup, followers, following, blocks, mutes) | โ | โ | โ | โ | โ | | Timelines (user, mentions, home) | โ | โ | โ | โ | | | Streams (filtered, sampled) | โ | โ | โ | โ | | | Lists (lookup, manage, members, follow) | โ | โ | โ | | | | Spaces (lookup, search) | โ | โ | โ | โ | | | Bookmarks | โ | โ | โ | | | | Direct Messages | โ | | | | | | Media Upload | โ | | | | | | Compliance | โ | โ | | | | | Usage | โ | โ | | โ | |
๐ Authentication
| Type | Use Case | Env Vars | |------|----------|----------| | Bearer Token | Read-only (search, lookup) | BEARER_TOKEN | | OAuth 2.0 PKCE | User actions (post, like, repost, bookmark, mute, etc.) | CLIENTID, CLIENTSECRET | | OAuth 1.0a | Legacy endpoints (if applicable) | CONSUMERKEY, CONSUMERSECRET |
๐ค For LLMs
llms.txt- Context file for AI assistantsapi-index.json- Machine-readable endpoint catalog
๐ Resources
๐ License
Apache 2.0