Do you want to learn how to create Tweets from a Java application using the X (Twitter) API v2? This blog will show you in a step-by-step guide how to do so. Enjoy!

1. Introduction

X (Twitter) provides an API which allows you to interact with your account from an application. Currently, two versions exist. In this blog you will use the most recent X API v2. Although a lot of information can be found how to set up your environment and how to interact with the API, it took me quite some time to do so from within a Java application. In this blog, you will learn how to set up your account and how you can create tweets from a Java application.

The sources for this blog can be found at GitHub.

2. Prerequisites

Prerequisites for this blog are:

  • Basic knowledge of Java, Java 21 is used;
  • An X account;
  • A website you own (not mandatory, but for security reasons the better).

3. Setup Developer Account

First thing to do, is to set up a developer account.

  1. Navigate to the sign-up page.
  2. Beware that there exist multiple types of accounts: free account, basic account, pro account, enterprise account.
  3. Scroll down all the way to the bottom of the page and choose to create a free account by clicking the button Sign up Free Account.
  4. You will need to describe your use case using at least 250 characters.
  5. After signing up, you end up in the developer portal.

4. Create Project and App

With the Free tier, you can create one Project and one App. Create the Project and the App.

5. Authentication

As you are going to create Tweets for a user, you will need to set up the authentication using OAuth 2.0 Authorization Code Flow with PKCE. However, it is important that you have configured your App correctly. Navigate to your App in the developer portal and click the Edit button in the User authentication settings.

Different sections are available here where you are required to add information and to choose options.

5.1 App Permissions

These permissions enable OAuth 1.0a Authentication. It is confusing that you need to check one of these bullets because OAuth 1.0a Authentication will not be used in your use case. However, because you will create a tweet, select Read and write, just to be sure.

5.2 Type of App

The type of App will enable OAuth 2.0 Authentication, this is the one you will use. You will invoke the API from an application. Therefore, choose Web App, Automated App or Bot.

5.3 App Info

In the App info section, you need to provide a Callback URI and a Website URL. The Callback URI is important as you will see later on in the next paragraphs. Fill in the URL of your website. You can use any URL, but the Callback URI will be used to provide you an access token, so it is better to use an URL of a website you own.

Click the Save button to save your changes. A Client ID and Client Secret are generated, save them.

6. Create Tweet

Everything is set up in the developer portal. Now it is time to create the Java application in order to be able to create a Tweet.

6.1 Twitter API Client Library for Java

In order to create the tweet, you will make use of the Twitter API Client Library for Java. Beware that, at the time of writing, the library is still in beta. The library also only supports the X API v2 endpoints, but that is exactly the endpoints you will be using, so that is not a problem.

Add the dependency to the pom file:

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

6.2 Authorization

In order to be able to create tweets on behalf of your account, you need to authorize the App. The source code below is based on the example provided in the SDK.

You need the Client ID and Client Secret you saved before. If you lost them, you can generate a new secret in the developer portal. Navigate to your App, click the Keys and tokens tab. Scroll down and retrieve the Client ID and generate a new Client Secret.

The main method executes the following steps:

  1. Set the correct credentials as environment variables:
    • TWITTER_OAUTH2_CLIENT_ID: the OAuth 2.0 client ID
    • TWITTER_OAUTH2_CLIENT_SECRET: the Oauth 2.0 Client Secret
    • TWITTER_OAUTH2_ACCESS_TOKEN: leave it blank
    • TWITTER_OAUTH2_REFRESH_TOKEN: leave it blank
  2. Authorize the App and retrieve an access and refresh token.
  3. Set the newly received access and refresh token in the credentials object.
  4. Call the X API in order to create the tweet.
public static void main(String[] args) {
    TwitterCredentialsOAuth2 credentials = 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"));

    OAuth2AccessToken accessToken = getAccessToken(credentials);
    if (accessToken == null) {
        return;
    }

    // Setting the access & refresh tokens into TwitterCredentialsOAuth2
    credentials.setTwitterOauth2AccessToken(accessToken.getAccessToken());
    credentials.setTwitterOauth2RefreshToken(accessToken.getRefreshToken());
    callApi(credentials);
}

The getAccessToken method executes the following steps:

  1. Creates a Twitter service object:
    • Set the Callback URI to the one you specified in the developer portal.
    • Set the scopes (what is allowed) you want to authorize. By using offline.access, you will receive a refresh token which allows you to retrieve a new access token without prompting the user via the refresh token flow. This means that you can continuously create tweets without the need of user interaction.
  2. An authorization URL is provided to you where you will authorize the App for the requested scopes.
  3. You are redirected to the Callback URI and in the URL the authorization code will be visible.
  4. The getAccessToken method waits until you copy the authorization code and hit enter.
  5. The access token and refresh token are printed to the console and returned from the method.
