Home

Awesome

Twitter API Client Library for Java.

Note: This SDK is in beta and is not ready for production

You can find examples of using the SDK under the examples/ directory

Note: Only Twitter API V2 is supported

Twitter API v2 available endpoints

For more information, please visit https://developer.twitter.com/

Table of contents

Requirements

Building the API client library requires:

  1. Java 1.8+
  2. Maven (3.8.3+)/Gradle (7.2+)

Installation

To install the API client library to your local Maven repository, simply execute:

mvn clean install

To deploy it to a remote Maven repository instead, configure the settings of the repository and execute:

mvn clean deploy

Refer to the OSSRH Guide for more information.

Maven users

Add this dependency to your project's POM:

<dependency>
  <groupId>com.twitter</groupId>
  <artifactId>twitter-api-java-sdk</artifactId>
  <version>2.0.3</version>
</dependency>

Gradle users

Add this dependency to your project's build file:

repositories {
mavenCentral()     // Needed if the 'twitter-api-java-sdk' jar has been published to maven central.
mavenLocal()       // Needed if the 'twitter-api-java-sdk' jar has been published to the local maven repo.
}

dependencies {
implementation "com.twitter:twitter-api-java-sdk:2.0.3"
}

Others

At first generate the JAR by executing:

mvn clean package

Then manually install the following JARs:

Twitter Credentials

Twitter APIs support three types of authentications:

TWITTER_OAUTH2_CLIENT_ID

TWITTER_OAUTH2_CLIENT_SECRET

TWITTER_OAUTH2_ACCESS_TOKEN

TWITTER_OAUTH2_REFRESH_TOKEN

TWITTER_OAUTH2_IS_AUTO_REFRESH_TOKEN - default value is false

TWITTER_BEARER_TOKEN

You can use the following objects in order to set the credentials: TwitterCredentialsOAuth2 & TwitterCredentialsBearer.


TwitterApi apiInstance = new TwitterApi(new TwitterCredentialsOAuth2(
      System.getenv("TWITTER_OAUTH2_CLIENT_ID"),
      System.getenv("TWITTER_OAUTH2_CLIENT_SECRET"),
      System.getenv("TWITTER_OAUTH2_ACCESS_TOKEN"),
      System.getenv("TWITTER_OAUTH2_REFRESH_TOKEN")));

Check the security tag of the required APIs in https://api.twitter.com/2/openapi.json in order to use the right credential object.

Getting Started

Please follow the installation instruction and execute the following Java code:


import java.util.HashSet;
import java.util.Set;
import com.twitter.clientlib.TwitterCredentialsOAuth2;
import com.twitter.clientlib.ApiException;
import com.twitter.clientlib.api.TwitterApi;
import com.twitter.clientlib.model.*;

public class TwitterApiExample {

  public static void main(String[] args) {
    /**
     * Set the credentials for the required APIs.
     * The Java SDK supports TwitterCredentialsOAuth2 & TwitterCredentialsBearer.
     * Check the 'security' tag of the required APIs in https://api.twitter.com/2/openapi.json in order
     * to use the right credential object.
     */
    TwitterApi apiInstance = new TwitterApi(new TwitterCredentialsOAuth2(
          System.getenv("TWITTER_OAUTH2_CLIENT_ID"),
          System.getenv("TWITTER_OAUTH2_CLIENT_SECRET"),
          System.getenv("TWITTER_OAUTH2_ACCESS_TOKEN"),
          System.getenv("TWITTER_OAUTH2_REFRESH_TOKEN")));

    Set<String> tweetFields = new HashSet<>();
    tweetFields.add("author_id");
    tweetFields.add("id");
    tweetFields.add("created_at");

    try {
     // findTweetById
     Get2TweetsIdResponse result = apiInstance.tweets().findTweetById("20")
       .tweetFields(tweetFields)
       .execute();
     if(result.getErrors() != null && result.getErrors().size() > 0) {
       System.out.println("Error:");

       result.getErrors().forEach(e -> {
         System.out.println(e.toString());
         if (e instanceof ResourceUnauthorizedProblem) {
           System.out.println(((ResourceUnauthorizedProblem) e).getTitle() + " " + ((ResourceUnauthorizedProblem) e).getDetail());
         }
       });
     } else {
       System.out.println("findTweetById - Tweet Text: " + result.toString());
     }
    } catch (ApiException e) {
      System.err.println("Status code: " + e.getCode());
      System.err.println("Reason: " + e.getResponseBody());
      System.err.println("Response headers: " + e.getResponseHeaders());
      e.printStackTrace();
    }
  }
}


Authentication

The Twitter API has multiple authentication methods that support different endpoints. To see what method an endpoint needs go here.

This library has support for OAuth 2.0, use TwitterOAuth20Service in order to get the OAuth 2.0 services. You can see various examples on how to use the authentication in examples/

Auto Refresh Token

By default the OAuth 2.0 access token should be maintained and refreshed by the user.

In order to change it to be automatically refreshed, set the TwitterCredentialsOAuth2.isOAuth2AutoRefreshToken to be true.

