{"id":12209,"library":"twitter-openapi-typescript-generated","title":"Twitter OpenAPI TypeScript Generated Client","description":"This package, `twitter-openapi-typescript-generated`, provides an automatically generated TypeScript/JavaScript client for the Twitter API, based on its OpenAPI specification. It leverages the native Fetch API for all network requests and is designed for use across diverse JavaScript environments, including Node.js, Webpack-bundled applications, and modern browsers. It supports both CommonJS and ES module systems, with full TypeScript type definitions automatically resolved. While the prompt specifies version 0.0.38, the related `twitter-openapi-typescript` package on npm is currently at 0.0.55, indicating a rapid release cadence in a pre-1.0 state. This early `0.0.x` versioning suggests that the API and its implementation may undergo frequent, potentially breaking, changes without strict adherence to semantic versioning. It serves as a direct, machine-generated interface to the Twitter API, differentiating itself from more 'human-friendly' wrappers by offering a direct reflection of the OpenAPI spec.","status":"active","version":"0.0.38","language":"javascript","source_language":"en","source_url":"https://github.com/fa0311/twitter-openapi-typescript","tags":["javascript","twitter","api","typescript","scraper"],"install":[{"cmd":"npm install twitter-openapi-typescript-generated","lang":"bash","label":"npm"},{"cmd":"yarn add twitter-openapi-typescript-generated","lang":"bash","label":"yarn"},{"cmd":"pnpm add twitter-openapi-typescript-generated","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"This is the primary class for initializing the Twitter API client. The `require` syntax is typically incorrect for modern ESM-first packages or when TypeScript's `esModuleInterop` is not configured correctly.","wrong":"const TwitterOpenApi = require('twitter-openapi-typescript-generated');","symbol":"TwitterOpenApi","correct":"import { TwitterOpenApi } from 'twitter-openapi-typescript-generated';"},{"note":"A lower-level client class that can be used directly for more advanced customization, as an alternative to the higher-level `TwitterOpenApi` interface.","symbol":"TwitterOpenApiClient","correct":"import { TwitterOpenApiClient } from 'twitter-openapi-typescript-generated';"},{"note":"Example of importing a specific generated type definition, such as for a user's legacy data. The exact path for models might vary slightly depending on the generator configuration, but typically resides in a `models` or `schemas` subdirectory.","symbol":"UserLegacy","correct":"import { UserLegacy } from 'twitter-openapi-typescript-generated/models';"}],"quickstart":{"code":"import { TwitterOpenApi } from 'twitter-openapi-typescript-generated';\n\nconst main = async () => {\n  const bearerToken = process.env.TWITTER_BEARER_TOKEN ?? '';\n\n  if (!bearerToken) {\n    console.error('Please set the TWITTER_BEARER_TOKEN environment variable.');\n    process.exit(1);\n  }\n\n  try {\n    // Initialize the API client with a bearer token\n    const api = new TwitterOpenApi();\n    api.bearer = bearerToken; // Direct bearer token assignment, as shown in similar usage examples.\n\n    // Get a guest client if bearer token is for guest access or specific API requires it\n    const client = await api.getGuestClient(); \n    \n    // Example: Fetching user details by screen name (e.g., Elon Musk)\n    const screenName = 'elonmusk';\n    console.log(`Attempting to fetch user: @${screenName}`);\n\n    const response = await client.getUserApi().getUserByScreenName({ screenName });\n\n    const userLegacy = response.data?.user?.legacy;\n\n    if (userLegacy) {\n      console.log(`Found user: ${userLegacy.name} (@${userLegacy.screenName})`);\n      console.log(`Followers: ${userLegacy.followersCount}, Following: ${userLegacy.friendsCount}`);\n    } else {\n      console.log(`User @${screenName} not found or data unavailable.`);\n      console.log('Full response:', JSON.stringify(response, null, 2));\n    }\n  } catch (error) {\n    console.error('An error occurred:', error);\n    if (error instanceof Error) {\n        console.error('Error message:', error.message);\n    }\n  }\n};\n\nmain();","lang":"typescript","description":"This quickstart initializes the Twitter API client with a bearer token and fetches a user's public profile information by screen name, demonstrating basic client setup and API interaction."},"warnings":[{"fix":"Regularly check the package's GitHub repository or npm page for updates and release notes. Pin exact versions in your `package.json` and manually test updates.","message":"This package is in a very early stage of development (0.0.x versions). Breaking changes are highly likely to occur between minor or even patch versions without strict adherence to semantic versioning, requiring frequent updates to your integration code.","severity":"breaking","affected_versions":">=0.0.0"},{"fix":"Ensure you have a valid, up-to-date Twitter Developer account and have generated granular access tokens. Update your CI/CD workflows for token management. Consult the official X Developers documentation for the latest authentication requirements.","message":"The Twitter API (now X API) has undergone significant changes, including the end of free access, deprecation of older tokens, and new authentication requirements (e.g., granular tokens, 2FA). Existing API keys or bearer tokens may be revoked or become invalid.","severity":"breaking","affected_versions":">=0.0.0"},{"fix":"If encountering authentication issues across different operating systems, explicitly set `sec-ch-ua-platform` headers using `api.setAdditionalApiHeaders({ 'sec-ch-ua-platform': '\"Windows\"' })` or similar, to match the OS where the token was issued.","message":"Authentication tokens issued by Twitter can be platform-specific. For example, a token issued on Windows might not work when the API client sends headers indicating a Linux environment, as the library defaults to Linux Chrome headers.","severity":"gotcha","affected_versions":">=0.0.0"},{"fix":"Implement robust error handling for HTTP 429 responses, including exponential backoff and retry logic. Design your application to minimize API calls and leverage caching where possible. Consult Twitter's official rate limit documentation.","message":"Twitter API has strict rate limits. Exceeding these limits will result in HTTP 429 Too Many Requests errors and potential temporary bans for your application or IP address.","severity":"gotcha","affected_versions":">=0.0.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"For Node.js, ensure you are running Node.js v18 or later, which includes `fetch` globally. For older Node.js versions or specific environments, install and import a `node-fetch` polyfill: `npm install node-fetch`.","cause":"The environment where the code is running (e.g., older Node.js versions or specific browser builds) does not natively support the Fetch API, or a polyfill is missing.","error":"ReferenceError: fetch is not defined"},{"fix":"Verify your bearer token is correct and active. Regenerate tokens if necessary from your X Developer dashboard. Check the token's permissions and ensure they align with the API calls being made. Confirm your API access level supports the desired functionality.","cause":"The provided API key or bearer token is invalid, expired, revoked, or lacks the necessary permissions for the requested operation due to recent Twitter API changes.","error":"Error: Request failed with status code 401 (Unauthorized) or 403 (Forbidden)"},{"fix":"Before making API calls, configure the `TwitterOpenApi` instance to send the correct platform header: `api.setAdditionalApiHeaders({ 'sec-ch-ua-platform': '\"YourOS\"' });`, replacing '\"YourOS\"' with the appropriate string (e.g., '\"Windows\"', '\"macOS\"', '\"Linux\"').","cause":"The security headers sent with the API request (specifically `sec-ch-ua-platform`) do not match the operating system context in which your Twitter API bearer token was originally generated or is expected to be used.","error":"Error: Token can only be used on the same OS that issued the Token"}],"ecosystem":"npm"}