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
- API version: 2.45
Twitter API v2 available endpoints
For more information, please visit https://developer.twitter.com/
- Requirements
- Installation
- Twitter Credentials
- Getting Started
- Authentication
- Rate limits retry mechanism
- Documentation for API Endpoints
- Documentation for Models
Building the API client library requires:
- Java 1.8+
- Maven (3.8.3+)/Gradle (7.2+)
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.
Add this dependency to your project's POM:
<dependency>
<groupId>com.twitter</groupId>
<artifactId>twitter-api-java-sdk</artifactId>
<version>2.0.1</version>
</dependency>
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.1"
}
At first generate the JAR by executing:
mvn clean package
Then manually install the following JARs:
target/twitter-api-java-sdk-2.0.1.jar
target/lib/*.jar
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.
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();
}
}
}
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/
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
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()apiInstance.tweets().sampleStream()
.tweetFields(tweetFields)
.execute(retries);
Read more about Filtered stream and rate limits
All URIs are relative to https://api.twitter.com
Class | Method | HTTP request | Description |
---|---|---|---|
BookmarksApi | getUsersIdBookmarks | GET /2/users/{id}/bookmarks | Bookmarks by User |
BookmarksApi | postUsersIdBookmarks | POST /2/users/{id}/bookmarks | Add Tweet to Bookmarks |
BookmarksApi | usersIdBookmarksDelete | DELETE /2/users/{id}/bookmarks/{tweet_id} | Remove a bookmarked Tweet |
ComplianceApi | createBatchComplianceJob | POST /2/compliance/jobs | Create compliance job |
ComplianceApi | getBatchComplianceJob | GET /2/compliance/jobs/{id} | Get Compliance Job |
ComplianceApi | listBatchComplianceJobs | GET /2/compliance/jobs | List Compliance Jobs |
GeneralApi | getOpenApiSpec | GET /2/openapi.json | Returns the OpenAPI Specification document. |
ListsApi | getUserListMemberships | GET /2/users/{id}/list_memberships | Get a User's List Memberships |
ListsApi | listAddMember | POST /2/lists/{id}/members | Add a List member |
ListsApi | listIdCreate | POST /2/lists | Create List |
ListsApi | listIdDelete | DELETE /2/lists/{id} | Delete List |
ListsApi | listIdGet | GET /2/lists/{id} | List lookup by List ID. |
ListsApi | listIdUpdate | PUT /2/lists/{id} | Update List. |
ListsApi | listRemoveMember | DELETE /2/lists/{id}/members/{user_id} | Remove a List member |
ListsApi | listUserFollow | POST /2/users/{id}/followed_lists | Follow a List |
ListsApi | listUserOwnedLists | GET /2/users/{id}/owned_lists | Get a User's Owned Lists. |
ListsApi | listUserPin | POST /2/users/{id}/pinned_lists | Pin a List |
ListsApi | listUserPinnedLists | GET /2/users/{id}/pinned_lists | Get a User's Pinned Lists |
ListsApi | listUserUnfollow | DELETE /2/users/{id}/followed_lists/{list_id} | Unfollow a List |
ListsApi | listUserUnpin | DELETE /2/users/{id}/pinned_lists/{list_id} | Unpin a List |
ListsApi | userFollowedLists | GET /2/users/{id}/followed_lists | Get User's Followed Lists |
SpacesApi | findSpaceById | GET /2/spaces/{id} | Space lookup by Space ID |
SpacesApi | findSpacesByCreatorIds | GET /2/spaces/by/creator_ids | Space lookup by their creators |
SpacesApi | findSpacesByIds | GET /2/spaces | Space lookup up Space IDs |
SpacesApi | searchSpaces | GET /2/spaces/search | Search for Spaces |
SpacesApi | spaceBuyers | GET /2/spaces/{id}/buyers | Retrieve the list of Users who purchased a ticket to the given space |
SpacesApi | spaceTweets | GET /2/spaces/{id}/tweets | Retrieve Tweets from a Space. |
TweetsApi | addOrDeleteRules | POST /2/tweets/search/stream/rules | Add/Delete rules |
TweetsApi | createTweet | POST /2/tweets | Creation of a Tweet |
TweetsApi | deleteTweetById | DELETE /2/tweets/{id} | Tweet delete by Tweet ID |
TweetsApi | findTweetById | GET /2/tweets/{id} | Tweet lookup by Tweet ID |
TweetsApi | findTweetsById | GET /2/tweets | Tweet lookup by Tweet IDs |
TweetsApi | findTweetsThatQuoteATweet | GET /2/tweets/{id}/quote_tweets | Retrieve Tweets that quote a Tweet. |
TweetsApi | getRules | GET /2/tweets/search/stream/rules | Rules lookup |
TweetsApi | hideReplyById | PUT /2/tweets/{tweet_id}/hidden | Hide replies |
TweetsApi | listsIdTweets | GET /2/lists/{id}/tweets | List Tweets timeline by List ID. |
TweetsApi | sampleStream | GET /2/tweets/sample/stream | Sample stream |
TweetsApi | searchStream | GET /2/tweets/search/stream | Filtered stream |
TweetsApi | spaceBuyers | GET /2/spaces/{id}/buyers | Retrieve the list of Users who purchased a ticket to the given space |
TweetsApi | spaceTweets | GET /2/spaces/{id}/tweets | Retrieve Tweets from a Space. |
TweetsApi | tweetCountsFullArchiveSearch | GET /2/tweets/counts/all | Full archive search counts |
TweetsApi | tweetCountsRecentSearch | GET /2/tweets/counts/recent | Recent search counts |
TweetsApi | tweetsFullarchiveSearch | GET /2/tweets/search/all | Full-archive search |
TweetsApi | tweetsRecentSearch | GET /2/tweets/search/recent | Recent search |
TweetsApi | usersIdLike | POST /2/users/{id}/likes | Causes the User (in the path) to like the specified Tweet |
TweetsApi | usersIdLikedTweets | GET /2/users/{id}/liked_tweets | Returns Tweet objects liked by the provided User ID |
TweetsApi | usersIdMentions | GET /2/users/{id}/mentions | User mention timeline by User ID |
TweetsApi | usersIdRetweets | POST /2/users/{id}/retweets | Causes the User (in the path) to retweet the specified Tweet. |
TweetsApi | usersIdTimeline | GET /2/users/{id}/timelines/reverse_chronological | User home timeline by User ID |
TweetsApi | usersIdTweets | GET /2/users/{id}/tweets | User Tweets timeline by User ID |
TweetsApi | usersIdUnlike | DELETE /2/users/{id}/likes/{tweet_id} | Causes the User (in the path) to unlike the specified Tweet |
TweetsApi | usersIdUnretweets | DELETE /2/users/{id}/retweets/{source_tweet_id} | Causes the User (in the path) to unretweet the specified Tweet |
UsersApi | findMyUser | GET /2/users/me | User lookup me |
UsersApi | findUserById | GET /2/users/{id} | User lookup by ID |
UsersApi | findUserByUsername | GET /2/users/by/username/{username} | User lookup by username |
UsersApi | findUsersById | GET /2/users | User lookup by IDs |
UsersApi | findUsersByUsername | GET /2/users/by | User lookup by usernames |
UsersApi | listGetFollowers | GET /2/lists/{id}/followers | Returns User objects that follow a List by the provided List ID |
UsersApi | listGetMembers | GET /2/lists/{id}/members | Returns User objects that are members of a List by the provided List ID. |
UsersApi | tweetsIdLikingUsers | GET /2/tweets/{id}/liking_users | Returns User objects that have liked the provided Tweet ID |
UsersApi | tweetsIdRetweetingUsers | GET /2/tweets/{id}/retweeted_by | Returns User objects that have retweeted the provided Tweet ID |
UsersApi | usersIdBlock | POST /2/users/{id}/blocking | Block User by User ID |
UsersApi | usersIdBlocking | GET /2/users/{id}/blocking | Returns User objects that are blocked by provided User ID |
UsersApi | usersIdFollow | POST /2/users/{id}/following | Follow User |
UsersApi | usersIdFollowers | GET /2/users/{id}/followers | Returns User objects that follow a List by the provided User ID |
UsersApi | usersIdFollowing | GET /2/users/{id}/following | Following by User ID |
UsersApi | usersIdMute | POST /2/users/{id}/muting | Mute User by User ID. |
UsersApi | usersIdMuting | GET /2/users/{id}/muting | Returns User objects that are muted by the provided User ID |
UsersApi | usersIdUnblock | DELETE /2/users/{source_user_id}/blocking/{target_user_id} | Unblock User by User ID |
UsersApi | usersIdUnfollow | DELETE /2/users/{source_user_id}/following/{target_user_id} | Unfollow User |
UsersApi | usersIdUnmute | DELETE /2/users/{source_user_id}/muting/{target_user_id} | Unmute User by User ID |
- AddOrDeleteRulesRequest
- AddOrDeleteRulesResponse
- AddRulesRequest
- AnimatedGif
- AnimatedGifAllOf
- BlockUserMutationResponse
- BlockUserMutationResponseData
- BlockUserRequest
- BookmarkAddRequest
- BookmarkMutationResponse
- BookmarkMutationResponseData
- CashtagEntity
- CashtagFields
- ClientDisconnectedProblem
- ClientForbiddenProblem
- ClientForbiddenProblemAllOf
- ComplianceJob
- ComplianceJobStatus
- ComplianceJobType
- ConflictProblem
- ConnectionExceptionProblem
- ConnectionExceptionProblemAllOf
- ContextAnnotation
- ContextAnnotationDomainFields
- ContextAnnotationEntityFields
- CreateComplianceJobRequest
- CreateComplianceJobResponse
- DeleteRulesRequest
- DeleteRulesRequestDelete
- DisallowedResourceProblem
- DisallowedResourceProblemAllOf
- DuplicateRuleProblem
- DuplicateRuleProblemAllOf
- EntityIndicesInclusiveExclusive
- EntityIndicesInclusiveInclusive
- Error
- Expansions
- FieldUnauthorizedProblem
- FieldUnauthorizedProblemAllOf
- FilteredStreamingTweetResponse
- FilteredStreamingTweetResponseMatchingRules
- FullTextEntities
- FullTextEntitiesAnnotations
- FullTextEntitiesAnnotationsAllOf
- GenericProblem
- Geo
- Get2ComplianceJobsIdResponse
- Get2ComplianceJobsResponse
- Get2ComplianceJobsResponseMeta
- Get2ListsIdFollowersResponse
- Get2ListsIdFollowersResponseMeta
- Get2ListsIdMembersResponse
- Get2ListsIdResponse
- Get2ListsIdTweetsResponse
- Get2SpacesByCreatorIdsResponse
- Get2SpacesIdBuyersResponse
- Get2SpacesIdResponse
- Get2SpacesIdTweetsResponse
- Get2SpacesResponse
- Get2SpacesSearchResponse
- Get2TweetsCountsAllResponse
- Get2TweetsCountsAllResponseMeta
- Get2TweetsCountsRecentResponse
- Get2TweetsIdLikingUsersResponse
- Get2TweetsIdQuoteTweetsResponse
- Get2TweetsIdQuoteTweetsResponseMeta
- Get2TweetsIdResponse
- Get2TweetsIdRetweetedByResponse
- Get2TweetsResponse
- Get2TweetsSampleStreamResponse
- Get2TweetsSearchAllResponse
- Get2TweetsSearchAllResponseMeta
- Get2TweetsSearchRecentResponse
- Get2TweetsSearchStreamResponse
- Get2UsersByResponse
- Get2UsersByUsernameUsernameResponse
- Get2UsersIdBlockingResponse
- Get2UsersIdBookmarksResponse
- Get2UsersIdFollowedListsResponse
- Get2UsersIdFollowersResponse
- Get2UsersIdFollowingResponse
- Get2UsersIdLikedTweetsResponse
- Get2UsersIdListMembershipsResponse
- Get2UsersIdMentionsResponse
- Get2UsersIdMentionsResponseMeta
- Get2UsersIdMutingResponse
- Get2UsersIdOwnedListsResponse
- Get2UsersIdPinnedListsResponse
- Get2UsersIdResponse
- Get2UsersIdTimelinesReverseChronologicalResponse
- Get2UsersIdTweetsResponse
- Get2UsersMeResponse
- Get2UsersResponse
- HashtagEntity
- HashtagFields
- InvalidRequestProblem
- InvalidRequestProblemAllOf
- InvalidRequestProblemAllOfErrors
- InvalidRuleProblem
- ListAddUserRequest
- ListCreateRequest
- ListCreateResponse
- ListCreateResponseData
- ListDeleteResponse
- ListDeleteResponseData
- ListFollowedRequest
- ListFollowedResponse
- ListFollowedResponseData
- ListMutateResponse
- ListMutateResponseData
- ListPinnedRequest
- ListPinnedResponse
- ListPinnedResponseData
- ListUnpinResponse
- ListUpdateRequest
- ListUpdateResponse
- ListUpdateResponseData
- Media
- MentionEntity
- MentionFields
- ModelList
- MuteUserMutationResponse
- MuteUserMutationResponseData
- MuteUserRequest
- NonCompliantRulesProblem
- OperationalDisconnectProblem
- OperationalDisconnectProblemAllOf
- Photo
- PhotoAllOf
- Place
- PlaceType
- Point
- Poll
- PollOption
- Problem
- ProblemErrors
- ProblemOrError
- ReplySettings
- ReportUsersRequest
- ReportUsersResponse
- ReportUsersResponseData
- ResourceNotFoundProblem
- ResourceNotFoundProblemAllOf
- ResourceUnauthorizedProblem
- ResourceUnauthorizedProblemAllOf
- ResourceUnavailableProblem
- ResourceUnavailableProblemAllOf
- Rule
- RuleNoId
- RulesCapProblem
- RulesLookupResponse
- RulesRequestSummary
- RulesRequestSummaryOneOf
- RulesRequestSummaryOneOf1
- RulesResponseMetadata
- SearchCount
- Space
- SpaceTopics
- StreamingTweetResponse
- Topic
- Tweet
- TweetAttachments
- TweetCreateRequest
- TweetCreateRequestGeo
- TweetCreateRequestMedia
- TweetCreateRequestPoll
- TweetCreateRequestReply
- TweetCreateResponse
- TweetCreateResponseData
- TweetDeleteResponse
- TweetDeleteResponseData
- TweetGeo
- TweetHideRequest
- TweetHideResponse
- TweetHideResponseData
- TweetNonPublicMetrics
- TweetOrganicMetrics
- TweetPromotedMetrics
- TweetPublicMetrics
- TweetReferencedTweets
- TweetWithheld
- UnsupportedAuthenticationProblem
- UrlEntity
- UrlFields
- UrlImage
- UsageCapExceededProblem
- UsageCapExceededProblemAllOf
- User
- UserEntities
- UserEntitiesUrl
- UserPublicMetrics
- UserWithheld
- UsersFollowingCreateRequest
- UsersFollowingCreateResponse
- UsersFollowingCreateResponseData
- UsersFollowingDeleteResponse
- UsersLikesCreateRequest
- UsersLikesCreateResponse
- UsersLikesCreateResponseData
- UsersLikesDeleteResponse
- UsersRetweetsCreateRequest
- UsersRetweetsCreateResponse
- UsersRetweetsCreateResponseData
- UsersRetweetsDeleteResponse
- Variant
- Video
- VideoAllOf
- VideoAllOfNonPublicMetrics
- VideoAllOfOrganicMetrics
- VideoAllOfPromotedMetrics
- VideoAllOfPublicMetrics