How to Access Twitter V2 API with Java

  • Post last modified:August 7, 2022
  • Reading time:4 mins read

Introduction

  • In this article we build Java client to access twitter follower count of any twitter user.
  • Twitter API v2 provides comprehensive list of endpoints to access necessary information , such as user info, follower info , tweets info etc.
  • Here are the details : https://developer.twitter.com/apitools

Get Access Key

  • In order to create token to access API key , we need to goto https://developer.twitter.com/en
  • Signup and create APP inside developer portal.
  • Once we create app , we get free access for 500k tweets per month .
  • We can generate bearer token from developer portal. We will need this token to access twitter API.

Building Client

  • We will use Java 11 http client to access the twitter api. For authentication / authorization we will pass the bearer token to the client.
  • Below are the steps that we will take.
    Step 1: Create Request object
    Step 2: Create Http Client
    Step 3: Execute the request and receive response
    Step 4: Read response as JSON element and print it.

Http Request Object

  • We will create HttpRequest object and setup request header with bearer token and add URI.
  • Twitter API needs twitter userID to be passed, i could not find a way to use twitter id from twitter so i used this website to get userId by providing userName. 
  • We also need to pass parameters such created_at, entries and public_metrics. We can choose whichever parameters we want by checking from the list mentioned .
HttpRequest request = HttpRequest
         .newBuilder()
         .header("Authorization", "Bearer "+BEARER_TOKEN)
         .uri(new URI("https://api.twitter.com/2/users/2521950180?user.fields=created_at,entities,public_metrics"))
         .GET()
         .build();
  • As Next step we will create HttpClient object and execute our request.
HttpClient httpClient = HttpClient.newBuilder().build();
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
  • Our response is String type which contains json object , hence we need to parse string as Json using some library.
  • I used ObjectMapper and read response body as JsonNode. Once we get the jsonNode object we can check the status code and full response by printing it.
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readValue(response.body(), JsonNode.class);

System.out.println(response.statusCode());
System.out.println(jsonNode.toString());
  • Now we read the response as Json object , it’s pretty easy for us to traverse the node and get the followers count as shown below.
  • Now we can verify the result by printing it on console.

Putting together all the code

  • Here is the entire client code.
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class TwitterClient {

    private static String BEARER_TOKEN = ""; // add bearer token here

    public static void main(String[] args) throws URISyntaxException, IOException, InterruptedException {

        HttpRequest request = HttpRequest
                .newBuilder()
                .header("Authorization", "Bearer "+BEARER_TOKEN)
                .uri(new URI("https://api.twitter.com/2/users/2521950180?user.fields=created_at,entities,public_metrics"))
                .GET()
                .build();

        HttpClient httpClient = HttpClient.newBuilder().build();
        HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());

        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode jsonNode = objectMapper.readValue(response.body(), JsonNode.class);

        System.out.println(response.statusCode());
        System.out.println(jsonNode.toString());

        String followersCount = jsonNode
                .get("data")
                .get("public_metrics")
                .get("followers_count")
                .asText();

        System.out.println("Followers Count : "+ followersCount);
    }
}

Dependency

  • In order to use JsonObject and ObjectMapper we need Jackson-databind dependency.

Conclusion

  • In this blog we used twitter api v2 to get access to user info. We used it to get the total followers count.
  • But we can use it to get various information at free of cost. Twitter provides access to 500k tweets / month for free.

Follow me on LinkedIn

Leave a Reply