You can implement the callback ApiClientCallback.onAfterRefreshToken() in order to maintain the refreshed access token.

Check this example of implementing ApiClientCallback

Rate limits retry mechanism

Everyday many thousands of developers make requests to the Twitter developer platform. To help manage the sheer volume of these requests, limits are placed on the number of requests that can be made. These limits help us provide the reliable and scalable API that our developer community relies on.

Each of our APIs use rate limits in different ways. To learn more about these differences between platforms, please review the specific rate limit pages within our specific API sections.

To check connection limits response will return three headers. This is useful to understand how many times you can use the rule endpoint, and how many reconnections attempts are allowed for the streaming endpoint.

The Java SDK provides APIs with a build-in retry mechanism to handle the rate limits. In case of getting an http error code 429, the API will check the response headers and will wait until the rate limit is reset.

In order to use the retry mechanism call the APIs with an additional parameter retries as a first argument, check the following example:

  int retries = 4;
  streamResult = apiInstance.tweets().sampleStream()
                      .tweetFields(tweetFields)
                      .execute(retries);

Read more about Filtered stream and rate limits

Get all fields

The Twitter API v2 endpoints are equipped with a set of parameters called fields, which allows you to select just the data that you want from each of the objects in your endpoint response.

When you need to get many fields in the response object it can be a bit gruelling to define all the needed fields. In order to make it easier, you can use the excludeInputFields approach. Instead of selecting the data that you want to get, you define which fields should be excluded from the response object. Using excludeInputFields() will change the behaviour of the execution, in this case all response fields will be returned besides the ones that were sent as input parameters.

    Set<String> tweetFields = new HashSet<>();
    tweetFields.add("non_public_metrics");
    tweetFields.add("promoted_metrics");
    tweetFields.add("organic_metrics");

    // Get all available fields excluding Tweet Fields `non_public_metrics`, `promoted_metrics` & `organic_metrics`
    Get2TweetsIdResponse result = apiInstance.tweets().findTweetById("20")
        .tweetFields(tweetFields).excludeInputFields().execute();

    // Get all the response fields
    Get2TweetsIdResponse result2 = apiInstance.tweets().findTweetById("20").excludeInputFields().execute();

Documentation for API Endpoints

All URIs are relative to https://api.twitter.com

