Home

Awesome

<p align="center"> <a href="https://github.com/twitter-dart/twitter-api-v2"> <img alt="twitter_api_v2" width="600px" src="https://user-images.githubusercontent.com/13072231/199728866-202b9742-d58e-4667-b046-e8096efd2339.png"> </a> </p> <p align="center"> <b>The Most Famous and Powerful Dart/Flutter Library for Twitter API v2.0 🐦</b> </p>

Awesome GitHub Sponsor GitHub Sponsor

v2 pub package Dart SDK Version Test Analyzer codecov Issues Pull Requests Stars Contributors Code size Last Commits License Contributor Covenant FOSSA Status


| English | 日本語 | Français | Tiếng Việt | বাংলা | Español | Deutsch | Português | 简体中文 |


<!-- TOC --> <!-- /TOC -->

1. Guide 🌎

This library provides the easiest way to use Twitter API v2.0 in Dart and Flutter apps.

Show some ❤️ and star the repo to support the project.

We also provide twitter_oauth2_pkce for easy OAuth 2.0 PKCE authentication when using the Twitter API!

Also, this library is listed in the Official Twitter page 🐦

1.1. Features 💎

✅ The wrapper library for Twitter API v2.0. </br>Easily integrates with the Dart & Flutter apps. </br> ✅ Provides response objects with a guaranteed safe types. </br> ✅ Supports all endpoints. </br> ✅ Support all request parameters and response fields.</br> ✅ Supports high-performance streaming endpoints. </br> ✅ Supports expansions and fields features. </br>Well documented and well tested.</br> ✅ Supports the powerful automatic retry.</br> ✅ Supports for large media uploads (image, gif, video).</br> ✅ Supports safe and powerful paging feature.

1.2. Getting Started ⚡

1.2.1. Install Library

With Dart:

 dart pub add twitter_api_v2

Or With Flutter:

 flutter pub add twitter_api_v2

1.2.2. Import

import 'package:twitter_api_v2/twitter_api_v2';

1.2.3. Implementation

import 'dart:async';
import 'dart:io';

import 'package:twitter_api_v2/twitter_api_v2.dart' as v2;

Future<void> main() async {
  //! You need to get keys and tokens at https://developer.twitter.com
  final twitter = v2.TwitterApi(
    //! Authentication with OAuth2.0 is the default.
    //!
    //! Note that to use endpoints that require certain user permissions,
    //! such as Tweets and Likes, you need a token issued by OAuth2.0 PKCE.
    //!
    //! The easiest way to achieve authentication with OAuth 2.0 PKCE is
    //! to use [twitter_oauth2_pkce](https://pub.dev/packages/twitter_oauth2_pkce)!
    bearerToken: 'YOUR_TOKEN_HERE',

    //! Or perhaps you would prefer to use the good old OAuth1.0a method
    //! over the OAuth2.0 PKCE method. Then you can use the following code
    //! to set the OAuth1.0a tokens.
    //!
    //! However, note that some endpoints cannot be used for OAuth 1.0a method
    //! authentication.
    oauthTokens: v2.OAuthTokens(
      consumerKey: 'YOUR_CONSUMER_KEY_HERE',
      consumerSecret: 'YOUR_CONSUMER_SECRET_HERE',
      accessToken: 'YOUR_ACCESS_TOKEN_HERE',
      accessTokenSecret: 'YOUR_ACCESS_TOKEN_SECRET_HERE',
    ),

    //! Automatic retry is available when network error or server error
    //! are happened.
    retryConfig: v2.RetryConfig(
      maxAttempts: 5,
      onExecute: (event) => print(
        'Retry after ${event.intervalInSeconds} seconds... '
        '[${event.retryCount} times]',
      ),
    ),

    //! The default timeout is 10 seconds.
    timeout: Duration(seconds: 20),
  );

  try {
    //! Get the authenticated user's profile.
    final me = await twitter.users.lookupMe();
    //! Get the tweets associated with the search query.
    final tweets = await twitter.tweets.searchRecent(
      query: '#ElonMusk',
      maxResults: 20,
      // You can expand the search result.
      expansions: [
        v2.TweetExpansion.authorId,
        v2.TweetExpansion.inReplyToUserId,
      ],
      tweetFields: [
        v2.TweetField.conversationId,
        v2.TweetField.publicMetrics,
        v2.TweetField.editControls,
      ],
      userFields: [
        v2.UserField.location,
        v2.UserField.verified,
        v2.UserField.entities,
        v2.UserField.publicMetrics,
      ],

      //! Safe paging is easy to implement.
      paging: (event) {
        print(event.response);

        if (event.count == 3) {
          return v2.ForwardPaginationControl.stop();
        }

        return v2.ForwardPaginationControl.next();
      },
    );

    //! You can serialize & deserialize JSON from response object
    //! and model object.
    final tweetJson = tweets.data.first.toJson();
    final tweet = v2.TweetData.fromJson(tweetJson);
    print(tweet);

    await twitter.tweets.createLike(
      userId: me.data.id,
      tweetId: tweets.data.first.id,
    );

    //! You can upload media such as image, gif and video.
    final uploadedMedia = await twitter.media.uploadMedia(
      file: File.fromUri(Uri.file('FILE_PATH')),
      altText: 'This is alt text.',

      //! You can check the upload progress.
      onProgress: (event) {
        switch (event.state) {
          case v2.UploadState.preparing:
            print('Upload is preparing...');
            break;
          case v2.UploadState.inProgress:
            print('${event.progress}% completed...');
            break;
          case v2.UploadState.completed:
            print('Upload has completed!');
            break;
        }
      },
      onFailed: (error) => print('Upload failed due to "${error.message}"'),
    );

    //! You can easily post a tweet with the uploaded media.
    await twitter.tweets.createTweet(
      text: 'Tweet with uploaded media',
      media: v2.TweetMediaParam(
        mediaIds: [uploadedMedia.data.id],
      ),
    );

    //! High-performance Volume Stream endpoint is available.
    final sampleStream = await twitter.tweets.connectSampleStream();
    await for (final response in sampleStream.stream.handleError(print)) {
      print(response);
    }

    //! Also high-performance Filtered Stream endpoint is available.
    await twitter.tweets.createFilteringRules(
      rules: [
        v2.FilteringRuleParam(value: '#ElonMusk'),

        //! You can easily build filtering rule using by "FilteringRule" object.
        v2.FilteringRuleParam(
          //! => #Tesla has:media
          value: v2.FilteringRule.of()
              .matchHashtag('Tesla')
              .and()
              .matchTweetContainsMedia()
              .build(),
        ),
        v2.FilteringRuleParam(
          //! => (#SpaceX has:media) OR (#SpaceX has:hashtags) sample:50
          value: v2.FilteringRule.ofSample(percent: 50)
              .group(
                v2.FilteringRule.of()
                    .matchHashtag('SpaceX')
                    .and()
                    .matchTweetContainsMedia(),
              )
              .or()
              .group(
                v2.FilteringRule.of()
                    .matchHashtag('SpaceX')
                    .and()
                    .matchTweetContainsHashtags(),
              )
              .build(),
        ),
      ],
    );

    final filteredStream = await twitter.tweets.connectFilteredStream();
    await for (final response in filteredStream.stream.handleError(print)) {
      print(response.data);
      print(response.matchingRules);
    }
  } on TimeoutException catch (e) {
    print(e);
  } on v2.UnauthorizedException catch (e) {
    print(e);
  } on v2.RateLimitExceededException catch (e) {
    print(e);
  } on v2.DataNotFoundException catch (e) {
    print(e);
  } on v2.TwitterUploadException catch (e) {
    print(e);
  } on v2.TwitterException catch (e) {
    print(e.response.headers);
    print(e.body);
    print(e);
  }}

