Twitter REST api - access tweets by hashtab
Here is code I wrote to access tweets from a given user using the Twitter REST service :
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Arrays;
import java.util.List;
public class GetTweets {
private static final String BEARER_TOKEN = "test";
public static String getTweetsByUsername(final String username) {
final ObjectMapper objectMapper = new ObjectMapper();
try {
URL url = new URL("https://api.twitter.com/2/users/by/username/" + username);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("Authorization", "Bearer " + BEARER_TOKEN);
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer content = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
in.close();
final DataResponse dataResponse = objectMapper.readValue(content.toString(), DataResponse.class);
url = new URL("https://api.twitter.com/2/users/" + dataResponse.getUserDetails().getId() + "/tweets");
con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("Authorization", "Bearer " + BEARER_TOKEN);
in = new BufferedReader(new InputStreamReader(con.getInputStream()));
content = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
in.close();
return content.toString();
} catch (IOException e) {
e.printStackTrace();
}
return "None";
}
public static void main(String argsp[]) throws IOException {
List<String> users = Arrays.asList("test1" , "test2");
users.forEach(x -> {
System.out.println(GetTweets.getTweetsByUsername(x));
});
}
}
This behaves as expected I'm unsure how to find the tweets for a given hashtag.
For example, If I use :
List<String> users = Arrays.asList("#test1");
I receive exception :
java.io.FileNotFoundException: https://api.twitter.com/2/users/by/username/#test1
What is the endpoint path to access tweets by hashtag ? I've tried https://api.twitter.com/2/users/by/hashtag/#test1
but this does not exist.
There is a similar question here Twitter REST API: tweet extraction but this refers to earlier version of api.
Solution 1:
Search tweets doc
Search query syntax
I have no access to Twitter API but the doc says it should work:
https://api.twitter.com/2/tweets/search/recent?query=#test
Solution 2:
Taking the answer provided by @Egor, and enhancing it to include your other requirement, to find Tweets from a particular user with a hashtag, you can use the from:
syntax in your query, combined with the hashtag itself.
https://api.twitter.com/2/tweets/search/recent?query=#test1%20from:user1