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:
- Java 1.8+
- 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:
target/twitter-api-java-sdk-2.0.3.jar
target/lib/*.jar
Twitter Credentials
Twitter APIs support three types of authentications:
OAuth 2.0 Authorization with PKCE
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
OAuth 2.0 Bearer Token (app-only)
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