1.3. Supported Endpoints 👀

1.3.1. Tweets Service

1.3.1.1. Tweet

EndpointMethod Name
POST /2/tweetscreateTweet
DELETE /2/tweets/:iddestroyTweet

1.3.1.2. Likes

EndpointMethod Name
POST /2/users/:id/likescreateLike
DELETE /2/users/:id/likes/:tweet_iddestroyLike
GET /2/tweets/:id/liking_userslookupLikingUsers
GET /2/users/:id/liked_tweetslookupLikedTweets

1.3.1.3. Retweets

EndpointMethod Name
POST /2/users/:id/retweetscreateRetweet
DELETE /2/users/:id/retweets/:source_tweet_iddestroyRetweet
GET /2/tweets/:id/retweeted_bylookupRetweetedUsers

1.3.1.4. Quote Tweets

EndpointMethod Name
GET /2/tweets/:id/quote_tweetslookupQuoteTweets

1.3.1.5. Search Tweets

EndpointMethod Name
GET /2/tweets/search/allsearchAll
GET /2/tweets/search/recentsearchRecent

1.3.1.6. Lookup Tweets

EndpointMethod Name
GET /2/tweetslookupByIds
GET /2/tweets/:idlookupById

1.3.1.7. Tweet Counts

EndpointMethod Name
GET /2/tweets/counts/allcountAll
GET /2/tweets/counts/recentcountRecent

1.3.1.8. Bookmarks

EndpointMethod Name
POST /2/users/:id/bookmarkscreateBookmark
DELETE /2/users/:id/bookmarks/:tweet_iddestroyBookmark
GET /2/users/:id/bookmarkslookupBookmarks

1.3.1.9. Timelines

EndpointMethod Name
GET /2/users/:id/mentionslookupMentions
GET /2/users/:id/tweetslookupTweets
GET /2/users/:id/timelines/reverse_chronologicallookupHomeTimeline

1.3.1.10. Hide Replies

EndpointMethod Name
PUT /2/tweets/:id/hiddencreateHiddenReply
PUT /2/tweets/:id/hiddendestroyHiddenReply

1.3.1.11. Volume Stream

EndpointMethod Name
GET /2/tweets/sample/streamconnectSampleStream
GET /2/tweets/sample10/streamconnectSample10Stream

1.3.1.12. Filtered Stream

EndpointMethod Name
POST /2/tweets/search/stream/rulescreateFilteringRules
GET /2/tweets/search/stream/ruleslookupFilteringRules
GET /2/tweets/search/streamconnectFilteredStream

1.3.2. Users Service

1.3.2.1. Follows

EndpointMethod Name
POST /2/users/:id/followingcreateFollow
DELETE /2/users/:source_user_id/following/:target_user_iddestroyFollow
GET /2/users/:id/followerslookupFollowers
GET /2/users/:id/followinglookupFollowings

1.3.2.2. Lookup Users

EndpointMethod Name
GET /2/userslookupByIds
GET /2/users/:idlookupById
GET /2/users/bylookupByNames
GET /2/users/by/username/:usernamelookupByName
GET /2/users/melookupMe

1.3.2.3. Users Mutes

EndpointMethod Name
POST /2/users/:id/mutingcreateMute
DELETE /2/users/:source_user_id/muting/:target_user_iddestroyMute
GET /2/users/:id/mutinglookupMutingUsers

1.3.2.4. Blocks

EndpointMethod Name
POST /2/users/:id/blockingcreateBlock
DELETE /2/users/:source_user_id/blocking/:target_user_iddestroyBlock
GET /2/users/:id/blockinglookupBlockingUsers

1.3.2.5. User Profile

Note</br> Twitter API v1.1 endpoint is used because Twitter Official does not yet release the endpoints to manage user profile for Twitter API v2.0. Therefore, this service may be changed in the future.

EndpointMethod Name
POST /1.1/account/update_profile.jsonupdateProfile
POST /1.1/account/update_profile_image.jsonupdateProfileImage
POST /1.1/account/update_profile_banner.jsonupdateProfileBanner
POST /1.1/account/remove_profile_banner.jsondestroyProfileBanner
GET users/profile_banner.jsonlookupProfileBannerById
GET users/profile_banner.jsonlookupProfileBannerByName

1.3.2.6. Report Spam

Note</br> Twitter API v1.1 endpoint is used because Twitter Official does not yet release the endpoints to report spam for Twitter API v2.0. Therefore, this service may be changed in the future.

EndpointMethod Name
POST /1.1/users/report_spam.jsoncreateReportById
POST /1.1/users/report_spam.jsoncreateReportByName

1.3.3. Spaces Service

1.3.3.1. Search Spaces

EndpointMethod Name
GET /2/spaces/searchsearch

1.3.3.2. Lookup Spaces

