Twitter API TypeScript SDK

repository·main·Indexed 21 days ago

https://github.com/xdevplatform/twitter-api-typescript-sdk

A TypeScript SDK for interacting with the Twitter API V2, providing full type safety for requests and responses. It supports Bearer Token and OAuth 2.0 authentication (including public and confidential clients), handles automatic rate limit retries for HTTP 429 errors, and provides utilities for consuming Twitter streams via Async Generators and managing paginated API results.

Tokens
5K
Snippets
24
Records
26
Agent score
77%

What's inside twitter-api-sdk

  1. Handle Pagination for paginated endpoints

    main

    For endpoints that support pagination (e.g., usersIdFollowers), you can either iterate over the pages using a for await...of loop to get all results, or await the call directly to get a single page of results.

    // Iterate through all pages
    const followers = client.users.usersIdFollowers("20");
    for await (const page of followers) {
      console.log(page.data);
    }
    
    // Or get just the first page
    const followersPage = await client.users.usersIdFollowers("20");
    console.log(followersPage.data);
  2. Configure OAuth 2.0 Authentication

    main

    The SDK supports OAuth 2.0. Before starting, ensure OAuth2 is enabled in your Twitter App settings and the app type is set to either a 'confidential client' or a 'public client'.

    Creating a Public Auth Client

    Use this for client-side or public applications where the client_secret cannot be kept secure.

    Creating a Confidential Auth Client

    Use this for server-side applications where you can securely store the client_secret.

    OAuth 2.0 Workflow

    1. Generate Auth URL: Use authClient.generateAuthURL with a code_challenge_method (e.g., s256).
    2. Redirect User: Send the user to the generated URL.
    3. Request Access Token: After the user approves, capture the code from the callback URL and call authClient.requestAccessToken(code).
    4. Revoke Token: Use authClient.revokeAccessToken() to invalidate the token.
    // Public Client Example
    const authClient = new auth.OAuth2User({
      client_id: process.env.CLIENT_ID,
      callback: "http://127.0.0.1:3000/callback",
      scopes: ["tweet.read", "users.read", "offline.access"],
    });
    
    const client = new Client(authClient);
    
    // Generating the URL
    const authUrl = authClient.generateAuthURL({
      code_challenge_method: "s256",
    });
    
    // Requesting token after callback
    await authClient.requestAccessToken(code);
  3. Run the Twitter API TypeScript SDK examples

    main

    To run the provided examples, navigate to the examples directory and follow these steps:

    1. Install dependencies: Run npm install to install the required packages.
    2. Configure environment variables: Create a .env file in the examples directory. Populate it with the necessary credentials. Note that different examples require different variables (e.g., oauth2-bearer.ts only requires BEARER_TOKEN).
    3. Execute examples: Use ts-node to run specific TypeScript files.

    Required environment variables for the .env file:

    • BEARER_TOKEN
    • CLIENT_ID
    • CLIENT_SECRET
    # 1. Install dependencies
    npm install
    
    # 2. Create .env file with required variables
    echo "BEARER_TOKEN=my-bearer-token" > .env
    echo "CLIENT_ID=my-client-id" >> .env
    echo "CLIENT_SECRET=my-client-secret" >> .env
    
    # 3. Run a specific example
    npx ts-node oauth2-bearer.ts
  4. Handle Twitter API rate limits with automatic retries

    main
    The request function includes built-in support for handling HTTP 429 (Too Many Requests) errors. If max_retries is provided as a positive integer, the SDK will automatically inspect the x-rate-limit-reset and x-rate-limit-remaining headers. If the rate limit has been exhausted (x-rate-limit-remaining is 0), the SDK will wait until the time specified by x-rate-limit-reset before attempting the request again, up to the specified max_retries limit.
  5. Handle paginated Twitter API responses

    main

    The SDK uses TwitterPaginatedResponse<T> to handle endpoints that return paginated data. This type extends AsyncIterable<T>, allowing you to iterate over pages of results using for await...of loops. The generic type T must extend TwitterNextToken, which contains the meta.next_token required for subsequent requests.

    // Example of how a paginated response is consumed
    for await (const page of paginatedResponse) {
      console.log(page.data);
      console.log(page.meta?.next_token);
    }
  6. Get a Tweet by ID

    main

    Use the client.tweets.findTweetById method to retrieve a specific tweet's data.

    import { Client } from "twitter-api-sdk";
    
    const client = new Client(process.env.BEARER_TOKEN);
    
    async function main() {
      const tweet = await client.tweets.findTweetById("20");
      console.log(tweet.data.text);
    }
    
    main();
  7. Consume a Twitter Stream using Async Generators

    main

    Endpoints that return a stream (like sampleStream) return an AsyncGenerator. You can iterate over the stream using a for await...of loop to process incoming data in real-time.

    import { Client } from "twitter-api-sdk";
    
    const client = new Client(process.env.BEARER_TOKEN);
    
    async function main() {
      const stream = client.tweets.sampleStream({
        "tweet.fields": ["author_id"],
      });
      for await (const tweet of stream) {
        console.log(tweet.data?.author_id);
      }
    }
    
    main();
  8. Get authorization headers for API requests

    main

    To make authenticated requests using the SDK's rest utility, call getAuthHeader(). This method is intelligent: it checks if the current access token is expired and automatically calls refreshAccessToken() if necessary before returning the Authorization: Bearer <token> header.

    const headers = await oauth2.getAuthHeader();
    // headers = { Authorization: 'Bearer ...' }
  9. Generate an OAuth2 authorization URL

    main

    Use generateAuthURL to create the URL you redirect users to for granting permissions. You must provide a state string to prevent CSRF attacks.

    Supported methods:

    1. s256: Uses PKCE with SHA-256. The client automatically generates a code_verifier and code_challenge internally.
    2. plain: Uses PKCE with a plain code_challenge provided by you.
    // Using S256 (Recommended)
    const url = oauth2.generateAuthURL({
      state: 'random_state_string',
      code_challenge_method: 's256'
    });
    
    // Using plain
    const url = oauth2.generateAuthURL({
      state: 'random_state_string',
      code_challenge: 'my_secret_challenge',
      code_challenge_method: 'plain'
    });