Twitter OpenAPI TypeScript Generated Client
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.
Common errors
-
ReferenceError: fetch is not defined
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.fixFor 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`. -
Error: Request failed with status code 401 (Unauthorized) or 403 (Forbidden)
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.fixVerify 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. -
Error: Token can only be used on the same OS that issued the Token
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.fixBefore 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"').
Warnings
- breaking 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.
- breaking 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.
- gotcha 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.
- gotcha 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.
Install
-
npm install twitter-openapi-typescript-generated -
yarn add twitter-openapi-typescript-generated -
pnpm add twitter-openapi-typescript-generated
Imports
- TwitterOpenApi
const TwitterOpenApi = require('twitter-openapi-typescript-generated');import { TwitterOpenApi } from 'twitter-openapi-typescript-generated'; - TwitterOpenApiClient
import { TwitterOpenApiClient } from 'twitter-openapi-typescript-generated'; - UserLegacy
import { UserLegacy } from 'twitter-openapi-typescript-generated/models';
Quickstart
import { TwitterOpenApi } from 'twitter-openapi-typescript-generated';
const main = async () => {
const bearerToken = process.env.TWITTER_BEARER_TOKEN ?? '';
if (!bearerToken) {
console.error('Please set the TWITTER_BEARER_TOKEN environment variable.');
process.exit(1);
}
try {
// Initialize the API client with a bearer token
const api = new TwitterOpenApi();
api.bearer = bearerToken; // Direct bearer token assignment, as shown in similar usage examples.
// Get a guest client if bearer token is for guest access or specific API requires it
const client = await api.getGuestClient();
// Example: Fetching user details by screen name (e.g., Elon Musk)
const screenName = 'elonmusk';
console.log(`Attempting to fetch user: @${screenName}`);
const response = await client.getUserApi().getUserByScreenName({ screenName });
const userLegacy = response.data?.user?.legacy;
if (userLegacy) {
console.log(`Found user: ${userLegacy.name} (@${userLegacy.screenName})`);
console.log(`Followers: ${userLegacy.followersCount}, Following: ${userLegacy.friendsCount}`);
} else {
console.log(`User @${screenName} not found or data unavailable.`);
console.log('Full response:', JSON.stringify(response, null, 2));
}
} catch (error) {
console.error('An error occurred:', error);
if (error instanceof Error) {
console.error('Error message:', error.message);
}
}
};
main();