EndpointMethod Name
GET /2/spaceslookupByIds
GET /2/spaces/:idlookupById
GET /2/spaces/:id/buyerslookupBuyers
GET /2/spaces/:id/tweetslookupTweets
GET /2/spaces/by/creator_idslookupByCreatorIds

1.3.4. Lists Service

1.3.4.1. Lookup Lists

EndpointMethod Name
GET /2/lists/:idlookupById
GET /2/users/:id/owned_listslookupOwnedBy

1.3.4.2. Pinnings

EndpointMethod Name
POST /2/users/:id/pinned_listscreatePinnedList
DELETE /2/users/:id/pinned_lists/:list_iddestroyPinnedList
GET /2/users/:id/pinned_listslookupPinnedLists

1.3.4.3. Tweet Lookup

EndpointMethod Name
GET /2/lists/:id/tweetslookupTweets

1.3.4.4. List Manage

EndpointMethod Name
POST /2/listscreatePublicList
POST /2/listscreatePrivateList
DELETE /2/lists/:iddestroyList
PUT /2/lists/:idupdateListAsPublic
PUT /2/lists/:idupdateListAsPrivate

1.3.4.5. Follows

EndpointMethod Name
POST /2/users/:id/followed_listscreateFollow
DELETE /2/users/:id/followed_lists/:list_iddestroyFollow
GET /2/lists/:id/followerslookupFollowers
GET /2/users/:id/followed_listslookupFollowedLists

1.3.4.6. Members

EndpointMethod Name
POST /2/lists/:id/memberscreateMember
DELETE /2/lists/:id/members/:user_iddestroyMember
GET /2/lists/:id/memberslookupMembers
GET /2/users/:id/list_membershipslookupMemberships

1.3.5. Media Service

Note</br> Twitter API v1.1 endpoint is used because Twitter Official does not yet release the Media endpoint for Twitter API v2.0. Therefore, this service may be changed in the future.

1.3.5.1. Upload Media

EndpointMethod Name
POST /1.1/media/upload.jsonuploadImage
POST /1.1/media/upload.json (INIT)</br>POST /1.1/media/upload.json (APPEND)</br>POST /1.1/media/upload.json (FINALIZE)</br>POST /1.1/media/upload.json (STATUS)</br>uploadMedia

1.3.6. Direct Messages Service

1.3.6.1. Lookup Event

EndpointMethod Name
GET /2/dm_eventslookupEvents
GET /2/dm_conversations/with/:participant_id/dm_eventslookupEventsWith
GET /2/dm_conversations/:dm_conversation_id/dm_eventslookupEventsIn

1.3.6.2. Manage Event

EndpointMethod Name
POST /2/dm_conversations/with/:participant_id/messagescreateConversation
POST /2/dm_conversationscreateGroupConversation
POST /2/dm_conversations/:dm_conversation_id/messagescreateMessage

1.3.7. Geo Service

Note</br> Twitter API v1.1 endpoint is used because Twitter Official does not yet release the Geo endpoint for Twitter API v2.0. Therefore, this service may be changed in the future.

1.3.7.1. Lookup Place

EndpointMethod Name
GET /1.1/geo/id/:placeId.jsonlookupById
GET /1.1/geo/reverse_geocode.jsonlookupReverseGeocodedLocations

1.3.7.2. Search Locations

EndpointMethod Name
GET /1.1/geo/search.jsonsearchLocations

1.3.8. Trends Service

Note</br> Twitter API v1.1 endpoint is used because Twitter Official does not yet release the Trends endpoint for Twitter API v2.0. Therefore, this service may be changed in the future.

1.3.8.1. Trending Location

EndpointMethod Name
GET /1.1/trends/available.jsonsearchAvailableLocations
GET /1.1/trends/closest.jsonsearchClosestLocations

1.3.8.2. Trend

EndpointMethod Name
GET /1.1/trends/place.jsonlookupTrends

1.3.9. Compliance Service

1.3.9.1. Batch Compliance

EndpointMethod Name
POST /2/compliance/jobscreateJob
GET /2/compliance/jobslookupJobs
GET /2/compliance/jobs/:idlookupJob

1.4. Tips 🏄

1.4.1. Method Names

twitter_api_v2 uses the following standard prefixes depending on endpoint characteristics. So it's very easy to find the method corresponding to the endpoint you want to use!

PrefixDescription
lookupThis prefix is attached to endpoints that reference tweets, users, etc.
searchThis prefix is attached to endpoints that perform extensive searches.
connectThis prefix is attached to endpoints with high-performance streaming.
countThis prefix is attached to the endpoint that counts a particular item.
createThis prefix is attached to the endpoint performing the create state such as Tweet and Follow.
destroyThis prefix is attached to the endpoint performing the destroy state such as Tweet and Follow.
updateThis prefix is attached to the endpoint performing the update state.
uploadThis prefix is attached to the endpoint performing the media uploading.

1.4.2. Automatic REST Client Resolution

Some of the Twitter API v2.0 endpoints support OAuth 1.0a method of authentication in parallel while assuming OAuth 2.0.

twitter_api_v2 also supports this specification and provides a mechanism to automatically resolve the REST client for HTTP communication depending on the state and type of token specified when creating an instance of the TwitterApi object.

This is resolved by the following rules.

WhenbearerToken.isEmptybearerToken.isNotEmpty
oauthTokens.isEmptyUnauthorizedExceptionOAuth 2.0
oauthTokens.isNotEmptyOAuth 1.0aOAuth 2.0
WhenbearerToken.isEmptybearerToken.isNotEmpty
oauthTokens.isEmptyUnauthorizedExceptionUnauthorizedException
oauthTokens.isNotEmptyOAuth 1.0aOAuth 1.0a

1.4.3. Generate App-Only Bearer Token

twitter_api_v2 provides utility to generate/find your app-only bearer token.

import 'package:twitter_api_v2/twitter_api_v2.dart' as v2;

Future<void> main() async {
  final bearerToken = await v2.OAuthUtils.generateAppOnlyBearerToken(
    consumerKey: 'YOUR_CONSUMER_KEY',
    consumerSecret: 'YOUR_CONSUMER_SECRET',
  );

  print(bearerToken);
}

1.4.4. Refresh Access Token

The advantage of access tokens issued by OAuth 2.0 PKCE is not only security, but also the ability to determine user access permissions in detail. However, the lifespan of this access token is short, expiring in about 2 hours.

And then, the refresh token is a mechanism to solve this problem. Refresh token can be used to reissue your expired access token.

