Skip to content

Commit 77f58d0

Browse files
authored
Merge pull request #64 from twitterdev/list-lookup-sample
added list lookup samples
2 parents a2d880d + 7dd1c67 commit 77f58d0

24 files changed

+1289
-0
lines changed
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
import requests
2+
import os
3+
import json
4+
5+
# To set your enviornment variables in your terminal run the following line:
6+
# export 'BEARER_TOKEN'='<your_bearer_token>'
7+
bearer_token = os.environ.get("BEARER_TOKEN")
8+
9+
10+
def create_url():
11+
# Tweet fields are adjustable.
12+
# Options include:
13+
# attachments, author_id, context_annotations,
14+
# conversation_id, created_at, entities, geo, id,
15+
# in_reply_to_user_id, lang, non_public_metrics, organic_metrics,
16+
# possibly_sensitive, promoted_metrics, public_metrics, referenced_tweets,
17+
# source, text, and withheld
18+
tweet_fields = "tweet.fields=lang,author_id"
19+
# Be sure to replace list-id with any List ID
20+
id = "list-id"
21+
url = "https://api.twitter.com/2/lists/{}/tweets".format(id)
22+
return url, tweet_fields
23+
24+
25+
def bearer_oauth(r):
26+
"""
27+
Method required by bearer token authentication.
28+
"""
29+
30+
r.headers["Authorization"] = f"Bearer {bearer_token}"
31+
r.headers["User-Agent"] = "v2ListTweetsLookupPython"
32+
return r
33+
34+
35+
def connect_to_endpoint(url, tweet_fields):
36+
response = requests.request(
37+
"GET", url, auth=bearer_oauth, params=tweet_fields)
38+
print(response.status_code)
39+
if response.status_code != 200:
40+
raise Exception(
41+
"Request returned an error: {} {}".format(
42+
response.status_code, response.text
43+
)
44+
)
45+
return response.json()
46+
47+
48+
def main():
49+
url, tweet_fields = create_url()
50+
json_response = connect_to_endpoint(url, tweet_fields)
51+
print(json.dumps(json_response, indent=4, sort_keys=True))
52+
53+
54+
if __name__ == "__main__":
55+
main()
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
# This script uses your bearer token to authenticate and retrieve the specified Tweet objects (by List ID)
2+
3+
require 'json'
4+
require 'typhoeus'
5+
6+
# The code below sets the bearer token from your environment variables
7+
# To set environment variables on Mac OS X, run the export command below from the terminal:
8+
# export BEARER_TOKEN='YOUR-TOKEN'
9+
bearer_token = ENV["BEARER_TOKEN"]
10+
11+
# Be sure to replace list-id with any List ID
12+
id = "list-id"
13+
url = "https://api.twitter.com/2/lists/#{id}/tweets"
14+
15+
16+
params = {
17+
# Tweet fields are adjustable.
18+
# Options include:
19+
# attachments, author_id, context_annotations,
20+
# conversation_id, created_at, entities, geo, id,
21+
# in_reply_to_user_id, lang, non_public_metrics, organic_metrics,
22+
# possibly_sensitive, promoted_metrics, public_metrics, referenced_tweets,
23+
# source, text, and withheld
24+
"tweet.fields": "lang,author_id",
25+
}
26+
27+
def list_tweets(url, bearer_token, params)
28+
options = {
29+
method: 'get',
30+
headers: {
31+
"User-Agent": "v2ListTweetsLookupRuby",
32+
"Authorization": "Bearer #{bearer_token}"
33+
},
34+
params: params
35+
}
36+
37+
request = Typhoeus::Request.new(url, options)
38+
response = request.run
39+
40+
return response
41+
end
42+
43+
response = list_tweets(url, bearer_token, params)
44+
puts response.code, JSON.pretty_generate(JSON.parse(response.body))
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
const needle = require("needle");
2+
// The code below sets the bearer token from your environment variables
3+
// To set environment variables on macOS or Linux, run the export command below from the terminal:
4+
// export BEARER_TOKEN='YOUR-TOKEN'
5+
6+
const token = process.env.BEARER_TOKEN;
7+
const id = "list-id";
8+
9+
const endpointURL = `https://api.twitter.com/2/lists/${id}/tweets`;
10+
11+
async function getRequest() {
12+
// These are the parameters for the API request
13+
// by default, only the Tweet ID and text are returned
14+
const params = {
15+
"tweet.fields": "lang,author_id", // Edit optional query parameters here
16+
expansions: "author_id", // expansions is used to include the user object
17+
"user.fields": "created_at", // Edit optional query parameters here
18+
};
19+
20+
// this is the HTTP header that adds bearer token authentication
21+
const res = await needle("get", endpointURL, params, {
22+
headers: {
23+
"User-Agent": "v2ListTweetsLookupJS",
24+
authorization: `Bearer ${token}`,
25+
},
26+
});
27+
28+
if (res.body) {
29+
return res.body;
30+
} else {
31+
throw new Error("Unsuccessful request");
32+
}
33+
}
34+
35+
(async () => {
36+
try {
37+
// Make request
38+
const response = await getRequest();
39+
console.dir(response, {
40+
depth: null,
41+
});
42+
} catch (e) {
43+
console.log(e);
44+
process.exit(-1);
45+
}
46+
process.exit();
47+
})();
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
const needle = require("needle");
2+
// The code below sets the bearer token from your environment variables
3+
// To set environment variables on macOS or Linux, run the export command below from the terminal:
4+
// export BEARER_TOKEN='YOUR-TOKEN'
5+
6+
const token = process.env.BEARER_TOKEN;
7+
const id = "list-id";
8+
9+
const endpointURL = `https://api.twitter.com/2/lists/${id}/followers`;
10+
11+
async function getRequest() {
12+
// These are the parameters for the API request
13+
// by default, only the User ID and name are returned
14+
const params = {
15+
"user.fields": "pinned_tweet_id,created_at", // Edit optional query parameters here
16+
expansions: "pinned_tweet_id", // expansions is used to include the Tweet object
17+
"tweet.fields": "created_at", // Edit optional query parameters here
18+
};
19+
20+
// this is the HTTP header that adds bearer token authentication
21+
const res = await needle("get", endpointURL, params, {
22+
headers: {
23+
"User-Agent": "v2ListFollowersLookupJS",
24+
authorization: `Bearer ${token}`,
25+
},
26+
});
27+
28+
if (res.body) {
29+
return res.body;
30+
} else {
31+
throw new Error("Unsuccessful request");
32+
}
33+
}
34+
35+
(async () => {
36+
try {
37+
// Make request
38+
const response = await getRequest();
39+
console.dir(response, {
40+
depth: null,
41+
});
42+
} catch (e) {
43+
console.log(e);
44+
process.exit(-1);
45+
}
46+
process.exit();
47+
})();
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
import requests
2+
import os
3+
import json
4+
5+
# To set your enviornment variables in your terminal run the following line:
6+
# export 'BEARER_TOKEN'='<your_bearer_token>'
7+
bearer_token = os.environ.get("BEARER_TOKEN")
8+
9+
10+
def create_url():
11+
# User fields are adjustable, options include:
12+
# created_at, description, entities, id, location, name,
13+
# pinned_tweet_id, profile_image_url, protected,
14+
# public_metrics, url, username, verified, and withheld
15+
user_fields = "user.fields=created_at,description,verified"
16+
# You can replace list-id with the List ID you wish to find followers of.
17+
id = "list-id"
18+
url = "https://api.twitter.com/2/lists/{}/followers".format(id)
19+
return url, user_fields
20+
21+
22+
def bearer_oauth(r):
23+
"""
24+
Method required by bearer token authentication.
25+
"""
26+
27+
r.headers["Authorization"] = f"Bearer {bearer_token}"
28+
r.headers["User-Agent"] = "v2ListFollowersLookupPython"
29+
return r
30+
31+
32+
def connect_to_endpoint(url, user_fields):
33+
response = requests.request("GET", url, auth=bearer_oauth, params=user_fields)
34+
print(response.status_code)
35+
if response.status_code != 200:
36+
raise Exception(
37+
"Request returned an error: {} {}".format(
38+
response.status_code, response.text
39+
)
40+
)
41+
return response.json()
42+
43+
44+
def main():
45+
url, user_fields = create_url()
46+
json_response = connect_to_endpoint(url, user_fields)
47+
print(json.dumps(json_response, indent=4, sort_keys=True))
48+
49+
50+
if __name__ == "__main__":
51+
main()
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
# This script uses your bearer token to authenticate and retrieve followers of a List specified by List ID
2+
3+
require 'json'
4+
require 'typhoeus'
5+
6+
# The code below sets the bearer token from your environment variables
7+
# To set environment variables on Mac OS X, run the export command below from the terminal:
8+
# export BEARER_TOKEN='YOUR-TOKEN'
9+
bearer_token = ENV["BEARER_TOKEN"]
10+
11+
# Be sure to replace list-id with any List ID
12+
id = "list-id"
13+
url = "https://api.twitter.com/2/lists/#{id}/followers"
14+
15+
16+
params = {
17+
# User fields are adjustable, options include:
18+
# created_at, description, entities, id, location, name,
19+
# pinned_tweet_id, profile_image_url, protected,
20+
# public_metrics, url, username, verified, and withheld
21+
"user.fields": "created_at,verified",
22+
}
23+
24+
def lists(url, bearer_token, params)
25+
options = {
26+
method: 'get',
27+
headers: {
28+
"User-Agent": "v2ListFollowersLookupRuby",
29+
"Authorization": "Bearer #{bearer_token}"
30+
},
31+
params: params
32+
}
33+
34+
request = Typhoeus::Request.new(url, options)
35+
response = request.run
36+
37+
return response
38+
end
39+
40+
response = lists(url, bearer_token, params)
41+
puts response.code, JSON.pretty_generate(JSON.parse(response.body))
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
const needle = require("needle");
2+
// The code below sets the bearer token from your environment variables
3+
// To set environment variables on macOS or Linux, run the export command below from the terminal:
4+
// export BEARER_TOKEN='YOUR-TOKEN'
5+
6+
const token = process.env.BEARER_TOKEN;
7+
const id = "user-id";
8+
9+
const endpointURL = `https://api.twitter.com/2/users/${id}/followed_lists`;
10+
11+
async function getRequest() {
12+
// These are the parameters for the API request
13+
// by default, only the List ID and name are returned
14+
const params = {
15+
"list.fields": "owner_id", // Edit optional query parameters here
16+
expansions: "owner_id", // expansions is used to include the user object
17+
"user.fields": "created_at,verified", // Edit optional query parameters here
18+
};
19+
20+
// this is the HTTP header that adds bearer token authentication
21+
const res = await needle("get", endpointURL, params, {
22+
headers: {
23+
"User-Agent": "v2userListMembershipsJS",
24+
authorization: `Bearer ${token}`,
25+
"x-des-apiservices": "staging1",
26+
},
27+
});
28+
29+
if (res.body) {
30+
return res.body;
31+
} else {
32+
throw new Error("Unsuccessful request");
33+
}
34+
}
35+
36+
(async () => {
37+
try {
38+
// Make request
39+
const response = await getRequest();
40+
console.dir(response, {
41+
depth: null,
42+
});
43+
} catch (e) {
44+
console.log(e);
45+
process.exit(-1);
46+
}
47+
process.exit();
48+
})();
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
import requests
2+
import os
3+
import json
4+
5+
# To set your enviornment variables in your terminal run the following line:
6+
# export 'BEARER_TOKEN'='<your_bearer_token>'
7+
bearer_token = os.environ.get("BEARER_TOKEN")
8+
9+
10+
def create_url():
11+
# List fields are adjustable, options include:
12+
# created_at, description, owner_id,
13+
# private, follower_count, member_count,
14+
list_fields = "list.fields=created_at,follower_count"
15+
# You can replace the user-id with any valid User ID you wish to find what Lists they are following.
16+
id = "user-id"
17+
url = "https://api.twitter.com/2/users/{}/followed_lists".format(id)
18+
return url, list_fields
19+
20+
21+
def bearer_oauth(r):
22+
"""
23+
Method required by bearer token authentication.
24+
"""
25+
26+
r.headers["Authorization"] = f"Bearer {bearer_token}"
27+
r.headers["User-Agent"] = "v2userListMembershipsPython"
28+
return r
29+
30+
31+
def connect_to_endpoint(url, list_fields):
32+
response = requests.request("GET", url, auth=bearer_oauth, params=list_fields)
33+
print(response.status_code)
34+
if response.status_code != 200:
35+
raise Exception(
36+
"Request returned an error: {} {}".format(
37+
response.status_code, response.text
38+
)
39+
)
40+
return response.json()
41+
42+
43+
def main():
44+
url, list_fields = create_url()
45+
json_response = connect_to_endpoint(url, list_fields)
46+
print(json.dumps(json_response, indent=4, sort_keys=True))
47+
48+
49+
if __name__ == "__main__":
50+
main()

0 commit comments

Comments
 (0)