private static OAuth2AccessToken getAccessToken(TwitterCredentialsOAuth2 credentials) {
     TwitterOAuth20Service service = new TwitterOAuth20Service(
             credentials.getTwitterOauth2ClientId(),
             credentials.getTwitterOAuth2ClientSecret(),
             "<Fill in your Callback URI as configured in your X App in the developer portal>",
             "offline.access tweet.read users.read tweet.write");

     OAuth2AccessToken accessToken = null;
     try {
         final Scanner in = new Scanner(System.in, "UTF-8");
         System.out.println("Fetching the Authorization URL...");

         final String secretState = "state";
         PKCE pkce = new PKCE();
         pkce.setCodeChallenge("challenge");
         pkce.setCodeChallengeMethod(PKCECodeChallengeMethod.PLAIN);
         pkce.setCodeVerifier("challenge");
         String authorizationUrl = service.getAuthorizationUrl(pkce, secretState);

         System.out.println("Go to the Authorization URL and authorize your App:\n" +
                 authorizationUrl + "\nAfter that paste the authorization code here\n>>");
         final String code = in.nextLine();
         System.out.println("\nTrading the Authorization Code for an Access Token...");
         accessToken = service.getAccessToken(pkce, code);

         System.out.println("Access token: " + accessToken.getAccessToken());
         System.out.println("Refresh token: " + accessToken.getRefreshToken());
     } catch (Exception e) {
         System.err.println("Error while getting the access token:\n " + e);
         e.printStackTrace();
     }
     return accessToken;
 }

Now that you authorized the App, you are able to see that you have done so in your X settings.

  1. Navigate to Settings and Privacy in your X account.
  2. Navigate to Security and account access.
  3. Navigate to Apps and sessions.
  4. Navigate to Connected apps.
  5. Here you will find the App you authorized and which authorizations it has.

The callApi method executes the following steps:

  1. Create a TwitterApi instance with the provided credentials.
  2. Create a TweetRequest.
  3. Create the Tweet.
private static void callApi(TwitterCredentialsOAuth2 credentials) {
    TwitterApi apiInstance = new TwitterApi(credentials);
    TweetCreateRequest tweetCreateRequest = new TweetCreateRequest(); // TweetCreateRequest |
    tweetCreateRequest.setText("Hello World!");
    try {
        TweetCreateResponse result = apiInstance.tweets().createTweet(tweetCreateRequest)
                .execute();
        System.out.println(result);
    } catch (ApiException e) {
        System.err.println("Exception when calling TweetsApi#createTweet");
        System.err.println("Status code: " + e.getCode());
        System.err.println("Reason: " + e.getResponseBody());
        System.err.println("Response headers: " + e.getResponseHeaders());
        e.printStackTrace();
    }
}

Add an sdk.properties file to the root of the repository, otherwise an Exception will be thrown (the Exception is not blocking, but spoils the output).

If everything went well, you now have created your first Tweet!

6.3 Obtain New Access Token

You only need to execute the source code above once. The retrieved access token, however, will only stay valid for two hours. After that time (or earlier), you need to retrieve a new access token using the refresh token. The source code below is based on the example provided in the SDK.

The main method executes the following steps:

  1. Set the credentials including the access and refresh token you obtained in the previous sections.
  2. Add a callback to the TwitterApi instance in order to retrieve a new access and refresh token.
  3. Request to refresh the token, the callback method MainToken will set the new tokens and again a Tweet can be created.
public static void main(String[] args) {
    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")));
    apiInstance.addCallback(new MaintainToken());

    try {
        apiInstance.refreshToken();
    } catch (Exception e) {
        System.err.println("Error while trying to refresh existing token : " + e);
        e.printStackTrace();
        return;
    }
    callApi(apiInstance);
}

The MaintainToken method only sets the new tokens.

class MaintainToken implements ApiClientCallback {
    @Override
    public void onAfterRefreshToken(OAuth2AccessToken accessToken) {
        System.out.println("access: " + accessToken.getAccessToken());
        System.out.println("refresh: " + accessToken.getRefreshToken());
    }
}

7. Conclusion

In this blog, you learned how to configure an App in the developer portal. You learned how to authorize your App from a Java application and how to create a Tweet.