You can implement it as follows.

import 'package:twitter_api_v2/twitter_api_v2.dart' as v2;

Future<void> main() async {
  final response = await v2.OAuthUtils.refreshAccessToken(
    clientId: 'YOUR_CLIENT_ID',
    clientSecret: 'YOUR_CLIENT_SECRET',
    refreshToken: 'REFRESH_TOKEN_YOU_GOT',
  );

  print(response.accessToken);
  print(response.refreshToken);
}

Note:</br> If you are looking for a way to authenticate with OAuth 2.0 PKCE, use twitter_oauth2_pkce.</br> The refresh token is returned together with the access token by specifying the offline.access scope to the Twitter authentication server.

1.4.5. Null Parameter at Request

In this library, parameters that are not required at request time, i.e., optional parameters, are defined as nullable. However, developers do not need to be aware of the null parameter when sending requests when using this library.

It means the parameters specified with a null value are safely removed and ignored before the request is sent.

For example, arguments specified with null are ignored in the following request.

import 'package:twitter_api_v2/twitter_api_v2.dart' as v2;

Future<void> main() async {
  final twitter = v2.TwitterApi(bearerToken: 'YOUR_TOKEN_HERE');

  await twitter.tweets.createTweet(
    text: 'Hello, World!',
    // These parameters are ignored at request because they are null.
    mediaIds: null,
    expansions: null,
  );
}

1.4.6. Expand Object Fields with expansions

For example, there may be a situation where data contains only an ID, and you want to retrieve the data object associated with that ID as well. In such cases, the Twitter API v2.0 specification called expansions is useful, and this library supports that specification.

Basically it can be used in endpoints that perform GET communication such as lookup and search processing. Some fields may also be included in the includes property of TwitterResponse.

You can use expansions like below:

import 'package:twitter_api_v2/twitter_api_v2.dart' as v2;

Future<void> main() async {
  final twitter = v2.TwitterApi(bearerToken: 'YOUR_TOKEN_HERE');

  try {
    final tweets = await twitter.tweets.searchRecent(
      query: '#ElonMusk',
      // Specify fields you need!
      expansions: [
        v2.TweetExpansion.authorId,
        v2.TweetExpansion.inReplyToUserId,
      ],
    );

    print(tweets);
  } on v2.TwitterException catch (e) {
    print(e);
  }
}

You can see more details about expansions from Official Documentation.

1.4.7. Expand Object Fields with fields

Twitter API v2.0 supports a very interesting specification, allowing users to control the amount of data contained in the response object for each endpoint depending on the situation. It's called fields, and this library supports this specification.

Basically it can be used in endpoints that perform GET communication such as lookup and search processing. Some fields may also be included in the includes field of TwitterResponse.

You can use fields like below:

import 'package:twitter_api_v2/twitter_api_v2.dart' as v2;

Future<void> main() async {
  final twitter = v2.TwitterApi(bearerToken: 'YOUR_TOKEN_HERE');

  try {
    final tweets = await twitter.tweets.searchRecent(
      query: '#ElonMusk',
      maxResults: 20,
      expansions: v2.TweetExpansion.values,
      tweetFields: [
        v2.TweetField.conversationId,
        v2.TweetField.publicMetrics,
      ],
      userFields: [
        v2.UserField.location,
        v2.UserField.publicMetrics,
      ],
    );

    print(tweets);
  } on v2.TwitterException catch (e) {
    print(e);
  }
}

Note</br> Some fields must be combined with expansions.

You can see more details about fields from Official Documentation.

1.4.8. JSON Serialization and Deserialization

All Twitter API responses obtained using twitter_api_v2 are returned stored in a safe type object. However, there may be cases where the raw JSON returned from the Twitter API is needed when creating applications in combination with other libraries.

In that case, you can use the toJson method provided by the TwitterResponse or other model objects to convert it to the raw JSON format returned by the Twitter API.

The JSON converted by this toJson method is completely equivalent to the JSON returned by the Twitter API and can be deserialized by using the factory constructor fromJson provided with each model object.

import 'package:twitter_api_v2/twitter_api_v2.dart' as v2;

Future<void> main() async {
  final twitter = v2.TwitterApi(bearerToken: 'YOUR_BEARER_TOKEN');

  try {
    final response = await twitter.tweets.searchRecent(
      query: '#ElonMusk',
      maxResults: 10,
      expansions: v2.TweetExpansion.values,
    );

    //! You can get raw JSON from this response.
    print(response.toJson());

    //! Or you can get raw JSON from specific model object.
    print(response.data.first.toJson());
  } on v2.TwitterException catch (e) {
    print(e);
  }
}

You could also write like:

import 'package:twitter_api_v2/twitter_api_v2.dart' as v2;

Future<void> main() async {
  final twitter = v2.TwitterApi(bearerToken: 'YOUR_BEARER_TOKEN');

  try {
    final response = await twitter.tweets.searchRecent(
      query: '#ElonMusk',
      maxResults: 10,
      expansions: v2.TweetExpansion.values,
    );

    //! Serialize & Deserialize
    final tweetJson = response.data.first.toJson();
    final tweet = v2.TweetData.fromJson(tweetJson);

    print(tweet);
  } on v2.TwitterException catch (e) {
    print(e);
  }
}

1.4.9. OAuth 2.0 Authorization Code Flow with PKCE

Twitter API v2.0 supports authentication methods with OAuth 2.0 PKCE, and it allows users of apps using Twitter API v2.0 to request authorization for the minimum necessary scope of operation.

Since OAuth2.0 PKCE authentication requires going through a browser, twitter_api_v2 does not provide this specification for compatibility with CLI applications. Instead, we provide twitter_oauth2_pkce, a library for Flutter apps.

The twitter_oauth2_pkce is 100% compatible with twitter_api_v2 and can be used. You can see more details from links below.

Also, please refer to the next simple sample Flutter application that combines twitter_api_v2 and twitter_oauth2_pkce.

1.4.10. Change the Timeout Duration

The library specifies a default timeout of 10 seconds for all API communications.

However, there may be times when you wish to specify an arbitrary timeout duration. If there is such a demand, an arbitrary timeout duration can be specified as follows.

import 'package:twitter_api_v2/twitter_api_v2.dart' as v2;

