Skip to content

Commit 47cb8c5

Browse files
committed
Add code samples for Usage Tweets
1 parent 0d15871 commit 47cb8c5

File tree

4 files changed

+169
-0
lines changed

4 files changed

+169
-0
lines changed

Usage Tweets/UsageTweetsDemo.java

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
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 Usage Tweets endpoint
19+
* */
20+
public class UsageTweetsDemo {
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+
String response = getUsageTweets(bearerToken);
29+
System.out.println(response);
30+
} else {
31+
System.out.println("There was a problem getting you bearer token. Please make sure you set the BEARER_TOKEN environment variable");
32+
}
33+
}
34+
35+
/*
36+
* This method calls the v2 Usage Tweets endpoint
37+
* */
38+
private static String getUsageTweets(String bearerToken) throws IOException, URISyntaxException {
39+
String usageTweetsResponse = null;
40+
41+
HttpClient httpClient = HttpClients.custom()
42+
.setDefaultRequestConfig(RequestConfig.custom()
43+
.setCookieSpec(CookieSpecs.STANDARD).build())
44+
.build();
45+
46+
URIBuilder uriBuilder = new URIBuilder("https://api.twitter.com/2/usage/tweets");
47+
HttpGet httpGet = new HttpGet(uriBuilder.build());
48+
httpGet.setHeader("Authorization", String.format("Bearer %s", bearerToken));
49+
httpGet.setHeader("Content-Type", "application/json");
50+
51+
HttpResponse response = httpClient.execute(httpGet);
52+
HttpEntity entity = response.getEntity();
53+
if (null != entity) {
54+
usageTweetsResponse = EntityUtils.toString(entity, "UTF-8");
55+
}
56+
return usageTweetsResponse;
57+
}
58+
}

Usage Tweets/get_usage_tweets.js

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
// Get Tweets Usage
2+
// https://developer.twitter.com/en/docs/twitter-api/usage/tweets
3+
4+
const needle = require('needle');
5+
6+
// The code below sets the bearer token from your environment variables
7+
// To set environment variables on macOS or Linux, run the export command below from the terminal:
8+
// export BEARER_TOKEN='YOUR-TOKEN'
9+
const token = process.env.BEARER_TOKEN;
10+
11+
const endpointURL = "https://api.twitter.com/2/usage/tweets";
12+
13+
async function getRequest() {
14+
15+
// this is the HTTP header that adds bearer token authentication
16+
const res = await needle('get', endpointURL, {
17+
headers: {
18+
"User-Agent": "v2UsageTweetsJS",
19+
"authorization": `Bearer ${token}`
20+
}
21+
})
22+
23+
if (res.body) {
24+
return res.body;
25+
} else {
26+
throw new Error('Unsuccessful request');
27+
}
28+
}
29+
30+
(async () => {
31+
32+
try {
33+
// Make request
34+
const response = await getRequest();
35+
console.dir(response, {
36+
depth: null
37+
});
38+
39+
} catch (e) {
40+
console.log(e);
41+
process.exit(-1);
42+
}
43+
process.exit();
44+
})();

Usage Tweets/get_usage_tweets.py

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
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+
def bearer_oauth(r):
10+
"""
11+
Method required by bearer token authentication.
12+
"""
13+
14+
r.headers["Authorization"] = f"Bearer {bearer_token}"
15+
r.headers["User-Agent"] = "v2UsageTweetsPython"
16+
return r
17+
18+
19+
def connect_to_endpoint(url):
20+
response = requests.request("GET", url, auth=bearer_oauth)
21+
print(response.status_code)
22+
if response.status_code != 200:
23+
raise Exception(
24+
"Request returned an error: {} {}".format(
25+
response.status_code, response.text
26+
)
27+
)
28+
return response.json()
29+
30+
31+
def main():
32+
url = "https://api.twitter.com/2/usage/tweets"
33+
json_response = connect_to_endpoint(url)
34+
print(json.dumps(json_response, indent=4, sort_keys=True))
35+
36+
37+
if __name__ == "__main__":
38+
main()

Usage Tweets/get_usage_tweets.rb

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
# This script uses your bearer token to authenticate and retrieve the Usage
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+
usage_tweets_url = "https://api.twitter.com/2/usage/tweets"
12+
13+
def usage_tweets(url, bearer_token)
14+
options = {
15+
method: 'get',
16+
headers: {
17+
"User-Agent": "v2UsageTweetsRuby",
18+
"Authorization": "Bearer #{bearer_token}"
19+
}
20+
}
21+
22+
request = Typhoeus::Request.new(url, options)
23+
response = request.run
24+
25+
return response
26+
end
27+
28+
response = usage_tweets(usage_tweets_url, bearer_token)
29+
puts response.code, JSON.pretty_generate(JSON.parse(response.body))

0 commit comments

Comments
 (0)