Read Tweets from a User's Timeline Using v2 API
This example shows you how to read Tweets from a user's timeline using Data Pipeline's TwitterTimelineTweetsReader. TwitterTimelineTweetsReader
uses Twitter v2 API to obtain records from Twitter.
In this demo code you are going to use OAuth 2.0 Bearer Token as an authentication standard. Bearer Token allows you to make API requests on behalf of your Twitter developer App. If you are making an API call on behalf of a Twitter user, you can use OAuth 1.0a as an authentication standard by specifying Access Token and Secret.
Java Code listing
package com.northconcepts.datapipeline.examples.twitter2; import com.northconcepts.datapipeline.core.StreamWriter; import com.northconcepts.datapipeline.job.Job; import com.northconcepts.datapipeline.twitter2.TwitterTimelineTweetsReader; public class ReadTweetsFromAUsersTimelineUsingV2 { private static final String API_KEY = "YOUR_API_KEY"; private static final String API_SECRET = "YOUR_API_SECRET"; private static final String BEARER_TOKEN = "YOUR_BEARER_TOKEN"; public static void main(String[] args) { TwitterTimelineTweetsReader reader = new TwitterTimelineTweetsReader(API_KEY, API_SECRET, BEARER_TOKEN, "TwitterDev"); reader.setMaxResults(100); Job.run(reader, new StreamWriter(System.out)); } }
Code Walkthrough
- First, parameters which are going to be used to connect to Twitter v2 API are specified.
TwitterTimelineTweetsReader
is created to read Tweets published by a Twitter account with a usernameTwitterDev
.reader.setMaxResults(100)
sets the maximum number of records that will be obtained by the endpoint to 100.- Data are transferred from
TwitterTimelineTweetsReader
to the console via Job.run() method. See how to compile and run data pipeline jobs.
TwitterTimelineTweetsReader
Obtains records of Tweets, Retweets, replies, and Quote Tweets published by a specific Twitter account. It extends TwitterTimelineReader class and it's constructor takes API_Key
, API_Secrete
, Brearer_Token
(alternatively you can use Access_Token
and Access_Secrete
instead of Brearer_Token
) and a username
of the Twitter account you are trying obtain Tweets from.
Console output
Obtained records will printed on the console.