Future<void> main() {
 final twitter = v2.TwitterApi(
    bearerToken: 'YOUR_TOKEN_HERE',

    //! The default timeout is 10 seconds.
    timeout: Duration(seconds: 5),
  );
}

1.4.11. Automatic Retry

Due to the nature of this library's communication with external systems, timeouts may occur due to inevitable communication failures or temporary crashes of the server to which requests are sent.

When such timeouts occur, an effective countermeasure in many cases is to send the request again after a certain interval. And twitter_api_v2 provides an automatic retry feature as a solution to this problem.

The errors subject to retry are as follows.

1.4.11.1. Exponential BackOff and Jitter

The easiest way to perform an automatic retry is to stop the process at a certain time and rerun it until it succeeds. However, if there is a network outage on Twitter's servers, sending multiple requests to a specific server at the same time may further overload the server to which the request is sent and further reduce the success rate of retry attempts.

This problem can be solved by exponential number and adding a random number called Jitter, and this method is called the Exponential BackOff and Jitter algorithm. By adding a random number to the exponentially increasing retry interval, the retry interval can be distributed more flexibly.

It can be implemented as follows.

import 'package:twitter_api_v2/twitter_api_v2.dart' as v2;

Future<void> main() async {
  final twitter = v2.TwitterApi(
    bearerToken: 'YOUR_TOKEN_HERE',

    //! Add these lines.
    retryConfig: v2.RetryConfig(
      maxAttempts: 3,
    ),
  );
}

In the above implementation, the interval increases exponentially for each retry count with jitter. It can be expressed by next formula.

(2 ^ retryCount) + jitter(Random Number between 0 ~ 3)

1.4.11.2. Do Something on Retry

It would be useful to output logging on retries and a popup notifying the user that a retry has been executed. So twitter_api_v2 provides callbacks that can perform arbitrary processing when retries are executed.

It can be implemented as follows.

import 'package:twitter_api_v2/twitter_api_v2.dart' as v2;

Future<void> main() async {
  final twitter = v2.TwitterApi(
    bearerToken: 'YOUR_TOKEN_HERE',

    retryConfig: v2.RetryConfig(
      maxAttempts: 3,

      //! Add this line.
      onExecute: (event) => print('Retrying... ${event.retryCount} times.'),
    ),
  );
}

The RetryEvent passed to the callback contains information on retries.

1.4.12. Thrown Exceptions

twitter_api_v2 provides a convenient exception object for easy handling of exceptional responses and errors returned from Twitter API v2.0.

ExceptionDescription
TwitterExceptionThe most basic exception object. For example, it can be used to search for tweets that have already been deleted, etc.
TwitterUploadExceptionThrown when an exception occurs during media upload.
UnauthorizedExceptionThrown when authentication fails with the specified access token.
RateLimitExceededExceptionThrown when the request rate limit is exceeded.
DataNotFoundExceptionThrown when response has no body or data field in body string.

Also, all of the above exceptions thrown from the twitter_api_v2 process extend TwitterException. This means that you can take all exceptions as TwitterException or handle them as certain exception types, depending on the situation.

However note that, if you receive an individual type exception, be sure to define the process so that the individual exception type is cached before TwitterException. Otherwise, certain type exceptions will also be caught as TwitterException.

Therefore, if you need to catch a specific type of exception in addition to TwitterException, be sure to catch TwitterException in the bottom catch clause as in the following example.

import 'package:twitter_api_v2/twitter_api_v2.dart' as v2;

Future<void> main() async {
  final twitter = v2.TwitterApi(bearerToken: 'YOUR_TOKEN_HERE');

  try {
    final tweets = await twitter.tweets.searchRecent(
      query: '#ElonMusk',
      maxResults: 20,
    );

    print(tweets);
  } on v2.UnauthorizedException catch (e) {
    print(e);
  } on v2.RateLimitExceededException catch (e) {
    print(e);
  } on v2.DataNotFoundException catch (e) {
    print(e);
  } on v2.TwitterUploadException catch (e) {
    print(e);
  } on v2.TwitterException catch (e) {
    print(e);
  }
}

1.4.13. Upload Media

Uploading media on Twitter and sharing it with various people is a very interesting activity. Also, from a business perspective, accompanying tweets with media will attract even more interest from people.

twitter_api_v2 provides strong support for this very high demand specification. All you have to do is prepare the media file to be uploaded and pass it to the methods, and specifically the following methods are available.

Method NameDescription
uploadImageLow capacity images can be uploaded, such as PNG and GIF.
uploadMediaIn addition to images, you can upload large media such as video. (Preferable)

Both methods are very easy to use.

All the difficult uploading process is capsuled, and as noted earlier, all you have to do is simply pass the prepared media file to the method. For example, if you want to upload a large video to Twitter you can implement the following.

import 'package:twitter_api_v2/twitter_api_v2.dart' as v2;

Future<void> main() async {
  final twitter = v2.TwitterApi(
    bearerToken: 'NO_NEED_BEARER_TOKEN_BECAUSE_IT_IS_V1.1_ENDPOINT',

    //! You need to set OAuth 1.0a tokens,
    //! because this is the v1.1 endpoint.
    oauthTokens: v2.OAuthTokens(
      consumerKey: 'YOUR_CONSUMER_KEY_HERE',
      consumerSecret: 'YOUR_CONSUMER_SECRET_HERE',
      accessToken: 'YOUR_ACCESS_TOKEN_HERE',
      accessTokenSecret: 'YOUR_ACCESS_TOKEN_SECRET_HERE',
    ),
  );

  try {
    final uploadedResponse = await twitter.media.uploadMedia(
      file: File.fromUri(
        Uri.file('FILE_PATH'),
      ),
    );

    print(uploadedResponse);
  } on v2.TwitterUploadException catch (e) {
    print(e);
  }
}

This upload process works very safely, but note that TwitterUploadException will be thrown if media in a format not supported by Twitter is specified.

Note</br> Also note that the v1.1 endpoint is used to achieve this specification in twitter_api_v2. This is because the official Twitter API v2.0 does not yet support media uploads. While I'm trying to keep the implementation as non-disruptive as possible in the future, there may be disruptive changes when media uploads are supported by the official Twitter API v2.0.

1.4.14. Check the Progress of Media Upload

Uploading small images to Twitter does not take long, but uploading large videos takes longer to complete. At that time, it would be very useful if you could show users how far along we are in the uploading process.