ClassMethodHTTP requestDescription
BookmarksApigetUsersIdBookmarksGET /2/users/{id}/bookmarksBookmarks by User
BookmarksApipostUsersIdBookmarksPOST /2/users/{id}/bookmarksAdd Tweet to Bookmarks
BookmarksApiusersIdBookmarksDeleteDELETE /2/users/{id}/bookmarks/{tweet_id}Remove a bookmarked Tweet
ComplianceApicreateBatchComplianceJobPOST /2/compliance/jobsCreate compliance job
ComplianceApigetBatchComplianceJobGET /2/compliance/jobs/{id}Get Compliance Job
ComplianceApigetTweetsComplianceStreamGET /2/tweets/compliance/streamTweets Compliance stream
ComplianceApigetUsersComplianceStreamGET /2/users/compliance/streamUsers Compliance stream
ComplianceApilistBatchComplianceJobsGET /2/compliance/jobsList Compliance Jobs
GeneralApigetOpenApiSpecGET /2/openapi.jsonReturns the OpenAPI Specification document.
ListsApigetUserListMembershipsGET /2/users/{id}/list_membershipsGet a User's List Memberships
ListsApilistAddMemberPOST /2/lists/{id}/membersAdd a List member
ListsApilistIdCreatePOST /2/listsCreate List
ListsApilistIdDeleteDELETE /2/lists/{id}Delete List
ListsApilistIdGetGET /2/lists/{id}List lookup by List ID.
ListsApilistIdUpdatePUT /2/lists/{id}Update List.
ListsApilistRemoveMemberDELETE /2/lists/{id}/members/{user_id}Remove a List member
ListsApilistUserFollowPOST /2/users/{id}/followed_listsFollow a List
ListsApilistUserOwnedListsGET /2/users/{id}/owned_listsGet a User's Owned Lists.
ListsApilistUserPinPOST /2/users/{id}/pinned_listsPin a List
ListsApilistUserPinnedListsGET /2/users/{id}/pinned_listsGet a User's Pinned Lists
ListsApilistUserUnfollowDELETE /2/users/{id}/followed_lists/{list_id}Unfollow a List
ListsApilistUserUnpinDELETE /2/users/{id}/pinned_lists/{list_id}Unpin a List
ListsApiuserFollowedListsGET /2/users/{id}/followed_listsGet User's Followed Lists
SpacesApifindSpaceByIdGET /2/spaces/{id}Space lookup by Space ID
SpacesApifindSpacesByCreatorIdsGET /2/spaces/by/creator_idsSpace lookup by their creators
SpacesApifindSpacesByIdsGET /2/spacesSpace lookup up Space IDs
SpacesApisearchSpacesGET /2/spaces/searchSearch for Spaces
SpacesApispaceBuyersGET /2/spaces/{id}/buyersRetrieve the list of Users who purchased a ticket to the given space
SpacesApispaceTweetsGET /2/spaces/{id}/tweetsRetrieve Tweets from a Space.
TweetsApiaddOrDeleteRulesPOST /2/tweets/search/stream/rulesAdd/Delete rules
TweetsApicreateTweetPOST /2/tweetsCreation of a Tweet
TweetsApideleteTweetByIdDELETE /2/tweets/{id}Tweet delete by Tweet ID
TweetsApifindTweetByIdGET /2/tweets/{id}Tweet lookup by Tweet ID
TweetsApifindTweetsByIdGET /2/tweetsTweet lookup by Tweet IDs
TweetsApifindTweetsThatQuoteATweetGET /2/tweets/{id}/quote_tweetsRetrieve Tweets that quote a Tweet.
TweetsApigetRulesGET /2/tweets/search/stream/rulesRules lookup
TweetsApigetTweetsFirehoseStreamGET /2/tweets/firehose/streamFirehose stream
TweetsApigetTweetsSample10StreamGET /2/tweets/sample10/streamSample 10% stream
TweetsApihideReplyByIdPUT /2/tweets/{tweet_id}/hiddenHide replies
TweetsApilistsIdTweetsGET /2/lists/{id}/tweetsList Tweets timeline by List ID.
TweetsApisampleStreamGET /2/tweets/sample/streamSample stream
TweetsApisearchStreamGET /2/tweets/search/streamFiltered stream
TweetsApispaceBuyersGET /2/spaces/{id}/buyersRetrieve the list of Users who purchased a ticket to the given space
TweetsApispaceTweetsGET /2/spaces/{id}/tweetsRetrieve Tweets from a Space.
TweetsApitweetCountsFullArchiveSearchGET /2/tweets/counts/allFull archive search counts
TweetsApitweetCountsRecentSearchGET /2/tweets/counts/recentRecent search counts
TweetsApitweetsFullarchiveSearchGET /2/tweets/search/allFull-archive search
TweetsApitweetsRecentSearchGET /2/tweets/search/recentRecent search
TweetsApiusersIdLikePOST /2/users/{id}/likesCauses the User (in the path) to like the specified Tweet
TweetsApiusersIdLikedTweetsGET /2/users/{id}/liked_tweetsReturns Tweet objects liked by the provided User ID
TweetsApiusersIdMentionsGET /2/users/{id}/mentionsUser mention timeline by User ID
TweetsApiusersIdRetweetsPOST /2/users/{id}/retweetsCauses the User (in the path) to retweet the specified Tweet.
TweetsApiusersIdTimelineGET /2/users/{id}/timelines/reverse_chronologicalUser home timeline by User ID
TweetsApiusersIdTweetsGET /2/users/{id}/tweetsUser Tweets timeline by User ID
TweetsApiusersIdUnlikeDELETE /2/users/{id}/likes/{tweet_id}Causes the User (in the path) to unlike the specified Tweet
TweetsApiusersIdUnretweetsDELETE /2/users/{id}/retweets/{source_tweet_id}Causes the User (in the path) to unretweet the specified Tweet
UsersApifindMyUserGET /2/users/meUser lookup me
UsersApifindUserByIdGET /2/users/{id}User lookup by ID
UsersApifindUserByUsernameGET /2/users/by/username/{username}User lookup by username
UsersApifindUsersByIdGET /2/usersUser lookup by IDs
UsersApifindUsersByUsernameGET /2/users/byUser lookup by usernames
UsersApilistGetFollowersGET /2/lists/{id}/followersReturns User objects that follow a List by the provided List ID
UsersApilistGetMembersGET /2/lists/{id}/membersReturns User objects that are members of a List by the provided List ID.
UsersApitweetsIdLikingUsersGET /2/tweets/{id}/liking_usersReturns User objects that have liked the provided Tweet ID
UsersApitweetsIdRetweetingUsersGET /2/tweets/{id}/retweeted_byReturns User objects that have retweeted the provided Tweet ID
UsersApiusersIdBlockPOST /2/users/{id}/blockingBlock User by User ID
UsersApiusersIdBlockingGET /2/users/{id}/blockingReturns User objects that are blocked by provided User ID
UsersApiusersIdFollowPOST /2/users/{id}/followingFollow User
UsersApiusersIdFollowersGET /2/users/{id}/followersFollowers by User ID
UsersApiusersIdFollowingGET /2/users/{id}/followingFollowing by User ID
UsersApiusersIdMutePOST /2/users/{id}/mutingMute User by User ID.
UsersApiusersIdMutingGET /2/users/{id}/mutingReturns User objects that are muted by the provided User ID
UsersApiusersIdUnblockDELETE /2/users/{source_user_id}/blocking/{target_user_id}Unblock User by User ID
UsersApiusersIdUnfollowDELETE /2/users/{source_user_id}/following/{target_user_id}Unfollow User
UsersApiusersIdUnmuteDELETE /2/users/{source_user_id}/muting/{target_user_id}Unmute User by User ID

Documentation for Models