### Install Twitter API Java SDK using Maven Source: https://github.com/xdevplatform/twitter-api-java-sdk/blob/main/README.md Installs the Twitter API client library to your local Maven repository. This command cleans the project and then installs the artifacts. For deployment to a remote repository, use 'mvn clean deploy'. ```shell mvn clean install ``` -------------------------------- ### Get User's Followers using Twitter API Java SDK Source: https://context7.com/xdevplatform/twitter-api-java-sdk/llms.txt This example shows how to retrieve a list of a user's followers using the `UsersApi`. It takes a user ID as input and allows specifying the maximum number of results and desired user fields. The output lists the usernames of the followers and includes logic for handling pagination if more results are available. ```java try { Get2UsersIdFollowersResponse result = apiInstance.users() .usersIdFollowers("2244994945") // User ID .maxResults(100) .userFields(userFields) // Assuming userFields is defined elsewhere .execute(); if (result.getData() != null) { result.getData().forEach(follower -> { System.out.println("Follower: @" + follower.getUsername()); }); } // Handle pagination if (result.getMeta() != null && result.getMeta().getNextToken() != null) { String nextToken = result.getMeta().getNextToken(); // Use nextToken for subsequent requests } } catch (ApiException e) { System.err.println("Failed to get followers: " + e.getResponseBody()); e.printStackTrace(); } ``` -------------------------------- ### Get Tweets Firehose Stream using Twitter API Java SDK Source: https://github.com/xdevplatform/twitter-api-java-sdk/blob/main/docs/TweetsApi.md This Java code snippet demonstrates how to connect to the Twitter API and retrieve a real-time stream of tweets using the Twitter API Java SDK. It covers authentication setup (Bearer Token), setting various parameters for the stream (like time range, fields to include), and processing the incoming tweet data line by line. ```java // Import classes: import com.twitter.clientlib.ApiClient; import com.twitter.clientlib.ApiException; import com.twitter.clientlib.Configuration; import com.twitter.clientlib.auth.*; import com.twitter.clientlib.model.*; import com.twitter.clientlib.TwitterCredentialsOAuth2; import com.twitter.clientlib.TwitterCredentialsBearer; import com.twitter.clientlib.api.TwitterApi; import com.twitter.clientlib.api.TweetsApi; import java.io.InputStream; import com.google.common.reflect.TypeToken; import java.io.BufferedReader; import java.io.InputStreamReader; import java.lang.reflect.Type; import java.util.List; import java.util.Set; import java.util.Arrays; import java.util.HashSet; import java.time.OffsetDateTime; public class Example { public static void main(String[] args) { // Set the credentials based on the API's "security" tag values. // Check the API definition in https://api.twitter.com/2/openapi.json // When multiple options exist, the SDK supports only "OAuth2UserToken" or "BearerToken" // Uncomment and set the credentials configuration // Configure HTTP bearer authorization: // TwitterCredentialsBearer credentials = new TwitterCredentialsBearer(System.getenv("TWITTER_BEARER_TOKEN")); TwitterApi apiInstance = new TwitterApi(credentials); // Set the params values Integer backfillMinutes = 56; // Integer | The number of minutes of backfill requested. Integer partition = 56; // Integer | The partition number. OffsetDateTime startTime = OffsetDateTime.parse("2021-02-14T18:40:40.000Z"); // OffsetDateTime | YYYY-MM-DDTHH:mm:ssZ. The earliest UTC timestamp to which the Tweets will be provided. OffsetDateTime endTime = OffsetDateTime.parse("2021-02-14T18:40:40.000Z"); // OffsetDateTime | YYYY-MM-DDTHH:mm:ssZ. The latest UTC timestamp to which the Tweets will be provided. Set tweetFields = new HashSet<>(Arrays.asList()); // Set | A comma separated list of Tweet fields to display. Set expansions = new HashSet<>(Arrays.asList()); // Set | A comma separated list of fields to expand. Set mediaFields = new HashSet<>(Arrays.asList()); // Set | A comma separated list of Media fields to display. Set pollFields = new HashSet<>(Arrays.asList()); // Set | A comma separated list of Poll fields to display. Set userFields = new HashSet<>(Arrays.asList()); // Set | A comma separated list of User fields to display. Set placeFields = new HashSet<>(Arrays.asList()); // Set | A comma separated list of Place fields to display. try { InputStream result = apiInstance.tweets().getTweetsFirehoseStream(partition) .backfillMinutes(backfillMinutes) .startTime(startTime) .endTime(endTime) .tweetFields(tweetFields) .expansions(expansions) .mediaFields(mediaFields) .pollFields(pollFields) .userFields(userFields) .placeFields(placeFields) .execute(); try{ JSON json = new JSON(); Type localVarReturnType = new TypeToken(){}.getType(); BufferedReader reader = new BufferedReader(new InputStreamReader(result)); String line = reader.readLine(); while (line != null) { if(line.isEmpty()) { System.out.println("==> Empty line"); line = reader.readLine(); continue; } Object jsonObject = json.getGson().fromJson(line, localVarReturnType); System.out.println(jsonObject != null ? jsonObject.toString() : "Null object"); line = reader.readLine(); } }catch (Exception e) { e.printStackTrace(); System.out.println(e); } } catch (ApiException e) { System.err.println("Exception when calling TweetsApi#getTweetsFirehoseStream"); System.err.println("Status code: " + e.getCode()); System.err.println("Reason: " + e.getResponseBody()); System.err.println("Response headers: " + e.getResponseHeaders()); e.printStackTrace(); } } } ``` -------------------------------- ### GET /2/tweets/sample/stream Source: https://github.com/xdevplatform/twitter-api-java-sdk/blob/main/docs/TweetsApi.md This endpoint provides a sample stream of tweets. It provides a real-time, representative sample of all public tweets. ```APIDOC ## GET /2/tweets/sample/stream ### Description Sample stream. ### Method GET ### Endpoint /2/tweets/sample/stream ### Parameters #### Query Parameters - **tweet.fields** (string) - Optional - Comma separated list of fields to include in the tweet object. - **expansions** (string) - Optional - Comma separated list of expansions to include in the response. - **media.fields** (string) - Optional - Comma separated list of media fields to include in the response. - **poll.fields** (string) - Optional - Comma separated list of poll fields to include in the response. - **user.fields** (string) - Optional - Comma separated list of user fields to include in the response. ### Request Example (No request body needed for GET) ### Response #### Success Response (200) - **data** (object) - The tweet. - **includes** (object) - Expansions of the tweet. #### Response Example { "data": { "id": "1234567890", "text": "Hello, world!" } } ``` -------------------------------- ### Get User Compliance Stream using Java Source: https://github.com/xdevplatform/twitter-api-java-sdk/blob/main/docs/ComplianceApi.md This snippet demonstrates how to retrieve a stream of user compliance events using the Twitter API Java SDK. Similar to tweet compliance, it requires authentication and allows setting parameters like partition, backfill minutes, start time, and end time. The method signature indicates it returns a `UserComplianceStreamResponse`. ```java UserComplianceStreamResponse getUsersComplianceStream(partition).backfillMinutes(backfillMinutes).startTime(startTime).endTime(endTime).execute(); ``` -------------------------------- ### TweetsApi - Sample Stream Source: https://github.com/xdevplatform/twitter-api-java-sdk/blob/main/docs/TweetsApi.md This example demonstrates how to connect to the Twitter API v2 sample stream using the Java SDK. It shows how to set up authentication, configure various tweet fields, and process the incoming stream of tweets. ```APIDOC ## GET /2/tweets/sample/stream ### Description Retrieves a low-fidelity stream of public tweets. This endpoint is part of the Twitter API v2 and allows for real-time access to a sample of public tweets. It supports various parameters to customize the data returned, such as tweet fields, expansions, and media fields. ### Method GET ### Endpoint /2/tweets/sample/stream ### Parameters #### Query Parameters - **backfillMinutes** (Integer) - Optional - The number of minutes of backfill requested. - **tweetFields** (Set) - Optional - A comma separated list of Tweet fields to display. - **expansions** (Set) - Optional - A comma separated list of fields to expand. - **mediaFields** (Set) - Optional - A comma separated list of Media fields to display. - **pollFields** (Set) - Optional - A comma separated list of Poll fields to display. - **userFields** (Set) - Optional - A comma separated list of User fields to display. - **placeFields** (Set) - Optional - A comma separated list of Place fields to display. ### Request Example ```java // Configure authentication (OAuth2UserToken or BearerToken) // TwitterCredentialsBearer credentials = new TwitterCredentialsBearer(System.getenv("TWITTER_BEARER_TOKEN")); TwitterApi apiInstance = new TwitterApi(credentials); Set tweetFields = new HashSet<>(Arrays.asList("created_at", "author_id")); Set expansions = new HashSet<>(Arrays.asList("author_id")); InputStream result = apiInstance.tweets().sampleStream() .backfillMinutes(5) .tweetFields(tweetFields) .expansions(expansions) .execute(); ``` ### Response #### Success Response (200) - **StreamingTweetResponse** - A stream of tweets matching the specified criteria. #### Response Example ```json { "data": { "id": "20", "text": "Wow, the sky is blue today." }, "includes": { "users": [ { "id": "789", "name": "Example User", "username": "exampleuser" } ] } } ``` #### Error Handling - **ApiException** - Catches errors related to API calls, providing status code, response body, and headers. ``` -------------------------------- ### Get Twitter Stream Sample using Java SDK Source: https://github.com/xdevplatform/twitter-api-java-sdk/blob/main/docs/TweetsApi.md This snippet demonstrates how to retrieve a sample stream of tweets using the Twitter API Java SDK. It covers setting up authentication (Bearer Token), configuring request parameters like backfill minutes and desired tweet fields, and processing the streaming response. Ensure you have the necessary dependencies and valid bearer token configured. ```java // Import classes: import com.twitter.clientlib.ApiClient; import com.twitter.clientlib.ApiException; import com.twitter.clientlib.Configuration; import com.twitter.clientlib.auth.*; import com.twitter.clientlib.model.*; import com.twitter.clientlib.TwitterCredentialsOAuth2; import com.twitter.clientlib.TwitterCredentialsBearer; import com.twitter.clientlib.api.TwitterApi; import com.twitter.clientlib.api.TweetsApi; import java.io.InputStream; import com.google.common.reflect.TypeToken; import java.io.BufferedReader; import java.io.InputStreamReader; import java.lang.reflect.Type; import java.util.List; import java.util.Set; import java.util.Arrays; import java.util.HashSet; import java.time.OffsetDateTime; public class Example { public static void main(String[] args) { // Set the credentials based on the API's "security" tag values. // Check the API definition in https://api.twitter.com/2/openapi.json // When multiple options exist, the SDK supports only "OAuth2UserToken" or "BearerToken" // Uncomment and set the credentials configuration // Configure HTTP bearer authorization: // TwitterCredentialsBearer credentials = new TwitterCredentialsBearer(System.getenv("TWITTER_BEARER_TOKEN")); TwitterApi apiInstance = new TwitterApi(credentials); // Set the params values Integer backfillMinutes = 56; // Integer | The number of minutes of backfill requested. Set tweetFields = new HashSet<>(Arrays.asList()); // Set | A comma separated list of Tweet fields to display. Set expansions = new HashSet<>(Arrays.asList()); // Set | A comma separated list of fields to expand. Set mediaFields = new HashSet<>(Arrays.asList()); // Set | A comma separated list of Media fields to display. Set pollFields = new HashSet<>(Arrays.asList()); // Set | A comma separated list of Poll fields to display. Set userFields = new HashSet<>(Arrays.asList()); // Set | A comma separated list of User fields to display. Set placeFields = new HashSet<>(Arrays.asList()); // Set | A comma separated list of Place fields to display. try { InputStream result = apiInstance.tweets().sampleStream() .backfillMinutes(backfillMinutes) .tweetFields(tweetFields) .expansions(expansions) .mediaFields(mediaFields) .pollFields(pollFields) .userFields(userFields) .placeFields(placeFields) .execute(); try{ JSON json = new JSON(); Type localVarReturnType = new TypeToken(){}.getType(); BufferedReader reader = new BufferedReader(new InputStreamReader(result)); String line = reader.readLine(); while (line != null) { if(line.isEmpty()) { System.out.println("==> Empty line"); line = reader.readLine(); continue; } Object jsonObject = json.getGson().fromJson(line, localVarReturnType); System.out.println(jsonObject != null ? jsonObject.toString() : "Null object"); line = reader.readLine(); } }catch (Exception e) { e.printStackTrace(); System.out.println(e); } } catch (ApiException e) { System.err.println("Exception when calling TweetsApi#sampleStream"); System.err.println("Status code: " + e.getCode()); System.err.println("Reason: " + e.getResponseBody()); System.err.println("Response headers: " + e.getResponseHeaders()); e.printStackTrace(); } } } ``` -------------------------------- ### Stream Tweets using Twitter API Java SDK Source: https://github.com/xdevplatform/twitter-api-java-sdk/blob/main/docs/TweetsApi.md This example demonstrates how to connect to the Twitter API, configure parameters for streaming tweets, and process the incoming data. It requires setting up authentication credentials (Bearer Token or OAuth2) and specifies various optional parameters for filtering and expanding tweet data. The code handles potential API exceptions and parses the streamed JSON responses. ```java // Import classes: import com.twitter.clientlib.ApiClient; import com.twitter.clientlib.ApiException; import com.twitter.clientlib.Configuration; import com.twitter.clientlib.auth.*; import com.twitter.clientlib.model.*; import com.twitter.clientlib.TwitterCredentialsOAuth2; import com.twitter.clientlib.TwitterCredentialsBearer; import com.twitter.clientlib.api.TwitterApi; import com.twitter.clientlib.api.TweetsApi; import java.io.InputStream; import com.google.common.reflect.TypeToken; import java.io.BufferedReader; import java.io.InputStreamReader; import java.lang.reflect.Type; import java.util.List; import java.util.Set; import java.util.Arrays; import java.util.HashSet; import java.time.OffsetDateTime; public class Example { public static void main(String[] args) { // Set the credentials based on the API's "security" tag values. // Check the API definition in https://api.twitter.com/2/openapi.json // When multiple options exist, the SDK supports only "OAuth2UserToken" or "BearerToken" // Uncomment and set the credentials configuration // Configure HTTP bearer authorization: // TwitterCredentialsBearer credentials = new TwitterCredentialsBearer(System.getenv("TWITTER_BEARER_TOKEN")); TwitterApi apiInstance = new TwitterApi(credentials); // Set the params values Integer backfillMinutes = 56; // Integer | The number of minutes of backfill requested. Integer partition = 56; // Integer | The partition number. OffsetDateTime startTime = OffsetDateTime.parse("2021-02-14T18:40:40.000Z"); // OffsetDateTime | YYYY-MM-DDTHH:mm:ssZ. The earliest UTC timestamp to which the Tweets will be provided. OffsetDateTime endTime = OffsetDateTime.parse("2021-02-14T18:40:40.000Z"); // OffsetDateTime | YYYY-MM-DDTHH:mm:ssZ. The latest UTC timestamp to which the Tweets will be provided. Set tweetFields = new HashSet<>(Arrays.asList()); // Set | A comma separated list of Tweet fields to display. Set expansions = new HashSet<>(Arrays.asList()); // Set | A comma separated list of fields to expand. Set mediaFields = new HashSet<>(Arrays.asList()); // Set | A comma separated list of Media fields to display. Set pollFields = new HashSet<>(Arrays.asList()); // Set | A comma separated list of Poll fields to display. Set userFields = new HashSet<>(Arrays.asList()); // Set | A comma separated list of User fields to display. Set placeFields = new HashSet<>(Arrays.asList()); // Set | A comma separated list of Place fields to display. try { InputStream result = apiInstance.tweets().getTweetsSample10Stream(partition) .backfillMinutes(backfillMinutes) .startTime(startTime) .endTime(endTime) .tweetFields(tweetFields) .expansions(expansions) .mediaFields(mediaFields) .pollFields(pollFields) .userFields(userFields) .placeFields(placeFields) .execute(); try{ JSON json = new JSON(); Type localVarReturnType = new TypeToken(){}.getType(); BufferedReader reader = new BufferedReader(new InputStreamReader(result)); String line = reader.readLine(); while (line != null) { if(line.isEmpty()) { System.out.println("==> Empty line"); line = reader.readLine(); continue; } Object jsonObject = json.getGson().fromJson(line, localVarReturnType); System.out.println(jsonObject != null ? jsonObject.toString() : "Null object"); line = reader.readLine(); } }catch (Exception e) { e.printStackTrace(); System.out.println(e); } } catch (ApiException e) { System.err.println("Exception when calling TweetsApi#getTweetsSample10Stream"); System.err.println("Status code: " + e.getCode()); System.err.println("Reason: " + e.getResponseBody()); System.err.println("Response headers: " + e.getResponseHeaders()); e.printStackTrace(); } } } ``` -------------------------------- ### EntityIndicesInclusiveExclusive Source: https://github.com/xdevplatform/twitter-api-java-sdk/blob/main/docs/EntityIndicesInclusiveExclusive.md Represents a boundary range (start and end index) for a recognized entity, such as a hashtag or mention. The start index is inclusive, and the end index is exclusive. The start index must be smaller than the end index. ```APIDOC ## EntityIndicesInclusiveExclusive ### Description Represents a boundary range (start and end index) for a recognized entity (for example a hashtag or a mention). `start` must be smaller than `end`. The start index is inclusive, the end index is exclusive. ### Properties #### start - **start** (Integer) - Required - Index (zero-based) at which position this entity starts. The index is inclusive. #### end - **end** (Integer) - Required - Index (zero-based) at which position this entity ends. The index is exclusive. ### Example ```json { "start": 0, "end": 10 } ``` ``` -------------------------------- ### Get Tweet Compliance Stream using Java Source: https://github.com/xdevplatform/twitter-api-java-sdk/blob/main/docs/ComplianceApi.md This snippet shows how to retrieve a stream of tweet compliance events using the Twitter API Java SDK. It requires setting up authentication (Bearer Token or OAuth2), specifying parameters like partition, backfill minutes, start time, and end time. The response is processed line by line, parsing each compliance event. ```java // Import classes: import com.twitter.clientlib.ApiClient; import com.twitter.clientlib.ApiException; import com.twitter.clientlib.Configuration; import com.twitter.clientlib.auth.*; import com.twitter.clientlib.model.*; import com.twitter.clientlib.TwitterCredentialsOAuth2; import com.twitter.clientlib.TwitterCredentialsBearer; import com.twitter.clientlib.api.TwitterApi; import com.twitter.clientlib.api.ComplianceApi; import java.io.InputStream; import com.google.common.reflect.TypeToken; import java.io.BufferedReader; import java.io.InputStreamReader; import java.lang.reflect.Type; import java.util.List; import java.util.Set; import java.util.Arrays; import java.util.HashSet; import java.time.OffsetDateTime; public class Example { public static void main(String[] args) { // Set the credentials based on the API's "security" tag values. // Check the API definition in https://api.twitter.com/2/openapi.json // When multiple options exist, the SDK supports only "OAuth2UserToken" or "BearerToken" // Uncomment and set the credentials configuration // Configure HTTP bearer authorization: // TwitterCredentialsBearer credentials = new TwitterCredentialsBearer(System.getenv("TWITTER_BEARER_TOKEN")); TwitterApi apiInstance = new TwitterApi(credentials); // Set the params values Integer backfillMinutes = 56; // Integer | The number of minutes of backfill requested. Integer partition = 56; // Integer | The partition number. OffsetDateTime startTime = OffsetDateTime.parse("2021-02-01T18:40:40.000Z"); // OffsetDateTime | YYYY-MM-DDTHH:mm:ssZ. The earliest UTC timestamp from which the Tweet Compliance events will be provided. OffsetDateTime endTime = OffsetDateTime.parse("2021-02-14T18:40:40.000Z"); // OffsetDateTime | YYYY-MM-DDTHH:mm:ssZ. The latest UTC timestamp to which the Tweet Compliance events will be provided. try { InputStream result = apiInstance.compliance().getTweetsComplianceStream(partition) .backfillMinutes(backfillMinutes) .startTime(startTime) .endTime(endTime) .execute(); try{ JSON json = new JSON(); Type localVarReturnType = new TypeToken(){}.getType(); BufferedReader reader = new BufferedReader(new InputStreamReader(result)); String line = reader.readLine(); while (line != null) { if(line.isEmpty()) { System.out.println("==> Empty line"); line = reader.readLine(); continue; } Object jsonObject = json.getGson().fromJson(line, localVarReturnType); System.out.println(jsonObject != null ? jsonObject.toString() : "Null object"); line = reader.readLine(); } }catch (Exception e) { e.printStackTrace(); System.out.println(e); } } catch (ApiException e) { System.err.println("Exception when calling ComplianceApi#getTweetsComplianceStream"); System.err.println("Status code: " + e.getCode()); System.err.println("Reason: " + e.getResponseBody()); System.err.println("Response headers: " + e.getResponseHeaders()); e.printStackTrace(); } } } ``` -------------------------------- ### Create Tweet - Java Source: https://github.com/xdevplatform/twitter-api-java-sdk/blob/main/docs/TweetsApi.md Provides an example of how to create a Tweet using the Twitter API Java SDK. This functionality allows users to post new tweets under their authorized account. The method `createTweet` is called with a `tweetCreateRequest` object to execute the tweet creation. ```java TweetCreateResponse result = apiInstance.tweets().createTweet(tweetCreateRequest).execute(); ``` -------------------------------- ### Initialize TwitterApi with Bearer Token or OAuth 2.0 Authentication Source: https://context7.com/xdevplatform/twitter-api-java-sdk/llms.txt Demonstrates how to initialize the TwitterApi client using either Bearer Token authentication for app-only access or OAuth 2.0 for user-context operations. Requires setting environment variables for credentials. ```java import com.twitter.clientlib.TwitterCredentialsBearer; import com.twitter.clientlib.TwitterCredentialsOAuth2; import com.twitter.clientlib.api.TwitterApi; // Bearer Token Authentication (App-only) TwitterApi apiInstance = new TwitterApi( new TwitterCredentialsBearer(System.getenv("TWITTER_BEARER_TOKEN")) ); // OAuth 2.0 Authentication (User context) 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") ) ); ``` -------------------------------- ### GET /2/users/:id/pinned_lists Source: https://github.com/xdevplatform/twitter-api-java-sdk/blob/main/docs/ListsApi.md Get a User's Pinned Lists. Returns a List of Lists the user has pinned to their profile. ```APIDOC ## GET /2/users/:id/pinned_lists ### Description Get a User's Pinned Lists. Returns a List of Lists the user has pinned to their profile. ### Method GET ### Endpoint /2/users/:id/pinned_lists ### Parameters #### Path Parameters - **id** (String) - Required - The ID of the User for whom to retrieve pinned Lists. #### Query Parameters - **list_fields** (List) - Optional - A comma-separated list of List fields to enhance the response. - **expansions** (List) - Optional - A comma-separated list of additional fields to include in the response. - **user_fields** (List) - Optional - A comma-separated list of User fields to enhance the response. ### Request Example ``` GET https://api.twitter.com/2/users/2244994945/pinned_lists?list_fields=owner_id&expansions=owner_id&user_fields=created_at ``` ### Response #### Success Response (200) - **data** (List) - A list of pinned Lists. - **id** (String) - The ID of the List. - **name** (String) - The name of the List. - **owner_id** (String) - The ID of the user who owns the List. - **includes** (Object) - Contains additional data for fields specified in `expansions`. - **users** (List) - User objects. #### Response Example ```json { "data": [ { "id": "1234567890", "name": "My Pinned List", "owner_id": "2244994945" } ], "includes": { "users": [ { "id": "2244994945", "name": "Twitter Dev", "username": "TwitterDev" } ] } } ``` ### Errors - **400 Bad Request**: The request is malformed or invalid. - **401 Unauthorized**: Authentication information is missing or invalid. - **404 Not Found**: The specified User could not be found. ``` -------------------------------- ### Package Twitter API Java SDK using Maven Source: https://github.com/xdevplatform/twitter-api-java-sdk/blob/main/README.md Generates the JAR file for the Twitter API client library. After packaging, you need to manually install the generated JAR and other library JARs from the 'target/lib/' directory. ```shell mvn clean package ``` -------------------------------- ### GET /2/users/:id/owned_lists Source: https://github.com/xdevplatform/twitter-api-java-sdk/blob/main/docs/ListsApi.md Get a User's Owned Lists. This endpoint retrieves a list of all lists created by a specified user. ```APIDOC ## GET /2/users/:id/owned_lists ### Description Get a User's Owned Lists. This endpoint retrieves a list of all lists created by a specified user. ### Method GET ### Endpoint /2/users/:id/owned_lists ### Parameters #### Path Parameters - **id** (String) - Required - The ID of the user whose owned lists are to be retrieved. #### Query Parameters - **maxResults** (Integer) - Optional - The number of results to retrieve per page. - **paginationToken** (String) - Optional - The token used to retrieve the next page of results. - **listFields** (List) - Optional - A list of fields to be included in the list objects. - **expansions** (List) - Optional - A list of fields to be expanded in the list objects. - **userFields** (List) - Optional - A list of fields to be included in the user objects associated with the lists. #### Request Body None ### Request Example ```java // Example usage (assuming apiInstance is already configured) String id = "user_id_example"; Get2UsersIdOwnedListsResponse result = apiInstance.lists().listUserOwnedLists(id) .maxResults(10) .paginationToken("next_token") .listFields(Arrays.asList("description", "owner_id")) .expansions(Arrays.asList("owner_id")) .userFields(Arrays.asList("created_at")) .execute(); System.out.println(result); ``` ### Response #### Success Response (200) - **Get2UsersIdOwnedListsResponse** (Get2UsersIdOwnedListsResponse) - The response object containing the user's owned lists. #### Response Example ```json { "example": "response body" } ``` ``` -------------------------------- ### GET /2/compliance/users/stream Source: https://github.com/xdevplatform/twitter-api-java-sdk/blob/main/docs/ComplianceApi.md Retrieves a stream of User Compliance events. This endpoint is used to get compliance data related to user information. ```APIDOC ## GET /2/compliance/users/stream ### Description Retrieves a stream of User Compliance events. This endpoint is used to get compliance data related to user information. ### Method GET ### Endpoint /2/compliance/users/stream ### Parameters #### Query Parameters - **partition** (integer) - Required - The partition number. - **backfillMinutes** (integer) - Optional - The number of minutes of backfill requested. - **startTime** (datetime) - Optional - YYYY-MM-DDTHH:mm:ssZ. The earliest UTC timestamp from which the User Compliance events will be provided. - **endTime** (datetime) - Optional - YYYY-MM-DDTHH:mm:ssZ. The latest UTC timestamp from which the User Compliance events will be provided. ### Request Example ```java // Assuming 'apiInstance' is an initialized TwitterApi object Integer backfillMinutes = 56; Integer partition = 56; OffsetDateTime startTime = OffsetDateTime.parse("2021-02-01T18:40:40.000Z"); OffsetDateTime endTime = OffsetDateTime.parse("2021-02-01T18:40:40.000Z"); InputStream result = apiInstance.compliance().getUsersComplianceStream(partition) .backfillMinutes(backfillMinutes) .startTime(startTime) .endTime(endTime) .execute(); ``` ### Response #### Success Response (200) - **UserComplianceStreamResponse** (object) - A stream of User Compliance events. #### Response Example ```json { "event_id": "1234567890", "event_type": "user_delete", "timestamp": "2021-02-01T18:40:40.000Z", "payload": { "user_id": "12345" } } ``` ### Authorization BearerToken ``` -------------------------------- ### Create Tweet using Twitter API Java SDK Source: https://github.com/xdevplatform/twitter-api-java-sdk/blob/main/docs/TweetsApi.md Demonstrates how to create a new tweet using the Twitter API Java SDK. It requires setting up OAuth2 or Bearer token credentials and handles potential API exceptions. The input is a TweetCreateRequest object, and the output is a TweetCreateResponse. ```java // Import classes: import com.twitter.clientlib.ApiClient; import com.twitter.clientlib.ApiException; import com.twitter.clientlib.Configuration; import com.twitter.clientlib.auth.*; import com.twitter.clientlib.model.*; import com.twitter.clientlib.TwitterCredentialsOAuth2; import com.twitter.clientlib.TwitterCredentialsBearer; import com.twitter.clientlib.api.TwitterApi; import com.twitter.clientlib.api.TweetsApi; import java.util.List; import java.util.Set; import java.util.Arrays; import java.util.HashSet; import java.time.OffsetDateTime; public class Example { public static void main(String[] args) { // Set the credentials based on the API's "security" tag values. // Check the API definition in https://api.twitter.com/2/openapi.json // When multiple options exist, the SDK supports only "OAuth2UserToken" or "BearerToken" // Uncomment and set the credentials configuration // Configure OAuth2 access token for authorization: // 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")); TwitterApi apiInstance = new TwitterApi(credentials); // Set the params values TweetCreateRequest tweetCreateRequest = new TweetCreateRequest(); // TweetCreateRequest | 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(); } } } ``` -------------------------------- ### GET /2/users/:id/mentions Source: https://github.com/xdevplatform/twitter-api-java-sdk/blob/main/docs/TweetsApi.md Retrieves a timeline of Tweets that mention the user specified by the ID. ```APIDOC ## GET /2/users/:id/mentions ### Description Returns Tweet objects that mention the user specified by the ID. ### Method GET ### Endpoint /2/users/:id/mentions ### Parameters #### Path Parameters - **id** (String) - Required - The ID of the User to lookup. #### Query Parameters - **since_id** (String) - Optional - Returns results that have the ID specified. - **until_id** (String) - Optional - Returns results that have the ID specified. - **maxResults** (Integer) - Optional - The maximum number of results. - **paginationToken** (String) - Optional - This parameter is used to get the next 'page' of results. - **startTime** (String) - Optional - Returns results posted after this timestamp. - **endTime** (String) - Optional - Returns results posted before this timestamp. - **tweetFields** (Set) - Optional - A comma separated list of Tweet fields to display. [enum: attachments, author_id, context_annotations, conversation_id, created_at, edit_controls, edit_history_tweet_ids, entities, geo, id, in_reply_to_user_id, lang, non_public_metrics, organic_metrics, possibly_sensitive, promoted_metrics, public_metrics, referenced_tweets, reply_settings, source, text, withheld] - **expansions** (Set) - Optional - A comma separated list of fields to expand. [enum: attachments.media_keys, attachments.poll_ids, author_id, edit_history_tweet_ids, entities.mentions.username, geo.place_id, in_reply_to_user_id, referenced_tweets.id, referenced_tweets.id.author_id] - **mediaFields** (Set) - Optional - A comma separated list of Media fields to display. [enum: alt_text, duration_ms, height, media_key, non_public_metrics, organic_metrics, preview_image_url, promoted_metrics, public_metrics, type, url, variants, width] - **pollFields** (Set) - Optional - A comma separated list of Poll fields to display. [enum: duration_minutes, end_datetime, id, options, voting_status] - **userFields** (Set) - Optional - A comma separated list of User fields to display. [enum: created_at, description, entities, id, location, name, pinned_tweet_id, profile_image_url, protected, public_metrics, url, username, verified, withheld] - **placeFields** (Set) - Optional - A comma separated list of Place fields to display. [enum: contained_within, country, country_code, full_name, geo, id, name, place_type] ### Request Body None ### Response #### Success Response (200) - **data** (Array[Tweet]) - The Tweet objects. - **includes** (Object) - Included sub-resources like users, media, polls, etc. - **meta** (Object) - Metadata about the response. - **errors** (Array[Problem]) - Errors encountered during the request. #### Response Example { "data": [ { "id": "1234567890123456789", "text": "This is a tweet mentioning you!" } ], "meta": { "newest_id": "1234567890123456789", "oldest_id": "1234567890123456789", "result_count": 1 } } #### Error Response (0) - **errors** (Array[Problem]) - Errors encountered during the request. ``` -------------------------------- ### Deploy Twitter API Java SDK using Maven Source: https://github.com/xdevplatform/twitter-api-java-sdk/blob/main/README.md Deploys the Twitter API client library to a remote Maven repository. This requires configuring repository settings. Ensure you have the necessary permissions and configurations for your remote repository. ```shell mvn clean deploy ``` -------------------------------- ### Follow a List using Twitter API Java SDK Source: https://github.com/xdevplatform/twitter-api-java-sdk/blob/main/docs/ListsApi.md This Java code snippet demonstrates how to follow a list using the Twitter API Java SDK. It requires setting up OAuth2 credentials and making a call to the `listUserFollow` method of the `ListsApi`. The input includes a user ID and an optional `ListFollowedRequest` object. The output is a `ListFollowedResponse` or an `ApiException` if the call fails. ```java // Import classes: import com.twitter.clientlib.ApiClient; import com.twitter.clientlib.ApiException; import com.twitter.clientlib.Configuration; import com.twitter.clientlib.auth.*; import com.twitter.clientlib.model.*; import com.twitter.clientlib.TwitterCredentialsOAuth2; import com.twitter.clientlib.TwitterCredentialsBearer; import com.twitter.clientlib.api.TwitterApi; import com.twitter.clientlib.api.ListsApi; import java.util.List; import java.util.Set; import java.util.Arrays; import java.util.HashSet; import java.time.OffsetDateTime; public class Example { public static void main(String[] args) { // Set the credentials based on the API's "security" tag values. // Check the API definition in https://api.twitter.com/2/openapi.json // When multiple options exist, the SDK supports only "OAuth2UserToken" or "BearerToken" // Uncomment and set the credentials configuration // Configure OAuth2 access token for authorization: // 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")); TwitterApi apiInstance = new TwitterApi(credentials); // Set the params values ListFollowedRequest listFollowedRequest = new ListFollowedRequest(); // ListFollowedRequest | String id = "id_example"; // String | The ID of the authenticated source User that will follow the List. try { ListFollowedResponse result = apiInstance.lists().listUserFollow(id) .listFollowedRequest(listFollowedRequest) .execute(); System.out.println(result); } catch (ApiException e) { System.err.println("Exception when calling ListsApi#listUserFollow"); System.err.println("Status code: " + e.getCode()); System.err.println("Reason: " + e.getResponseBody()); System.err.println("Response headers: " + e.getResponseHeaders()); e.printStackTrace(); } } } ``` -------------------------------- ### GET /2/lists/:id/tweets Source: https://github.com/xdevplatform/twitter-api-java-sdk/blob/main/docs/TweetsApi.md Returns a list of Tweets associated with the provided List ID. ```APIDOC ## GET /2/lists/:id/tweets ### Description List Tweets timeline by List ID. Returns a list of Tweets associated with the provided List ID. ### Method GET ### Endpoint /2/lists/:id/tweets ### Parameters #### Path Parameters - **id** (String) - Required - The ID of the List whose Tweets you would like to retrieve. #### Query Parameters - **maxResults** (Integer) - Optional - The maximum number of results to be returned. - **paginationToken** (String) - Optional - Used to retrieve the next page of results. - **tweetFields** (List) - Optional - A comma separated list of Tweet fields to include in the response. - **expansions** (List) - Optional - A comma separated list of fields to expand. - **mediaFields** (List) - Optional - A comma separated list of Media fields to include in the response. - **pollFields** (List) - Optional - A comma separated list of Poll fields to include in the response. - **userFields** (List) - Optional - A comma separated list of User fields to include in the response. - **placeFields** (List) - Optional - A comma separated list of Place fields to include in the response. #### Request Body None ### Request Example None ### Response #### Success Response (200) - **data** (List) - A list of Tweet objects. - **meta** (Get2ListsIdTweetsResponseMeta) - Metadata for the response. - **includes** (Get2ListsIdTweetsResponseIncludes) - Expanded data objects. #### Response Example ```json { "data": [ { "id": "1460323737035677698", "text": "The first Tweet of the thread." }, { "id": "1460323747440779264", "text": "The second Tweet of the thread." } ], "meta": { "result_count": 2 } } ``` ``` -------------------------------- ### GET /2/users/by Source: https://github.com/xdevplatform/twitter-api-java-sdk/blob/main/docs/UsersApi.md Retrieves multiple users' information by their usernames. ```APIDOC ## GET /2/users/by ### Description User lookup by usernames. ### Method GET ### Endpoint /2/users/by ### Parameters #### Query Parameters - **usernames** (string) - Required - A comma-separated list of usernames. - **user_fields** (string) - Optional - Fields to include in the user object. - **expansions** (string) - Optional - Fields to expand in the response. - **tweet_fields** (string) - Optional - Fields to include in the user's tweets. ### Response #### Success Response (200) - **data** (array) - An array of user objects. - **includes** (object) - Included objects based on expansions. #### Response Example ```json { "data": [ { "id": "12345", "name": "Example User 1", "username": "exampleuser1" }, { "id": "67890", "name": "Example User 2", "username": "exampleuser2" } ] } ``` ``` -------------------------------- ### Create List using Twitter API Java SDK Source: https://github.com/xdevplatform/twitter-api-java-sdk/blob/main/docs/ListsApi.md Demonstrates how to create a list using the Twitter API Java SDK. It requires authentication credentials (OAuth2 or Bearer Token) and accepts a ListCreateRequest object. The output is a ListCreateResponse object or an ApiException if the request fails. ```java // Import classes: import com.twitter.clientlib.ApiClient; import com.twitter.clientlib.ApiException; import com.twitter.clientlib.Configuration; import com.twitter.clientlib.auth.*; import com.twitter.clientlib.model.*; import com.twitter.clientlib.TwitterCredentialsOAuth2; import com.twitter.clientlib.TwitterCredentialsBearer; import com.twitter.clientlib.api.TwitterApi; import com.twitter.clientlib.api.ListsApi; import java.util.List; import java.util.Set; import java.util.Arrays; import java.util.HashSet; import java.time.OffsetDateTime; public class Example { public static void main(String[] args) { // Set the credentials based on the API's "security" tag values. // Check the API definition in https://api.twitter.com/2/openapi.json // When multiple options exist, the SDK supports only "OAuth2UserToken" or "BearerToken" // Uncomment and set the credentials configuration // Configure OAuth2 access token for authorization: // 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")); TwitterApi apiInstance = new TwitterApi(credentials); // Set the params values ListCreateRequest listCreateRequest = new ListCreateRequest(); // ListCreateRequest | try { ListCreateResponse result = apiInstance.lists().listIdCreate() .listCreateRequest(listCreateRequest) .execute(); System.out.println(result); } catch (ApiException e) { System.err.println("Exception when calling ListsApi#listIdCreate"); System.err.println("Status code: " + e.getCode()); System.err.println("Reason: " + e.getResponseBody()); System.err.println("Response headers: " + e.getResponseHeaders()); e.printStackTrace(); } } } ``` -------------------------------- ### GET /2/users/me Source: https://github.com/xdevplatform/twitter-api-java-sdk/blob/main/docs/UsersApi.md Retrieves information about the currently authenticated user. ```APIDOC ## GET /2/users/me ### Description This endpoint returns information about the requesting User. ### Method GET ### Endpoint /2/users/me ### Parameters #### Query Parameters - **user_fields** (string) - Optional - Fields to include in the user object. - **expansions** (string) - Optional - Fields to expand in the response. - **tweet_fields** (string) - Optional - Fields to include in the user's tweets. ### Response #### Success Response (200) - **data** (object) - User object. - **includes** (object) - Included objects based on expansions. #### Response Example ```json { "data": { "id": "12345", "name": "Example User", "username": "exampleuser" } } ``` ``` -------------------------------- ### Stream Live Tweets using Twitter API Java SDK Source: https://context7.com/xdevplatform/twitter-api-java-sdk/llms.txt This example shows how to set up a real-time stream for monitoring tweets using the Twitter API Java SDK. It utilizes `TweetsStreamListenersExecutor` and `StreamingTweetHandlerImpl`. The stream continues until an error occurs, and it requires a bearer token for authentication. ```java import com.twitter.clientlib.TweetsStreamListenersExecutor; import com.twitter.clientlib.StreamingTweetHandlerImpl; TwitterApi apiInstance = new TwitterApi( new TwitterCredentialsBearer(System.getenv("TWITTER_BEARER_TOKEN")) ); try { TweetsStreamListenersExecutor tsle = new TweetsStreamListenersExecutor(); tsle.stream() .streamingHandler(new StreamingTweetHandlerImpl(apiInstance)) .executeListeners(); // Keep streaming until error occurs while (tsle.getError() == null) { try { System.out.println("Streaming... sleeping 5 seconds"); Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } } if (tsle.getError() != null) { System.err.println("Stream ended with error: " + tsle.getError()); } // Graceful shutdown // tsle.shutdown(); } catch (ApiException e) { System.err.println("Streaming error: " + e.getResponseBody()); e.printStackTrace(); } ```