twitter_api_v2 supports this specification and can be easily implemented as follows.

import 'package:twitter_api_v2/twitter_api_v2.dart' as v2;

Future<void> main() async {
  final twitter = v2.TwitterApi(
    bearerToken: 'NO_NEED_BEARER_TOKEN_BECAUSE_IT_IS_V1.1',

    //! You need to set OAuth 1.0a tokens,
    //! because this is the v1.1 endpoint.
    oauthTokens: v2.OAuthTokens(
      consumerKey: 'YOUR_CONSUMER_KEY_HERE',
      consumerSecret: 'YOUR_CONSUMER_SECRET_HERE',
      accessToken: 'YOUR_ACCESS_TOKEN_HERE',
      accessTokenSecret: 'YOUR_ACCESS_TOKEN_SECRET_HERE',
    ),
  );

  try {
    final uploadedResponse = await twitter.media.uploadMedia(
      file: File.fromUri(
        Uri.file('FILE_PATH'),
      ),

      //! Add this callback function.
      onProgress: (event) {
        switch (event.state) {
          case v2.UploadState.preparing:
            print('Upload is preparing...');
            break;
          case v2.UploadState.inProgress:
            print('${event.progress}% completed...');
            break;
          case v2.UploadState.completed:
            print('Upload has completed!');
            break;
        }
      },
    );

    print(uploadedResponse);
  } on v2.TwitterUploadException catch (e) {
    print(e);
  }
}

You can add processing when there is upload progress by specifying an onProgress callback for uploadMedia, as shown above.

The argument passed to this callback function is an UploadEvent object, which holds the status and progress rate of the upload at the time the callback function is called.

Importantly, there are 3 upload statuses, which transition from top to bottom during the upload process

StatusDescription
preparingThis indicates the start of the media upload process, up to the point where the media to be uploaded is sent to Twitter. The progress rate is always 0 at this point.
inProgressThis indicates that the media upload process is in progress on Twitter's server. This library polls Twitter's server at regular intervals to obtain the progress rate of media uploads.
completedThis indicates that the media upload has been successfully completed.

