Skip to content

Commit 9bd4a77

Browse files
committed
more cahnges
1 parent 157cb32 commit 9bd4a77

206 files changed

Lines changed: 15497 additions & 313 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

README.md

Lines changed: 49 additions & 92 deletions
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,16 @@
22

33
[![X API v2](https://img.shields.io/endpoint?url=https%3A%2F%2Ftwbadges.glitch.me%2Fbadges%2Fv2)](https://developer.x.com/en/docs/twitter-api)
44

5-
Working code samples for the **X (formerly Twitter) API v2** in Python, JavaScript, Ruby, and Java.
5+
Working code samples for the **X API v2** in Python, JavaScript, Ruby, Java, and R.
66

77
## 📁 Repository Structure
88

99
```
10-
├── python/ # Python examples (most complete)
11-
├── javascript/ # JavaScript (Node.js) examples
12-
├── ruby/ # Ruby examples
13-
├── java/ # Java examples
10+
├── python/ # 108 Python examples
11+
├── javascript/ # 70 JavaScript examples
12+
├── ruby/ # 58 Ruby examples
13+
├── java/ # 19 Java examples
14+
├── r/ # 5 R examples
1415
├── llms.txt # LLM-friendly documentation
1516
└── api-index.json # Machine-readable endpoint catalog
1617
```
@@ -19,110 +20,66 @@ Working code samples for the **X (formerly Twitter) API v2** in Python, JavaScri
1920

2021
### 1. Get API Credentials
2122

22-
Sign up at the [X Developer Portal](https://developer.x.com/en/portal/dashboard) and create a project/app.
23+
Sign up at the [X Developer Portal](https://developer.x.com/en/portal/dashboard).
2324

2425
### 2. Set Environment Variables
2526

2627
```bash
27-
# For app-only authentication (read-only endpoints)
2828
export BEARER_TOKEN='your_bearer_token'
29-
30-
# For user context authentication (actions on behalf of users)
3129
export CONSUMER_KEY='your_consumer_key'
3230
export CONSUMER_SECRET='your_consumer_secret'
3331
```
3432

35-
### 3. Choose Your Language
36-
37-
| Language | Setup | Run Example |
38-
|----------|-------|-------------|
39-
| **Python** | `pip install -r python/requirements.txt` | `python python/posts/search_recent.py` |
40-
| **JavaScript** | `cd javascript && npm install` | `node javascript/posts/search_recent.js` |
41-
| **Ruby** | `gem install typhoeus` | `ruby ruby/posts/search_recent.rb` |
42-
| **Java** | Add dependencies (see java/README.md) | `javac && java SearchRecent` |
43-
44-
## 📚 Available Examples
45-
46-
### Posts (formerly Tweets)
47-
48-
| Operation | Python | JavaScript | Ruby | Java |
49-
|-----------|--------|------------|------|------|
50-
| Create Post ||| | |
51-
| Delete Post ||| | |
52-
| Lookup Posts |||| |
53-
| Search Recent |||||
54-
| Search Full Archive || | | |
55-
| Post Counts || | | |
56-
| Quote Posts || | | |
57-
| Repost || | | |
58-
| Like/Unlike || | | |
59-
60-
### Users
61-
62-
| Operation | Python | JavaScript | Ruby | Java |
63-
|-----------|--------|------------|------|------|
64-
| Lookup Users |||||
65-
| Get Me || | | |
66-
| Followers |||| |
67-
| Following || | | |
68-
| Block/Unblock || | | |
69-
| Mute/Unmute || | | |
70-
71-
### Timelines
72-
73-
| Operation | Python | JavaScript | Ruby |
74-
|-----------|--------|------------|------|
75-
| User Posts ||||
76-
| User Mentions || | |
77-
| Home Timeline || | |
78-
79-
### Streams
80-
81-
| Operation | Python | JavaScript |
82-
|-----------|--------|------------|
83-
| Filtered Stream |||
84-
| Sampled Stream || |
85-
86-
### Other
87-
88-
| Category | Python | JavaScript | Ruby |
89-
|----------|--------|------------|------|
90-
| Bookmarks || | |
91-
| Spaces ||| |
92-
| Lists ||||
93-
| Direct Messages || | |
94-
| Media Upload || | |
95-
| Compliance || | |
96-
| Usage Stats || | |
97-
98-
## 🔐 Authentication Types
99-
100-
| Type | Use Case | Required Env Vars |
101-
|------|----------|-------------------|
102-
| **Bearer Token** | Read-only endpoints (search, lookup) | `BEARER_TOKEN` |
103-
| **OAuth 1.0a** | User actions (post, like, follow) | `CONSUMER_KEY`, `CONSUMER_SECRET` |
104-
| **OAuth 2.0 PKCE** | Newer endpoints (bookmarks) | OAuth flow required |
33+
### 3. Run an Example
10534

106-
## 🔗 Resources
35+
```bash
36+
# Python
37+
cd python && pip install -r requirements.txt
38+
python posts/recent_search.py
10739

108-
- [X API Documentation](https://developer.x.com/en/docs/twitter-api)
109-
- [Developer Portal](https://developer.x.com/en/portal/dashboard)
110-
- [API Reference Index](https://developer.x.com/en/docs/api-reference-index)
111-
- [Postman Collection](https://t.co/twitter-api-postman)
40+
# JavaScript
41+
cd javascript && npm install
42+
node posts/recent_search.js
43+
44+
# Ruby
45+
cd ruby && bundle install
46+
ruby posts/recent_search.rb
47+
```
48+
49+
## 📚 Examples by Category
50+
51+
| Category | Python | JavaScript | Ruby | Java | R |
52+
|----------|--------|------------|------|------|---|
53+
| Posts (search, create, delete, likes, retweets) ||||||
54+
| Users (lookup, followers, blocks, mutes) ||||||
55+
| Timelines (user, mentions, home) ||||| |
56+
| Streams (filtered, sampled) ||||| |
57+
| Lists (lookup, manage, members) |||| | |
58+
| Spaces (lookup, search) ||||| |
59+
| Bookmarks |||| | |
60+
| Direct Messages || | | | |
61+
| Media Upload || | | | |
62+
| Compliance ||| || |
63+
| Usage ||| || |
64+
65+
## 🔐 Authentication
66+
67+
| Type | Use Case | Env Vars |
68+
|------|----------|----------|
69+
| Bearer Token | Read-only (search, lookup) | `BEARER_TOKEN` |
70+
| OAuth 1.0a | User actions (post, like) | `CONSUMER_KEY`, `CONSUMER_SECRET` |
71+
| OAuth 2.0 PKCE | Bookmarks, newer endpoints | OAuth flow |
11272

11373
## 🤖 For LLMs
11474

115-
This repository includes:
116-
- **`llms.txt`** - Comprehensive context file for AI assistants
75+
- **`llms.txt`** - Context file for AI assistants
11776
- **`api-index.json`** - Machine-readable endpoint catalog
11877

119-
## 🤝 Contributing
78+
## 🔗 Resources
12079

121-
We welcome contributions! Please:
122-
1. Follow existing code patterns
123-
2. Include proper documentation headers
124-
3. Test your examples before submitting
80+
- [X API Documentation](https://developer.x.com/en/docs/twitter-api)
81+
- [Developer Portal](https://developer.x.com/en/portal/dashboard)
12582

12683
## 📄 License
12784

128-
Apache 2.0 - See [LICENSE](LICENSE)
85+
Apache 2.0
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
import java.io.IOException;
2+
import java.net.URISyntaxException;
3+
import java.util.ArrayList;
4+
5+
import org.apache.http.HttpEntity;
6+
import org.apache.http.HttpResponse;
7+
import org.apache.http.NameValuePair;
8+
import org.apache.http.client.HttpClient;
9+
import org.apache.http.client.config.CookieSpecs;
10+
import org.apache.http.client.config.RequestConfig;
11+
import org.apache.http.client.methods.HttpGet;
12+
import org.apache.http.client.utils.URIBuilder;
13+
import org.apache.http.impl.client.HttpClients;
14+
import org.apache.http.message.BasicNameValuePair;
15+
import org.apache.http.util.EntityUtils;
16+
17+
/*
18+
* Sample code to demonstrate the use of the Full archive search endpoint
19+
* */
20+
public class FullArchiveSearchDemo {
21+
22+
// To set your enviornment variables in your terminal run the following line:
23+
// export 'BEARER_TOKEN'='<your_bearer_token>'
24+
25+
public static void main(String args[]) throws IOException, URISyntaxException {
26+
String bearerToken = System.getenv("BEARER_TOKEN");
27+
if (null != bearerToken) {
28+
//Replace the search term with a term of your choice
29+
String response = search("from:TwitterDev OR from:SnowBotDev OR from:DailyNASA", bearerToken);
30+
System.out.println(response);
31+
} else {
32+
System.out.println("There was a problem getting your bearer token. Please make sure you set the BEARER_TOKEN environment variable");
33+
}
34+
}
35+
36+
/*
37+
* This method calls the full-archive search endpoint with a the search term passed to it as a query parameter
38+
* */
39+
private static String search(String searchString, String bearerToken) throws IOException, URISyntaxException {
40+
String searchResponse = null;
41+
42+
HttpClient httpClient = HttpClients.custom()
43+
.setDefaultRequestConfig(RequestConfig.custom()
44+
.setCookieSpec(CookieSpecs.STANDARD).build())
45+
.build();
46+
47+
URIBuilder uriBuilder = new URIBuilder("https://api.x.com/2/tweets/search/all");
48+
ArrayList<NameValuePair> queryParameters;
49+
queryParameters = new ArrayList<>();
50+
queryParameters.add(new BasicNameValuePair("query", searchString));
51+
uriBuilder.addParameters(queryParameters);
52+
53+
HttpGet httpGet = new HttpGet(uriBuilder.build());
54+
httpGet.setHeader("Authorization", String.format("Bearer %s", bearerToken));
55+
httpGet.setHeader("Content-Type", "application/json");
56+
57+
HttpResponse response = httpClient.execute(httpGet);
58+
HttpEntity entity = response.getEntity();
59+
if (null != entity) {
60+
searchResponse = EntityUtils.toString(entity, "UTF-8");
61+
}
62+
return searchResponse;
63+
}
64+
65+
}
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
import java.io.IOException;
2+
import java.net.URISyntaxException;
3+
import java.util.ArrayList;
4+
5+
import org.apache.http.HttpEntity;
6+
import org.apache.http.HttpResponse;
7+
import org.apache.http.NameValuePair;
8+
import org.apache.http.client.HttpClient;
9+
import org.apache.http.client.config.CookieSpecs;
10+
import org.apache.http.client.config.RequestConfig;
11+
import org.apache.http.client.methods.HttpGet;
12+
import org.apache.http.client.utils.URIBuilder;
13+
import org.apache.http.impl.client.HttpClients;
14+
import org.apache.http.message.BasicNameValuePair;
15+
import org.apache.http.util.EntityUtils;
16+
17+
/*
18+
* Sample code to demonstrate the use of the Full-archive Tweet counts endpoint
19+
* */
20+
public class FullArchiveTweetCountsDemo {
21+
22+
// To set your enviornment variables in your terminal run the following line:
23+
// export 'BEARER_TOKEN'='<your_bearer_token>'
24+
25+
public static void main(String args[]) throws IOException, URISyntaxException {
26+
String bearerToken = System.getenv("BEARER_TOKEN");
27+
if (null != bearerToken) {
28+
//Replace the search term with a term of your choice
29+
String response = getTweetCounts("from:TwitterDev", bearerToken);
30+
System.out.println(response);
31+
} else {
32+
System.out.println("There was a problem getting your bearer token. Please make sure you set the BEARER_TOKEN environment variable");
33+
}
34+
}
35+
36+
/*
37+
* This method calls the full-archive Tweet counts endpoint with a the search term passed to it as a query parameter
38+
* */
39+
private static String getTweetCounts(String searchString, String bearerToken) throws IOException, URISyntaxException {
40+
String searchResponse = null;
41+
42+
HttpClient httpClient = HttpClients.custom()
43+
.setDefaultRequestConfig(RequestConfig.custom()
44+
.setCookieSpec(CookieSpecs.STANDARD).build())
45+
.build();
46+
47+
URIBuilder uriBuilder = new URIBuilder("https://api.x.com/2/tweets/counts/all");
48+
ArrayList<NameValuePair> queryParameters;
49+
queryParameters = new ArrayList<>();
50+
queryParameters.add(new BasicNameValuePair("query", searchString));
51+
queryParameters.add(new BasicNameValuePair("granularity", "day"));
52+
queryParameters.add(new BasicNameValuePair("start_time", "2021-01-01T00:00:00Z"));
53+
uriBuilder.addParameters(queryParameters);
54+
55+
HttpGet httpGet = new HttpGet(uriBuilder.build());
56+
httpGet.setHeader("Authorization", String.format("Bearer %s", bearerToken));
57+
httpGet.setHeader("Content-Type", "application/json");
58+
59+
HttpResponse response = httpClient.execute(httpGet);
60+
HttpEntity entity = response.getEntity();
61+
if (null != entity) {
62+
searchResponse = EntityUtils.toString(entity, "UTF-8");
63+
}
64+
return searchResponse;
65+
}
66+
67+
}

java/posts/QuoteTweetsDemo.java

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
import org.apache.http.HttpEntity;
2+
import org.apache.http.HttpResponse;
3+
import org.apache.http.NameValuePair;
4+
import org.apache.http.client.HttpClient;
5+
import org.apache.http.client.config.CookieSpecs;
6+
import org.apache.http.client.config.RequestConfig;
7+
import org.apache.http.client.methods.HttpGet;
8+
import org.apache.http.client.utils.URIBuilder;
9+
import org.apache.http.impl.client.HttpClients;
10+
import org.apache.http.message.BasicNameValuePair;
11+
import org.apache.http.util.EntityUtils;
12+
13+
import java.io.IOException;
14+
import java.net.URISyntaxException;
15+
import java.util.ArrayList;
16+
17+
/*
18+
* Sample code to demonstrate the use of the v2 Quote Tweets endpoint
19+
* */
20+
public class QuoteTweetsDemo {
21+
22+
// To set your environment variables in your terminal run the following line:
23+
// export 'BEARER_TOKEN'='<your_bearer_token>'
24+
25+
public static void main(String args[]) throws IOException, URISyntaxException {
26+
final String bearerToken = System.getenv("BEARER_TOKEN");
27+
if (null != bearerToken) {
28+
//Replace with Tweet ID below
29+
String response = getTweets(20, bearerToken);
30+
System.out.println(response);
31+
} else {
32+
System.out.println("There was a problem getting your bearer token. Please make sure you set the BEARER_TOKEN environment variable");
33+
}
34+
}
35+
36+
/*
37+
* This method calls the v2 Quote Tweets endpoint by Tweet ID
38+
* */
39+
private static String getTweets(int tweetId, String bearerToken) throws IOException, URISyntaxException {
40+
String tweetResponse = null;
41+
42+
HttpClient httpClient = HttpClients.custom()
43+
.setDefaultRequestConfig(RequestConfig.custom()
44+
.setCookieSpec(CookieSpecs.STANDARD).build())
45+
.build();
46+
47+
URIBuilder uriBuilder = new URIBuilder(String.format("https://api.x.com/2/tweets/%s/quote_tweets", tweetId));
48+
ArrayList<NameValuePair> queryParameters;
49+
queryParameters = new ArrayList<>();
50+
queryParameters.add(new BasicNameValuePair("tweet.fields", "created_at"));
51+
uriBuilder.addParameters(queryParameters);
52+
53+
HttpGet httpGet = new HttpGet(uriBuilder.build());
54+
httpGet.setHeader("Authorization", String.format("Bearer %s", bearerToken));
55+
httpGet.setHeader("Content-Type", "application/json");
56+
57+
HttpResponse response = httpClient.execute(httpGet);
58+
HttpEntity entity = response.getEntity();
59+
if (null != entity) {
60+
tweetResponse = EntityUtils.toString(entity, "UTF-8");
61+
}
62+
return tweetResponse;
63+
}
64+
}

0 commit comments

Comments
 (0)