twitter-api-v2

repository·master·Indexed 23 days ago

https://github.com/plhery/node-twitter-api-v2

A strongly typed, lightweight, and full-featured Node.js client for the Twitter API v1.1 and v2. It provides full endpoint wrapping, pagination utilities, media upload helpers, and support for OAuth 1.0a, OAuth2, and Basic HTTP Authorization. The library includes experimental support for the Twitter Ads API and official plugins for token refreshing, rate limit tracking, and Redis caching.

Tokens
41.8K
Snippets
117
Records
201
Agent score
81%

What's inside twitter-api-v2

  1. Core Features of twitter-api-v2

    master

    The library provides several key capabilities for interacting with the Twitter API:

    API Support & Auth

    • Support for v1.1 and v2 APIs.
    • Authentication support for OAuth 1.0a, OAuth2 (including user-context OAuth2), and Basic HTTP Authorization.

    Request & Data Handling

    • Typed Wrappers: Dedicated methods for endpoints with typed arguments and fully typed responses (including tweets, users, and media entities).
    • Pagination: Automatic paginators for timelines (user/tweet) that support modern asynchronous iterators.
    • Streaming: High-class support for stream endpoints with easy data consumption and auto-reconnect.
    • HTTP Helpers: Helpers for GET, POST, PUT, DELETE, and PATCH that handle query string formatting and automatic body formatting.

    Media & Errors

    • Media Uploads: API v1.1 helpers supporting long video, subtitles, automatic type detection, chunked uploads, and concurrent uploads.
    • Error Handling: Typed errors with meaningful messages and error enumerations for both v1.1 and v2.
  2. How plugins work in `twitter-api-v2`

    master

    Plugins are objects that implement the ITwitterApiClientPlugin interface. They allow you to hook into various stages of the request lifecycle, including request preparation, execution, success, and error handling. Every method in the interface is optional, allowing you to implement only the specific hooks you need.

    interface ITwitterApiClientPlugin {
      // Classic requests
      /* Executed when request is about to be prepared. OAuth headers, body, query normalization hasn't been done yet. */
      onBeforeRequestConfig?: TTwitterApiBeforeRequestConfigHook
      /* Executed when request is about to be made. Headers/body/query has been prepared, and HTTP options has been initialized. */
      onBeforeRequest?: TTwitterApiBeforeRequestHook
      /* Executed when a request succeeds (failed requests don't trigger this hook). */
      onAfterRequest?: TTwitterApiAfterRequestHook
      // Error handling in classic requests
      /* Executed when Twitter doesn't reply (network error, server disconnect). */
      onRequestError?: TTwitterApiRequestErrorHook
      /* Executed when Twitter reply but with an error? */
      onResponseError?: TTwitterApiResponseErrorHook
      // Stream requests
      /* Executed when a stream request is about to be prepared. This method **can't** return a `Promise`. */
      onBeforeStreamRequestConfig?: TTwitterApiBeforeStreamRequestConfigHook
      // Request token
      /* Executed after a `.generateAuthLink`, mainly to allow automatic collect of `oauth_token`/`oauth_token_secret` couples.  */
      onOAuth1RequestToken?: TTwitterApiAfterOAuth1RequestTokenHook
      /* Executed after a `.generateOAuth2AuthLink`, mainly to allow automatic collect of `state`/`codeVerifier` couples.  */
      onOAuth2RequestToken?: TTwitterApiAfterOAuth2RequestTokenHook
    }
  3. Rate limiting behavior in Paginators

    master

    Paginators handle rate limits automatically during .fetchLast() calls or when using async iteration; the process will simply end when a rate limit is encountered. You can also check the current rate limit status for the paginator's endpoint using the .rateLimit getter.

    const paginator = await client.v1.homeTimeline();
    console.log(paginator.rateLimit); // { limit: number, remaining: number, reset: number }
  4. User-wide authentication flow (OAuth 1.0a)

    master

    The OAuth 1.0a "3-legged" authentication flow allows your application to act on behalf of a Twitter user. It is the most common method for user-specific actions but is the most complex to implement.

    The 3-Legged Process:

    1. Generate Auth Link: Your server generates a link for the user. You must store the oauth_token and oauth_token_secret returned by this step in a session or database.
    2. User Approval: The user clicks the link and approves your app on Twitter. Twitter then redirects them to your CALLBACK_URL with an oauth_token and oauth_verifier, or provides a PIN.
    3. Exchange for Persistent Tokens: You use the temporary tokens and the verifier (or PIN) to obtain a persistent accessToken and accessSecret that allow long-term access to that user's account.

    Requirements:

    • You must have a way to store data (session, Redis, file, etc.) between step 1 and step 2.
    • You must implement either an oauth callback URL or a PIN input field for the user.
  5. Access Twitter API v2 methods

    master

    All Twitter API v2 methods are attached to the v2 property of the client instance. You access them via client.v2.

    If a specific endpoint is not implemented in the package, you can perform manual requests using the generic HTTP wrapper methods: .get(), .post(), .put(), .patch(), and .delete().

    Key technical notes:

    • Arguments: Described arguments usually refer to an interface name. The actual argument type is typically a Partial<InterfaceName>, meaning all properties are optional.
    • Return Types: All API methods return Promises.
    • Data Inclusion: The API uses includes to attach related data (like media, polls, or users) to responses. Use the includes helper to browse these attached entities.
  6. Use versioned API clients (v1, v2, and Labs)

    master

    Because the library supports multiple versions of the Twitter API, you must specify which version you intend to use to access the correct endpoint-wrapper methods. Using a versioned client automatically applies the correct URL prefix.

    • v1 Client: client.v1 (Prefix: https://api.x.com/1.1/)
    • v2 Client: client.v2 (Prefix: https://api.x.com/2/)
    • v2 Labs Client: client.v2.labs (Prefix: https://api.x.com/labs/2/)
    const v1Client = client.v1;
    const v2Client = client.v2;
    const v2LabsClient = client.v2.labs;
  7. Access Twitter API v1.1 methods via the v1 client

    master

    All Twitter API v1.1 methods are attached to the v1 property of your client instance. To use them, access them through client.v1.

    If a specific endpoint is not implemented as a dedicated method, you can still make manual requests using the generic HTTP wrapper methods: .get(), .post(), .put(), .patch(), and .delete().

  8. How to create a stream without immediate connection

    master

    By default, streaming methods connect immediately and return a Promise that resolves to the stream. If you want to configure event handlers before the connection starts, or if you want the method to return the TweetStream object synchronously, pass { autoConnect: false } in the options object.

    You must then manually call .connect() to start the stream. This is useful for setting up complex reconnection logic or specific event listeners upfront.

    const stream = client.v2.sampleStream({ autoConnect: false });
    
    stream.on(ETwitterStreamEvent.Data, console.log);
    stream.on(ETwitterStreamEvent.Connected, () => console.log('Stream is started.'));
    
    await stream.connect({ autoReconnect: true, autoReconnectRetries: Infinity });
  9. Use TwitterV2IncludesHelper to handle v2 API expansions

    master

    In Twitter API v2, expanded metadata (like user objects or media) is returned in an includes object rather than directly within the primary data array. To avoid manual searching and handling undefined values, use the TwitterV2IncludesHelper class.

    Simple Usage

    Instantiate the helper by passing the full API response object. The helper provides fail-safe getters for all include types (tweets, media, users, polls, and places), ensuring they are always defined even if the response lacks them.

    Static Usage

    You can also use the helper without instantiation by calling its methods statically. The pattern is MethodName(responseObject, ...restParameters).

    Example:

    TwitterV2IncludesHelper.tweets(response)
    TwitterV2IncludesHelper.retweets(response, tweet)
  10. Extend functionality with official plugins

    master

    You can extend the twitter-api-v2 client using official plugins. Common plugins include:

    • @twitter-api-v2/plugin-token-refresher: Automatically handles OAuth 2.0 (user-context) token refreshing.
    • @twitter-api-v2/plugin-rate-limit: Provides access to and storage for automatic rate limit data.
    • @twitter-api-v2/plugin-cache-redis: Enables caching of responses using a Redis store.
  11. How Paginators work in twitter-api-v2

    master

    Endpoints that return paginable collections (such as user timelines, tweet searches, or home timelines) return a subclass of TwitterPaginator.

    When you call a paginable method, the instance is initialized with the first page of data. You can then use various methods to navigate through subsequent pages of results. Paginators support both cumulative fetching (adding new items to the existing instance) and discrete fetching (getting a new instance for the next page).

    const homeTimeline = await client.v1.homeTimeline();
  12. Handle different types of API errors

    master

    When a request fails, you can catch one of three error types, all of which are instances of Error. Identifying the type helps determine if the issue is local, connection-based, or returned by Twitter.

    • ApiRequestError: The request failed to be sent (e.g., network error, invalid URL).
    • ApiPartialResponseError: The response was partially received, but the connection was closed (by the client, OS, or Twitter) before completion.
    • ApiResponseError: Twitter successfully received the request and replied with an error (e.g., 401 Unauthorized, 404 Not Found).

    Common properties across these error types:

    • error: true
    • type: Contains ETwitterApiError.Request, ETwitterApiError.PartialResponse, or ETwitterApiError.Response.
    • request: The raw Node.js ClientRequest instance.