And the trigger that calls the onProgress callback is as follows. But if the media upload completes immediately and no polling is required, the inProgress status will not occur.

  1. When the upload status becomes preparing (Always called once at the start of processing)
  2. When the upload status becomes inProgress (Per polling, and it's not called if polling is not required)
  3. When the upload status becomes completed (Always called once at the end of processing)

Note that media uploads may also fail for reasons such as broken media. In such cases, TwitterUploadException is always thrown.

1.4.15. Generate Filtering Rules Safely and Easily

Some endpoints in Twitter API v2.0 supports a number of operators for advanced searches, not just keywords and hashtags.

For example, if you want to extract tweets with the hashtag "#ElonMusk" and the language of the tweeted content is English, you would create the following rule:

Generating these filtering rules is simple at first glance, but the number of supported operators is so large that it's quite a painstaking task to look at the references for each rule you create. Also, there is a syntax specific to this filtering rule, and typos may occur when entering the rules manually.

So, twitter_api_v2 provides FilteringRule object that allows this filtering rule to be constructed safely and easily.

The previous filtering rule example would look like following with FilteringRule object.

import 'package:twitter_api_v2/twitter_api_v2.dart' as v2;

void main() {
  final rule = v2.FilteringRule.of()
      .matchHashtag('ElonMusk')
      .and()
      .matchLanguage(v2.Language.english);

  // -> #ElonMusk lang:en
  print(rule.build());
}

Okay, the specifications of this feature are difficult to explain in this README alone. For this reason, I have created a document for the FilteringRule object, which you should also review.

1.5. Contribution 🏆

If you would like to contribute to twitter_api_v2, please create an issue or create a Pull Request.

There are many ways to contribute to the OSS. For example, the following subjects can be considered:

You can see more details from resources below:

Or you can create a discussion if you like.

Feel free to join this development, diverse opinions make software better!

1.6. Contributors ✨

Thanks goes to these wonderful people (emoji key):

<!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section --> <!-- prettier-ignore-start --> <!-- markdownlint-disable --> <table> <tbody> <tr> <td align="center"><a href="https://github.com/myConsciousness"><img src="https://avatars.githubusercontent.com/u/13072231?v=4?s=100" width="100px;" alt="Kato Shinya / 加藤 真也"/><br /><sub><b>Kato Shinya / 加藤 真也</b></sub></a><br /><a href="https://github.com/twitter-dart/twitter-api-v2/commits?author=myConsciousness" title="Code">💻</a> <a href="#content-myConsciousness" title="Content">🖋</a> <a href="#data-myConsciousness" title="Data">🔣</a> <a href="https://github.com/twitter-dart/twitter-api-v2/commits?author=myConsciousness" title="Documentation">📖</a> <a href="#design-myConsciousness" title="Design">🎨</a> <a href="#example-myConsciousness" title="Examples">💡</a> <a href="#fundingFinding-myConsciousness" title="Funding Finding">🔍</a> <a href="#ideas-myConsciousness" title="Ideas, Planning, & Feedback">🤔</a> <a href="#infra-myConsciousness" title="Infrastructure (Hosting, Build-Tools, etc)">🚇</a> <a href="#maintenance-myConsciousness" title="Maintenance">🚧</a> <a href="#mentoring-myConsciousness" title="Mentoring">🧑‍🏫</a> <a href="#projectManagement-myConsciousness" title="Project Management">📆</a> <a href="#question-myConsciousness" title="Answering Questions">💬</a> <a href="https://github.com/twitter-dart/twitter-api-v2/pulls?q=is%3Apr+reviewed-by%3AmyConsciousness" title="Reviewed Pull Requests">👀</a> <a href="#security-myConsciousness" title="Security">🛡️</a> <a href="#translation-myConsciousness" title="Translation">🌍</a> <a href="https://github.com/twitter-dart/twitter-api-v2/commits?author=myConsciousness" title="Tests">⚠️</a> <a href="#tutorial-myConsciousness" title="Tutorials">✅</a></td> <td align="center"><a href="https://github.com/andypiper"><img src="https://avatars.githubusercontent.com/u/552452?v=4?s=100" width="100px;" alt="Andy Piper"/><br /><sub><b>Andy Piper</b></sub></a><br /><a href="#content-andypiper" title="Content">🖋</a> <a href="#talk-andypiper" title="Talks">📢</a></td> <td align="center"><a href="https://github.com/XRayAdamo"><img src="https://avatars.githubusercontent.com/u/4430621?v=4?s=100" width="100px;" alt="Konstantin"/><br /><sub><b>Konstantin</b></sub></a><br /><a href="https://github.com/twitter-dart/twitter-api-v2/commits?author=XRayAdamo" title="Code">💻</a> <a href="#design-XRayAdamo" title="Design">🎨</a> <a href="https://github.com/twitter-dart/twitter-api-v2/commits?author=XRayAdamo" title="Documentation">📖</a> <a href="#example-XRayAdamo" title="Examples">💡</a> <a href="https://github.com/twitter-dart/twitter-api-v2/commits?author=XRayAdamo" title="Tests">⚠️</a></td> <td align="center"><a href="https://github.com/robertodoering"><img src="https://avatars.githubusercontent.com/u/20045287?v=4?s=100" width="100px;" alt="Roberto Doering"/><br /><sub><b>Roberto Doering</b></sub></a><br /><a href="https://github.com/twitter-dart/twitter-api-v2/commits?author=robertodoering" title="Code">💻</a> <a href="#design-robertodoering" title="Design">🎨</a> <a href="https://github.com/twitter-dart/twitter-api-v2/commits?author=robertodoering" title="Documentation">📖</a> <a href="#example-robertodoering" title="Examples">💡</a> <a href="https://github.com/twitter-dart/twitter-api-v2/commits?author=robertodoering" title="Tests">⚠️</a> <a href="#ideas-robertodoering" title="Ideas, Planning, & Feedback">🤔</a></td> <td align="center"><a href="https://github.com/niteshsh4rma"><img src="https://avatars.githubusercontent.com/u/58659088?v=4?s=100" width="100px;" alt="Nitesh Sharma"/><br /><sub><b>Nitesh Sharma</b></sub></a><br /><a href="https://github.com/twitter-dart/twitter-api-v2/commits?author=niteshsh4rma" title="Code">💻</a> <a href="#design-niteshsh4rma" title="Design">🎨</a> <a href="https://github.com/twitter-dart/twitter-api-v2/commits?author=niteshsh4rma" title="Documentation">📖</a> <a href="#example-niteshsh4rma" title="Examples">💡</a> <a href="https://github.com/twitter-dart/twitter-api-v2/commits?author=niteshsh4rma" title="Tests">⚠️</a> <a href="#ideas-niteshsh4rma" title="Ideas, Planning, & Feedback">🤔</a></td> </tr> <tr> <td align="center"><a href="https://github.com/ngoluuduythai"><img src="https://avatars.githubusercontent.com/u/12238262?v=4?s=100" width="100px;" alt="ngoluuduythai"/><br /><sub><b>ngoluuduythai</b></sub></a><br /><a href="https://github.com/twitter-dart/twitter-api-v2/commits?author=ngoluuduythai" title="Documentation">📖</a> <a href="#translation-ngoluuduythai" title="Translation">🌍</a></td> <td align="center"><a href="https://github.com/its-me-mahmud"><img src="https://avatars.githubusercontent.com/u/53822204?v=4?s=100" width="100px;" alt="Abdullah Al Mahmud"/><br /><sub><b>Abdullah Al Mahmud</b></sub></a><br /><a href="https://github.com/twitter-dart/twitter-api-v2/commits?author=its-me-mahmud" title="Documentation">📖</a> <a href="#translation-its-me-mahmud" title="Translation">🌍</a></td> <td align="center"><a href="https://github.com/omar6260"><img src="https://avatars.githubusercontent.com/u/82382673?v=4?s=100" width="100px;" alt="Oumar fall"/><br /><sub><b>Oumar fall</b></sub></a><br /><a href="https://github.com/twitter-dart/twitter-api-v2/commits?author=omar6260" title="Documentation">📖</a> <a href="#translation-omar6260" title="Translation">🌍</a></td> <td align="center"><a href="https://github.com/natastro"><img src="https://avatars.githubusercontent.com/u/17433156?v=4?s=100" width="100px;" alt="Natalie Stroud"/><br /><sub><b>Natalie Stroud</b></sub></a><br /><a href="https://github.com/twitter-dart/twitter-api-v2/commits?author=natastro" title="Documentation">📖</a> <a href="#translation-natastro" title="Translation">🌍</a></td> <td align="center"><a href="https://github.com/novas1r1"><img src="https://avatars.githubusercontent.com/u/2575205?v=4?s=100" width="100px;" alt="novas1r1"/><br /><sub><b>novas1r1</b></sub></a><br /><a href="https://github.com/twitter-dart/twitter-api-v2/commits?author=novas1r1" title="Documentation">📖</a> <a href="#translation-novas1r1" title="Translation">🌍</a> <a href="#ideas-novas1r1" title="Ideas, Planning, & Feedback">🤔</a></td> </tr> <tr> <td align="center"><a href="https://github.com/eltociear"><img src="https://avatars.githubusercontent.com/u/22633385?v=4?s=100" width="100px;" alt="Ikko Ashimine"/><br /><sub><b>Ikko Ashimine</b></sub></a><br /><a href="https://github.com/twitter-dart/twitter-api-v2/commits?author=eltociear" title="Documentation">📖</a></td> <td align="center"><a href="https://github.com/VinniciusJesus"><img src="https://avatars.githubusercontent.com/u/57817746?v=4?s=100" width="100px;" alt="Marcos Vinícius"/><br /><sub><b>Marcos Vinícius</b></sub></a><br /><a href="https://github.com/twitter-dart/twitter-api-v2/commits?author=VinniciusJesus" title="Documentation">📖</a> <a href="#translation-VinniciusJesus" title="Translation">🌍</a></td> <td align="center"><a href="https://github.com/MarkOSullivan94"><img src="https://avatars.githubusercontent.com/u/6950843?v=4?s=100" width="100px;" alt="Mark O'Sullivan"/><br /><sub><b>Mark O'Sullivan</b></sub></a><br /><a href="#ideas-MarkOSullivan94" title="Ideas, Planning, & Feedback">🤔</a></td> <td align="center"><a href="https://github.com/bors-ng"><img src="https://avatars.githubusercontent.com/u/24979321?v=4?s=100" width="100px;" alt="bors-ng"/><br /><sub><b>bors-ng</b></sub></a><br /><a href="#maintenance-bors-ng" title="Maintenance">🚧</a> <a href="https://github.com/twitter-dart/twitter-api-v2/pulls?q=is%3Apr+reviewed-by%3Abors-ng" title="Reviewed Pull Requests">👀</a></td> <td align="center"><a href="https://github.com/all-contributors"><img src="https://avatars.githubusercontent.com/u/46410174?v=4?s=100" width="100px;" alt="All Contributors"/><br /><sub><b>All Contributors</b></sub></a><br /><a href="https://github.com/twitter-dart/twitter-api-v2/commits?author=all-contributors" title="Documentation">📖</a></td> </tr> <tr> <td align="center"><a href="https://github.com/codecov"><img src="https://avatars.githubusercontent.com/u/8226205?v=4?s=100" width="100px;" alt="Codecov"/><br /><sub><b>Codecov</b></sub></a><br /><a href="https://github.com/twitter-dart/twitter-api-v2/commits?author=codecov" title="Tests">⚠️</a> <a href="#maintenance-codecov" title="Maintenance">🚧</a> <a href="#security-codecov" title="Security">🛡️</a></td> <td align="center"><a href="https://github.com/fossabot"><img src="https://avatars.githubusercontent.com/u/9543448?v=4?s=100" width="100px;" alt="FOSSA"/><br /><sub><b>FOSSA</b></sub></a><br /><a href="#maintenance-fossas" title="Maintenance">🚧</a> <a href="#security-fossas" title="Security">🛡️</a></td> <td align="center"><a href="https://github.com/yuto90"><img src="https://avatars.githubusercontent.com/u/53107639?v=4?s=100" width="100px;" alt="yuto90"/><br /><sub><b>yuto90</b></sub></a><br /><a href="#blog-yuto90" title="Blogposts">📝</a> <a href="#content-yuto90" title="Content">🖋</a> <a href="#example-yuto90" title="Examples">💡</a> <a href="#tutorial-yuto90" title="Tutorials">✅</a></td> <td align="center"><a href="https://github.com/normidar"><img src="https://avatars.githubusercontent.com/u/36730656?v=4?s=100" width="100px;" alt="normidar"/><br /><sub><b>normidar</b></sub></a><br /><a href="#ideas-normidar" title="Ideas, Planning, & Feedback">🤔</a> <a href="https://github.com/twitter-dart/twitter-api-v2/commits?author=normidar" title="Code">💻</a> <a href="https://github.com/twitter-dart/twitter-api-v2/commits?author=normidar" title="Documentation">📖</a> <a href="#question-normidar" title="Answering Questions">💬</a></td> <td align="center"><a href="https://github.com/TSurkis"><img src="https://avatars.githubusercontent.com/u/10674270?v=4?s=100" width="100px;" alt="Tim Surkis"/><br /><sub><b>Tim Surkis</b></sub></a><br /><a href="https://github.com/twitter-dart/twitter-api-v2/issues?q=author%3ATSurkis" title="Bug reports">🐛</a> <a href="#ideas-TSurkis" title="Ideas, Planning, & Feedback">🤔</a> <a href="#question-TSurkis" title="Answering Questions">💬</a> <a href="#userTesting-TSurkis" title="User Testing">📓</a></td> </tr> <tr> <td align="center"><a href="https://github.com/shinobi-art"><img src="https://avatars.githubusercontent.com/u/79818229?v=4?s=100" width="100px;" alt="shinobi-art"/><br /><sub><b>shinobi-art</b></sub></a><br /><a href="https://github.com/twitter-dart/twitter-api-v2/issues?q=author%3Ashinobi-art" title="Bug reports">🐛</a> <a href="#question-shinobi-art" title="Answering Questions">💬</a></td> <td align="center"><a href="https://github.com/Tushar-Mishra999"><img src="https://avatars.githubusercontent.com/u/75738710?v=4?s=100" width="100px;" alt="Tushar Mishra"/><br /><sub><b>Tushar Mishra</b></sub></a><br /><a href="https://github.com/twitter-dart/twitter-api-v2/commits?author=Tushar-Mishra999" title="Code">💻</a></td> <td align="center"><a href="https://github.com/azkadev"><img src="https://avatars.githubusercontent.com/u/82513502?v=4?s=100" width="100px;" alt="Azka Full Snack Developer:)"/><br /><sub><b>Azka Full Snack Developer:)</b></sub></a><br /><a href="#question-azkadev" title="Answering Questions">💬</a> <a href="#ideas-azkadev" title="Ideas, Planning, & Feedback">🤔</a></td> </tr> </tbody> </table> <!-- markdownlint-restore --> <!-- prettier-ignore-end --> <!-- ALL-CONTRIBUTORS-LIST:END -->

This project follows the all-contributors specification. Contributions of any kind welcome!

1.7. Support ❤️

The simplest way to show us your support is by giving the project a star at GitHub and Pub.dev.

You can also support this project by becoming a sponsor on GitHub:

<div align="left"> <p> <a href="https://github.com/sponsors/myconsciousness"> <img src="https://cdn.ko-fi.com/cdn/kofi3.png?v=3" height="50" width="210" alt="myconsciousness" /> </a> </p> </div>

You can also show on your repository that your app is made with twitter_api_v2 by using one of the following badges:

Powered by twitter_api_v2 Powered by twitter_api_v2 Powered by twitter_api_v2

[![Powered by twitter_api_v2](https://img.shields.io/badge/Powered%20by-twitter_api_v2-00acee.svg)](https://github.com/twitter-dart/twitter-api-v2)
[![Powered by twitter_api_v2](https://img.shields.io/badge/Powered%20by-twitter_api_v2-00acee.svg?style=flat-square)](https://github.com/twitter-dart/twitter-api-v2)
[![Powered by twitter_api_v2](https://img.shields.io/badge/Powered%20by-twitter_api_v2-00acee.svg?style=for-the-badge)](https://github.com/twitter-dart/twitter-api-v2)

1.8. License 🔑

All resources of twitter_api_v2 is provided under the BSD-3 license.

FOSSA Status

Note</br> License notices in the source are strictly validated based on .github/header-checker-lint.yml. Please check header-checker-lint.yml for the permitted standards.

1.9. More Information 🧐

twitter_api_v2 was designed and implemented by Kato Shinya (@myConsciousness).