diff --git a/Usage Tweets/UsageTweetsDemo.java b/Usage Tweets/UsageTweetsDemo.java new file mode 100644 index 0000000..38f588f --- /dev/null +++ b/Usage Tweets/UsageTweetsDemo.java @@ -0,0 +1,58 @@ +import org.apache.http.HttpEntity; +import org.apache.http.HttpResponse; +import org.apache.http.NameValuePair; +import org.apache.http.client.HttpClient; +import org.apache.http.client.config.CookieSpecs; +import org.apache.http.client.config.RequestConfig; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.utils.URIBuilder; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.message.BasicNameValuePair; +import org.apache.http.util.EntityUtils; + +import java.io.IOException; +import java.net.URISyntaxException; +import java.util.ArrayList; + +/* + * Sample code to demonstrate the use of the v2 Usage Tweets endpoint + * */ +public class UsageTweetsDemo { + + // To set your enviornment variables in your terminal run the following line: + // export 'BEARER_TOKEN'='' + + public static void main(String args[]) throws IOException, URISyntaxException { + String bearerToken = System.getenv("BEARER_TOKEN"); + if (null != bearerToken) { + String response = getUsageTweets(bearerToken); + System.out.println(response); + } else { + System.out.println("There was a problem getting you bearer token. Please make sure you set the BEARER_TOKEN environment variable"); + } + } + + /* + * This method calls the v2 Usage Tweets endpoint + * */ + private static String getUsageTweets(String bearerToken) throws IOException, URISyntaxException { + String usageTweetsResponse = null; + + HttpClient httpClient = HttpClients.custom() + .setDefaultRequestConfig(RequestConfig.custom() + .setCookieSpec(CookieSpecs.STANDARD).build()) + .build(); + + URIBuilder uriBuilder = new URIBuilder("https://api.twitter.com/2/usage/tweets"); + HttpGet httpGet = new HttpGet(uriBuilder.build()); + httpGet.setHeader("Authorization", String.format("Bearer %s", bearerToken)); + httpGet.setHeader("Content-Type", "application/json"); + + HttpResponse response = httpClient.execute(httpGet); + HttpEntity entity = response.getEntity(); + if (null != entity) { + usageTweetsResponse = EntityUtils.toString(entity, "UTF-8"); + } + return usageTweetsResponse; + } +} \ No newline at end of file diff --git a/Usage Tweets/get_usage_tweets.js b/Usage Tweets/get_usage_tweets.js new file mode 100644 index 0000000..53df3be --- /dev/null +++ b/Usage Tweets/get_usage_tweets.js @@ -0,0 +1,44 @@ +// Get Tweets Usage +// https://developer.twitter.com/en/docs/twitter-api/usage/tweets + +const needle = require('needle'); + +// The code below sets the bearer token from your environment variables +// To set environment variables on macOS or Linux, run the export command below from the terminal: +// export BEARER_TOKEN='YOUR-TOKEN' +const token = process.env.BEARER_TOKEN; + +const endpointURL = "https://api.twitter.com/2/usage/tweets"; + +async function getRequest() { + + // this is the HTTP header that adds bearer token authentication + const res = await needle('get', endpointURL, { + headers: { + "User-Agent": "v2UsageTweetsJS", + "authorization": `Bearer ${token}` + } + }) + + if (res.body) { + return res.body; + } else { + throw new Error('Unsuccessful request'); + } +} + +(async () => { + + try { + // Make request + const response = await getRequest(); + console.dir(response, { + depth: null + }); + + } catch (e) { + console.log(e); + process.exit(-1); + } + process.exit(); +})(); diff --git a/Usage Tweets/get_usage_tweets.py b/Usage Tweets/get_usage_tweets.py new file mode 100644 index 0000000..e2842aa --- /dev/null +++ b/Usage Tweets/get_usage_tweets.py @@ -0,0 +1,38 @@ +import requests +import os +import json + +# To set your enviornment variables in your terminal run the following line: +# export 'BEARER_TOKEN'='' +bearer_token = os.environ.get("BEARER_TOKEN") + +def bearer_oauth(r): + """ + Method required by bearer token authentication. + """ + + r.headers["Authorization"] = f"Bearer {bearer_token}" + r.headers["User-Agent"] = "v2UsageTweetsPython" + return r + + +def connect_to_endpoint(url): + response = requests.request("GET", url, auth=bearer_oauth) + print(response.status_code) + if response.status_code != 200: + raise Exception( + "Request returned an error: {} {}".format( + response.status_code, response.text + ) + ) + return response.json() + + +def main(): + url = "https://api.twitter.com/2/usage/tweets" + json_response = connect_to_endpoint(url) + print(json.dumps(json_response, indent=4, sort_keys=True)) + + +if __name__ == "__main__": + main() diff --git a/Usage Tweets/get_usage_tweets.rb b/Usage Tweets/get_usage_tweets.rb new file mode 100644 index 0000000..6bd93bb --- /dev/null +++ b/Usage Tweets/get_usage_tweets.rb @@ -0,0 +1,29 @@ +# This script uses your bearer token to authenticate and retrieve the Usage + +require 'json' +require 'typhoeus' + +# The code below sets the bearer token from your environment variables +# To set environment variables on Mac OS X, run the export command below from the terminal: +# export BEARER_TOKEN='YOUR-TOKEN' +bearer_token = ENV["BEARER_TOKEN"] + +usage_tweets_url = "https://api.twitter.com/2/usage/tweets" + +def usage_tweets(url, bearer_token) + options = { + method: 'get', + headers: { + "User-Agent": "v2UsageTweetsRuby", + "Authorization": "Bearer #{bearer_token}" + } + } + + request = Typhoeus::Request.new(url, options) + response = request.run + + return response +end + +response = usage_tweets(usage_tweets_url, bearer_token) +puts response.code, JSON.pretty_generate(JSON.parse(response.body))