### Install XDK via Package Managers Source: https://github.com/xdevplatform/xdk-typescript/blob/main/README.md Commands to install the XDK package using common JavaScript package managers. ```bash npm install @xdevplatform/xdk ``` ```bash yarn add @xdevplatform/xdk ``` ```bash pnpm add @xdevplatform/xdk ``` -------------------------------- ### Xdev Platform XDK Users API - Manage Relationships Source: https://context7.com/xdevplatform/xdk-typescript/llms.txt Demonstrates how to manage user relationships like follows, blocks, and mutes using the XDK. This includes fetching followers, getting followed users, following/unfollowing, blocking/unblocking, and muting/unmuting users. ```typescript // Get followers of a user const followers = await client.users.getFollowers('783214', { maxResults: 100, userFields: ['id', 'name', 'username'] }); // Get users a user is following const following = await client.users.getFollowing('783214', { maxResults: 100 }); // Follow a user await client.users.followUser('my-user-id', { body: { targetUserId: '783214' } }); // Unfollow a user await client.users.unfollowUser('my-user-id', '783214'); // Get blocked users const blocked = await client.users.getBlocking('my-user-id'); // Get muted users const muted = await client.users.getMuting('my-user-id'); // Mute a user await client.users.muteUser('my-user-id', { body: { targetUserId: '783214' } }); // Unmute a user await client.users.unmuteUser('my-user-id', '783214'); ``` -------------------------------- ### Xdev Platform XDK Users API - Get User Information Source: https://context7.com/xdevplatform/xdk-typescript/llms.txt Shows how to retrieve user information using the XDK's Users API. This includes fetching the authenticated user, getting users by their ID or username, retrieving multiple users by IDs or usernames, and searching for users. ```typescript // Get authenticated user const me = await client.users.getMe({ userFields: ['id', 'name', 'username', 'description', 'profile_image_url'] }); console.log(me.data.username); // Get user by ID const user = await client.users.getById('783214', { userFields: ['id', 'name', 'username', 'public_metrics'], expansions: ['pinned_tweet_id'] }); // Get user by username const user = await client.users.getByUsername('elonmusk', { userFields: ['id', 'name', 'description', 'verified'] }); // Get multiple users by IDs const users = await client.users.getByIds(['783214', '12'], { userFields: ['id', 'name', 'username'] }); // Get multiple users by usernames const users = await client.users.getByUsernames(['elonmusk', 'x'], { userFields: ['id', 'name', 'public_metrics'] }); // Search users const searchResults = await client.users.search('developers', { maxResults: 20, userFields: ['id', 'name', 'username', 'description'] }); ``` -------------------------------- ### GET /users/affiliates Source: https://context7.com/xdevplatform/xdk-typescript/llms.txt Retrieve a list of affiliated users associated with an organization account. ```APIDOC ## GET /users/affiliates ### Description Fetches a list of users affiliated with a specific organization account. ### Method GET ### Endpoint /users/:id/affiliates ### Parameters #### Path Parameters - **id** (string) - Required - The organization user ID. #### Query Parameters - **maxResults** (number) - Optional - Maximum number of results to return. - **userFields** (array) - Optional - Fields to include in the response (e.g., id, name, username). ### Response #### Success Response (200) - **data** (array) - List of affiliated user objects. ``` -------------------------------- ### Search Posts with XDK TypeScript Source: https://context7.com/xdevplatform/xdk-typescript/llms.txt Search for posts using various criteria such as recent posts or full archive search. Supports filtering by keywords, time range, and sorting. Also provides functionality to get post counts for specified periods. Requires appropriate API access for full archive search. ```typescript // Search recent posts (last 7 days) const recentPosts = await client.posts.searchRecent('typescript sdk', { maxResults: 100, tweetFields: ['id', 'text', 'created_at', 'author_id'], startTime: '2024-01-01T00:00:00Z', endTime: '2024-01-07T00:00:00Z', sortOrder: 'recency' }); // Search all posts (full archive - requires Academic Research access) const allPosts = await client.posts.searchAll('from:elonmusk', { maxResults: 500, tweetFields: ['text', 'public_metrics'] }); // Get post counts for recent period const counts = await client.posts.getCountsRecent('typescript', { granularity: 'day' }); // Get post counts for full archive const allCounts = await client.posts.getCountsAll('typescript', { granularity: 'hour', startTime: '2023-01-01T00:00:00Z', endTime: '2023-12-31T23:59:59Z' }); ``` -------------------------------- ### Initialize XDK Client Source: https://github.com/xdevplatform/xdk-typescript/blob/main/README.md Demonstrates how to authenticate and initialize the XDK client using a bearer token from environment variables. ```typescript import { Client } from '@xdevplatform/xdk'; const client = new Client({ bearerToken: process.env.X_API_BEARER_TOKEN }); ``` -------------------------------- ### OAuth2 Authentication with PKCE using Xdev Platform XDK Source: https://context7.com/xdevplatform/xdk-typescript/llms.txt Illustrates the process of setting up and managing OAuth2 authentication with PKCE using the XDK. This includes initializing the OAuth2 handler, setting PKCE parameters, generating authorization URLs, exchanging codes for tokens, refreshing tokens, and managing token storage. ```typescript import { OAuth2 } from '@xdevplatform/xdk'; // Initialize OAuth2 handler const oauth2 = new OAuth2({ clientId: 'your-client-id', clientSecret: 'your-client-secret', // Optional for public clients redirectUri: 'https://your-app.com/callback', scope: ['tweet.read', 'tweet.write', 'users.read', 'offline.access'] }); // Set up PKCE parameters await oauth2.setPkceParameters(codeVerifier); // Get authorization URL const authUrl = await oauth2.getAuthorizationUrl('state-token'); // Redirect user to authUrl // Exchange authorization code for tokens const token = await oauth2.exchangeCode(authorizationCode, codeVerifier); // Refresh access token const newToken = await oauth2.refreshToken(); // Check token expiration if (oauth2.isTokenExpired()) { await oauth2.refreshToken(); } // Store and restore tokens oauth2.setToken(storedToken, expiresAt); const currentToken = oauth2.getToken(); ``` -------------------------------- ### Initialize XDK Client Source: https://github.com/xdevplatform/xdk-typescript/blob/main/README.md Basic initialization of the XDK client for use in environments like React Native or standard Node.js applications. ```javascript import { Client } from '@xdevplatform/xdk'; const client = new Client({ bearerToken: 'your-token' }); ``` -------------------------------- ### Initialize Xdev Platform XDK Client Source: https://context7.com/xdevplatform/xdk-typescript/llms.txt Demonstrates how to initialize the main XDK client using different authentication methods: Bearer Token, OAuth2 User Token, and OAuth1. It also shows full configuration options including base URL, timeout, retries, and custom headers. ```typescript import { Client } from '@xdevplatform/xdk'; // Bearer token authentication (app-only) const client = new Client({ bearerToken: 'your-bearer-token' }); // OAuth2 User Token authentication const client = new Client({ accessToken: 'your-oauth2-access-token' }); // OAuth1 authentication const client = new Client({ oauth1: oauth1Instance }); // Full configuration options const client = new Client({ bearerToken: 'your-bearer-token', baseUrl: 'https://api.x.com', timeout: 30000, retry: true, maxRetries: 3, headers: { 'Custom-Header': 'value' } }); ``` -------------------------------- ### Manage Real-time Streaming Source: https://github.com/xdevplatform/xdk-typescript/blob/main/README.md Demonstrates how to connect to live data feeds, process events via listeners or async iteration, and manage stream lifecycle. ```typescript import { Client } from '@xdevplatform/xdk'; const client: Client = new Client({ bearerToken: 'your-bearer-token' }); const stream = await client.stream.postsSample({ tweetfields: ['id','text','created_at'] }); // Event-driven stream.on('data', (event) => console.log(event)); // Async iteration for await (const event of stream) { console.log(event); } // Lifecycle management stream.close(); ``` -------------------------------- ### Fetch User Data with Bearer Token Source: https://github.com/xdevplatform/xdk-typescript/blob/main/README.md Demonstrates how to authenticate using a Bearer token and retrieve user information from the X API. ```typescript import { Client, type ClientConfig, type UsersGetByUsernameResponse } from '@xdevplatform/xdk'; const config: ClientConfig = { bearerToken: 'your-bearer-token' }; const client: Client = new Client(config); async function main(): Promise { const userResponse: UsersGetByUsernameResponse = await client.users.getByUsername('XDevelopers'); const username: string = userResponse.data?.username!; console.log(username); } main(); ``` -------------------------------- ### Implement Pagination Source: https://github.com/xdevplatform/xdk-typescript/blob/main/README.md Covers various methods for handling paginated API responses, including manual fetching, async iteration, and handling rate limits. ```typescript import { Client, UserPaginator, PaginatedResponse, Schemas } from '@xdevplatform/xdk'; const client: Client = new Client({ bearerToken: 'your-bearer-token' }); const followers: UserPaginator = new UserPaginator( async (token?: string): Promise> => { const res = await client.users.getFollowers('', { maxResults: 100, paginationToken: token, userfields: ['id','name','username'], }); return { data: res.data ?? [], meta: res.meta, includes: res.includes, errors: res.errors }; } ); // Manual paging await followers.fetchNext(); while (!followers.done) { await followers.fetchNext(); } // Async iteration for await (const user of followers) { console.log(user.username); } // Error handling try { await followers.fetchNext(); } catch (err) { if (followers.rateLimited) console.error('Rate limited'); } ``` -------------------------------- ### Manage Posts with XDK TypeScript Source: https://context7.com/xdevplatform/xdk-typescript/llms.txt Create, retrieve, and manage posts including text, media, and replies. Supports fetching posts by ID or multiple IDs, and deleting or hiding posts. Requires a client instance configured for the API. ```typescript // Create a new post const post = await client.posts.create({ text: 'Hello from XDK!' }); console.log(`Created post: ${post.data.id}`); // Create a post with media const postWithMedia = await client.posts.create({ text: 'Check out this image!', media: { mediaIds: ['media-id-here'] } }); // Create a reply const reply = await client.posts.create({ text: 'This is a reply', reply: { inReplyToTweetId: '1234567890' } }); // Get post by ID const post = await client.posts.getById('1234567890', { tweetFields: ['id', 'text', 'created_at', 'public_metrics'], expansions: ['author_id'], userFields: ['name', 'username'] }); // Get multiple posts by IDs const posts = await client.posts.getByIds(['id1', 'id2', 'id3'], { tweetFields: ['text', 'public_metrics'] }); // Delete a post await client.posts.delete('1234567890'); // Hide/unhide a reply await client.posts.hideReply('1234567890', { body: { hidden: true } }); ``` -------------------------------- ### Authenticate with OAuth 2.0 PKCE Source: https://github.com/xdevplatform/xdk-typescript/blob/main/README.md Implements the OAuth 2.0 flow with PKCE, including generating challenges and exchanging authorization codes for tokens. ```typescript import { Client, OAuth2, generateCodeVerifier, generateCodeChallenge, type OAuth2Config, type ClientConfig, type OAuth2Token } from '@xdevplatform/xdk'; (async (): Promise => { const oauth2Config: OAuth2Config = { clientId: 'your-client-id', clientSecret: 'your-client-secret', redirectUri: 'https://example.com', scope: ['tweet.read', 'users.read', 'offline.access'], }; const oauth2: OAuth2 = new OAuth2(oauth2Config); const codeVerifier: string = generateCodeVerifier(); const codeChallenge: string = await generateCodeChallenge(codeVerifier); oauth2.setPkceParameters(codeVerifier, codeChallenge); const authUrl: string = await oauth2.getAuthorizationUrl('example-state'); const tokens: OAuth2Token = await oauth2.exchangeCode(authCode, codeVerifier); const client: Client = new Client({ accessToken: tokens.access_token }); }); ``` -------------------------------- ### Authenticate with OAuth 1.0a Source: https://github.com/xdevplatform/xdk-typescript/blob/main/README.md Configures the XDK client using OAuth 1.0a credentials for user-context operations. ```typescript import { Client, OAuth1, type OAuth1Config, type ClientConfig, type Users } from '@xdevplatform/xdk'; const oauth1Config: OAuth1Config = { apiKey: 'your-api-key', apiSecret: 'your-api-secret', accessToken: 'user-access-token', accessTokenSecret: 'user-access-token-secret' }; const oauth1: OAuth1 = new OAuth1(oauth1Config); const config: ClientConfig = { oauth1: oauth1 }; const client: Client = new Client(config); async function main(): Promise { const response: Users.GetMeResponse = await client.users.getMe(); console.log(response.data); } main(); ``` -------------------------------- ### Bookmarks API Source: https://context7.com/xdevplatform/xdk-typescript/llms.txt Endpoints for managing user bookmarks, including retrieving bookmarks, creating, deleting, and organizing them into folders. ```APIDOC ## GET /users/{id}/bookmarks ### Description Retrieves a user's bookmarked posts. ### Method GET ### Endpoint /users/{id}/bookmarks ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the user. #### Query Parameters - **maxResults** (integer) - Optional - The maximum number of results to return (default 10, max 100). - **tweetFields** (array) - Optional - Fields to include for each bookmarked post. ### Response #### Success Response (200) - **data** (array of objects) - A list of bookmarked post objects. - **meta** (object) - Metadata about the results. #### Response Example ```json { "data": [ { "id": "bookmarked-post-id", "text": "Bookmarked post content" } ], "meta": { "result_count": 1 } } ``` ## POST /users/{id}/bookmarks ### Description Creates a bookmark for a specific post for a user. ### Method POST ### Endpoint /users/{id}/bookmarks ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the user. #### Request Body - **tweetId** (string) - Required - The ID of the post to bookmark. ### Request Example ```json { "tweetId": "1234567890" } ``` ### Response #### Success Response (200) - **data** (object) - Confirmation of the bookmark creation, typically with a boolean success flag. #### Response Example ```json { "data": { "bookmarked": true } } ``` ## DELETE /users/{id}/bookmarks/{tweet_id} ### Description Deletes a specific bookmarked post for a user. ### Method DELETE ### Endpoint /users/{id}/bookmarks/{tweet_id} ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the user. - **tweet_id** (string) - Required - The ID of the bookmarked post to delete. ### Response #### Success Response (200) - **data** (object) - Confirmation of the bookmark deletion, typically with a boolean success flag. #### Response Example ```json { "data": { "deleted": true } } ``` ## GET /users/{id}/bookmark_folders ### Description Retrieves a list of bookmark folders for a user. ### Method GET ### Endpoint /users/{id}/bookmark_folders ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the user. ### Response #### Success Response (200) - **data** (array of objects) - A list of bookmark folder objects. #### Response Example ```json { "data": [ { "id": "folder-id-1", "name": "Folder One" } ] } ``` ## GET /users/{id}/bookmarks?folder_id={folder_id} ### Description Retrieves bookmarked posts from a specific folder for a user. ### Method GET ### Endpoint /users/{id}/bookmarks ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the user. #### Query Parameters - **folder_id** (string) - Required - The ID of the bookmark folder. - **maxResults** (integer) - Optional - The maximum number of results to return (default 10, max 100). - **tweetFields** (array) - Optional - Fields to include for each bookmarked post. ### Response #### Success Response (200) - **data** (array of objects) - A list of bookmarked post objects within the specified folder. - **meta** (object) - Metadata about the results. #### Response Example ```json { "data": [ { "id": "bookmarked-post-id", "text": "Bookmarked post in folder" } ], "meta": { "result_count": 1 } } ``` ``` -------------------------------- ### Connect to Real-time Streams Source: https://context7.com/xdevplatform/xdk-typescript/llms.txt Initializes a connection to the real-time streaming interface via the StreamClient. Implementation details vary based on specific stream configuration. ```typescript const stream = client.stream; ``` -------------------------------- ### Posts API Source: https://context7.com/xdevplatform/xdk-typescript/llms.txt Endpoints for creating, retrieving, managing, and deleting posts. Supports creating posts with text, media, and replies, fetching posts by ID or multiple IDs, and deleting posts. ```APIDOC ## POST /posts ### Description Creates a new post. Supports adding text, media, and replying to existing posts. ### Method POST ### Endpoint /posts ### Parameters #### Request Body - **text** (string) - Required - The content of the post. - **media** (object) - Optional - Media to attach to the post. Example: `{ mediaIds: ['media-id-here'] }`. - **reply** (object) - Optional - Information for creating a reply. Example: `{ inReplyToTweetId: '1234567890' }`. ### Request Example ```json { "text": "Hello from XDK!", "media": {"mediaIds": ["media-id-here"]}, "reply": {"inReplyToTweetId": "1234567890"} } ``` ### Response #### Success Response (200) - **data** (object) - The created post object, including its ID. #### Response Example ```json { "data": { "id": "post-id-here", "text": "Hello from XDK!" } } ``` ## GET /posts/{id} ### Description Retrieves a specific post by its ID, with options to expand related data and specify fields. ### Method GET ### Endpoint /posts/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the post to retrieve. #### Query Parameters - **tweetFields** (array) - Optional - Fields to include for the post (e.g., `['id', 'text', 'created_at', 'public_metrics']`). - **expansions** (array) - Optional - Fields to expand (e.g., `['author_id']`). - **userFields** (array) - Optional - Fields to include for expanded user data (e.g., `['name', 'username']`). ### Response #### Success Response (200) - **data** (object) - The requested post object. - **includes** (object) - Included related data (e.g., author information). #### Response Example ```json { "data": { "id": "1234567890", "text": "Example post text" }, "includes": { "users": [ { "id": "author-id", "name": "Author Name" } ] } } ``` ## GET /posts ### Description Retrieves multiple posts by their IDs. ### Method GET ### Endpoint /posts ### Parameters #### Query Parameters - **ids** (array of strings) - Required - A list of post IDs to retrieve. - **tweetFields** (array) - Optional - Fields to include for each post. ### Response #### Success Response (200) - **data** (array of objects) - A list of post objects. #### Response Example ```json { "data": [ { "id": "id1", "text": "Post 1 text" }, { "id": "id2", "text": "Post 2 text" } ] } ``` ## DELETE /posts/{id} ### Description Deletes a specific post by its ID. ### Method DELETE ### Endpoint /posts/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the post to delete. ### Response #### Success Response (200) - **data** (object) - Confirmation of deletion, typically with a boolean success flag. #### Response Example ```json { "data": { "deleted": true } } ``` ## PUT /posts/{id}/hide ### Description Hides or unhides a reply to a post. ### Method PUT ### Endpoint /posts/{id}/hide ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the reply post to hide or unhide. #### Request Body - **hidden** (boolean) - Required - Set to `true` to hide, `false` to unhide. ### Request Example ```json { "hidden": true } ``` ### Response #### Success Response (200) - **data** (object) - Confirmation of the hide/unhide action. #### Response Example ```json { "data": { "hidden": true } } ``` ``` -------------------------------- ### Manage Bookmarks with XDK TypeScript Source: https://context7.com/xdevplatform/xdk-typescript/llms.txt Manage user bookmarks, including retrieving all bookmarks, bookmarks from specific folders, creating new bookmarks, and deleting existing ones. Requires a user ID and optionally a folder ID. Supports specifying fields for retrieved bookmarks. ```typescript // Get user's bookmarks const bookmarks = await client.users.getBookmarks('my-user-id', { maxResults: 100, tweetFields: ['id', 'text', 'author_id'] }); // Create a bookmark await client.users.createBookmark('my-user-id', { tweetId: '1234567890' }); // Delete a bookmark await client.users.deleteBookmark('my-user-id', '1234567890'); // Get bookmark folders const folders = await client.users.getBookmarkFolders('my-user-id'); // Get bookmarks from a specific folder const folderBookmarks = await client.users.getBookmarksByFolderId( 'my-user-id', 'folder-id' ); ``` -------------------------------- ### Authentication Management Source: https://context7.com/xdevplatform/xdk-typescript/llms.txt Methods for validating authentication status, retrieving supported auth types, and managing token lifecycles. ```APIDOC ## Authentication Validation ### Description Provides utilities to check the current authentication status of the client, list supported authentication mechanisms, and handle token expiration for OAuth2 flows. ### Methods - `client.isAuthenticated()`: Returns boolean status. - `client.getAvailableAuthTypes()`: Returns array of supported strings. - `client.isTokenExpired()`: Checks OAuth2 token validity. - `client.refreshToken()`: Refreshes the current session token. ### Response Example { "authTypes": ["bearer_token", "oauth2_user_context", "oauth1"] } ``` -------------------------------- ### Utilize Pagination with XDK TypeScript Source: https://context7.com/xdevplatform/xdk-typescript/llms.txt Demonstrates XDK's automatic and manual pagination features using async iterators and the Paginator class. Allows for effortless fetching of paginated data, controlling pagination flow, and accessing metadata. Requires the Paginator class and a client instance. ```typescript import { Paginator } from '@xdevplatform/xdk'; // Automatic iteration with for await...of const followers = await client.users.getFollowers('783214'); for await (const follower of followers) { console.log(follower.username); // Automatically fetches next pages as needed } // Manual pagination control const paginator = new Paginator(async (token) => { return client.users.getFollowers('783214', { paginationToken: token }); }); // Fetch first page await paginator.fetchNext(); console.log(`Fetched ${paginator.items.length} followers`); // Check if more pages are available while (!paginator.done) { await paginator.fetchNext(); console.log(`Total: ${paginator.items.length} followers`); } // Access pagination metadata console.log(paginator.meta.nextToken); console.log(paginator.meta.resultCount); // Get items as array const allFollowers = paginator.items; // Check rate limit status if (paginator.rateLimited) { console.log('Rate limit reached, try again later'); } // Fetch specific number of additional items await paginator.fetchLast(500); // Get next page as new instance const nextPage = await paginator.next(); // Reset paginator to start over paginator.reset(); ``` -------------------------------- ### Validate Authentication and Manage Tokens Source: https://context7.com/xdevplatform/xdk-typescript/llms.txt Demonstrates how to check authentication status, retrieve supported auth types, and handle OAuth2 token expiration. Requires a configured client instance. ```typescript if (client.isAuthenticated()) { console.log('Client has valid credentials'); } const authTypes = client.getAvailableAuthTypes(); if (client.isTokenExpired()) { await client.refreshToken(); } ``` -------------------------------- ### Retrieve User Affiliates Source: https://context7.com/xdevplatform/xdk-typescript/llms.txt Fetches a list of affiliated users for a given organization account. Supports pagination parameters and field selection. ```typescript const affiliates = await client.users.getAffiliates('org-user-id', { maxResults: 100, userFields: ['id', 'name', 'username'] }); ``` -------------------------------- ### Retrieve Post Analytics and Insights with XDK TypeScript Source: https://context7.com/xdevplatform/xdk-typescript/llms.txt Enables fetching detailed analytics and engagement metrics for posts. Supports retrieving general post analytics, 28-hour insights, and historical insights over specified date ranges and intervals. Requires post IDs and date parameters. ```typescript // Get post analytics const analytics = await client.posts.getAnalytics( ['id1', 'id2', 'id3'], '2024-01-31T23:59:59Z', '2024-01-01T00:00:00Z', 'day', { analyticsFields: ['impressions', 'engagements'] } ); // Get 28-hour insights const insights28hr = await client.posts.getInsights28hr( ['id1', 'id2'], 'hour', ['impressions', 'likes', 'retweets'] ); // Get historical insights const historicalInsights = await client.posts.getInsightsHistorical( ['id1', 'id2'], '2024-01-31T23:59:59Z', '2024-01-01T00:00:00Z', 'day', ['impressions', 'engagements'] ); ``` -------------------------------- ### Manage Lists with XDK TypeScript Source: https://context7.com/xdevplatform/xdk-typescript/llms.txt Interact with user-owned, followed, and pinned lists. This includes fetching lists, following/unfollowing, and pinning/unpinning lists. Requires a client instance and user/list identifiers. ```typescript // Get lists owned by a user const ownedLists = await client.users.getOwnedLists('783214', { maxResults: 25, listFields: ['id', 'name', 'member_count'] }); // Get lists a user follows const followedLists = await client.users.getFollowedLists('783214'); // Get pinned lists const pinnedLists = await client.users.getPinnedLists('my-user-id'); // Get list memberships const memberships = await client.users.getListMemberships('783214'); // Follow a list await client.users.followList('my-user-id', { body: { listId: 'list-id' } }); // Unfollow a list await client.users.unfollowList('my-user-id', 'list-id'); // Pin a list await client.users.pinList('my-user-id', { listId: 'list-id' }); // Unpin a list await client.users.unpinList('my-user-id', 'list-id'); ``` -------------------------------- ### Post Search API Source: https://context7.com/xdevplatform/xdk-typescript/llms.txt Endpoints for searching posts using keywords and date ranges, and retrieving counts of posts. ```APIDOC ## GET /posts/search/recent ### Description Searches for posts created within the last 7 days based on a query. ### Method GET ### Endpoint /posts/search/recent ### Parameters #### Query Parameters - **query** (string) - Required - The search query. - **maxResults** (integer) - Optional - The maximum number of results to return (default 10, max 100). - **tweetFields** (array) - Optional - Fields to include for each post. - **startTime** (string) - Optional - ISO 8601 timestamp for the start of the search period. - **endTime** (string) - Optional - ISO 8601 timestamp for the end of the search period. - **sortOrder** (string) - Optional - Sort order for results (`recency` or `relevancy`). ### Response #### Success Response (200) - **data** (array of objects) - A list of matching post objects. - **meta** (object) - Metadata about the search results. #### Response Example ```json { "data": [ { "id": "post-id", "text": "Search result post" } ], "meta": { "result_count": 1 } } ``` ## GET /posts/search/all ### Description Searches for posts across the full archive. Requires Academic Research access. ### Method GET ### Endpoint /posts/search/all ### Parameters #### Query Parameters - **query** (string) - Required - The search query. - **maxResults** (integer) - Optional - The maximum number of results to return (default 10, max 500). - **tweetFields** (array) - Optional - Fields to include for each post. ### Response #### Success Response (200) - **data** (array of objects) - A list of matching post objects. - **meta** (object) - Metadata about the search results. #### Response Example ```json { "data": [ { "id": "post-id", "text": "Archive search result" } ], "meta": { "result_count": 1 } } ``` ## GET /posts/counts/recent ### Description Gets the count of posts matching a query for a recent period, with daily granularity. ### Method GET ### Endpoint /posts/counts/recent ### Parameters #### Query Parameters - **query** (string) - Required - The search query. - **granularity** (string) - Optional - The time granularity for counts (`day`, `hour`, `minute`). ### Response #### Success Response (200) - **data** (array of objects) - An array of count objects, each with a `period` and `tweet_count`. #### Response Example ```json { "data": [ { "period": "2024-01-01T00:00:00Z", "tweet_count": 150 } ] } ``` ## GET /posts/counts/all ### Description Gets the count of posts matching a query across the full archive. ### Method GET ### Endpoint /posts/counts/all ### Parameters #### Query Parameters - **query** (string) - Required - The search query. - **granularity** (string) - Optional - The time granularity for counts (`day`, `hour`, `minute`). - **startTime** (string) - Optional - ISO 8601 timestamp for the start of the period. - **endTime** (string) - Optional - ISO 8601 timestamp for the end of the period. ### Response #### Success Response (200) - **data** (array of objects) - An array of count objects, each with a `period` and `tweet_count`. #### Response Example ```json { "data": [ { "period": "2023-01-01T00:00:00Z", "tweet_count": 10000 } ] } ``` ``` -------------------------------- ### POST /users/block-dms Source: https://context7.com/xdevplatform/xdk-typescript/llms.txt Endpoints for managing direct message blocking preferences for specific users. ```APIDOC ## POST /users/block-dms ### Description Blocks direct messages from a specified user. ### Method POST ### Endpoint /users/block-dms ### Parameters #### Request Body - **target-user-id** (string) - Required - The unique identifier of the user to block. ### Response #### Success Response (200) - **status** (string) - Confirmation of the block action. ``` -------------------------------- ### User Timeline and Mentions API Source: https://context7.com/xdevplatform/xdk-typescript/llms.txt Endpoints for accessing a user's timeline, their posts, mentions, liked posts, and reposts of their posts. ```APIDOC ## GET /users/{id}/timeline ### Description Retrieves a user's timeline in reverse chronological order. ### Method GET ### Endpoint /users/{id}/timeline ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the user. #### Query Parameters - **maxResults** (integer) - Optional - The maximum number of results to return (default 10, max 100). - **tweetFields** (array) - Optional - Fields to include for each post. - **exclude** (array) - Optional - Types of posts to exclude (e.g., `['replies', 'retweets']`). ### Response #### Success Response (200) - **data** (array of objects) - A list of post objects in the user's timeline. - **meta** (object) - Metadata about the results. #### Response Example ```json { "data": [ { "id": "post-id-1", "text": "Timeline post 1" } ], "meta": { "result_count": 1 } } ``` ## GET /users/{id}/posts ### Description Retrieves posts created by a specific user. ### Method GET ### Endpoint /users/{id}/posts ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the user. #### Query Parameters - **maxResults** (integer) - Optional - The maximum number of results to return (default 10, max 100). - **tweetFields** (array) - Optional - Fields to include for each post. - **startTime** (string) - Optional - ISO 8601 timestamp for the start of the period. ### Response #### Success Response (200) - **data** (array of objects) - A list of post objects created by the user. - **meta** (object) - Metadata about the results. #### Response Example ```json { "data": [ { "id": "post-id-1", "text": "User post 1" } ], "meta": { "result_count": 1 } } ``` ## GET /users/{id}/mentions ### Description Retrieves posts that mention a specific user. ### Method GET ### Endpoint /users/{id}/mentions ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the user. #### Query Parameters - **maxResults** (integer) - Optional - The maximum number of results to return (default 10, max 100). - **sinceId** (string) - Optional - Returns results with an ID greater than this specified ID. ### Response #### Success Response (200) - **data** (array of objects) - A list of post objects mentioning the user. - **meta** (object) - Metadata about the results. #### Response Example ```json { "data": [ { "id": "mention-post-id", "text": "A post mentioning the user." } ], "meta": { "result_count": 1 } } ``` ## GET /users/{id}/liked_posts ### Description Retrieves posts that a specific user has liked. ### Method GET ### Endpoint /users/{id}/liked_posts ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the user. #### Query Parameters - **maxResults** (integer) - Optional - The maximum number of results to return (default 10, max 100). ### Response #### Success Response (200) - **data** (array of objects) - A list of post objects liked by the user. - **meta** (object) - Metadata about the results. #### Response Example ```json { "data": [ { "id": "liked-post-id", "text": "A post the user liked." } ], "meta": { "result_count": 1 } } ``` ## GET /users/me/reposts ### Description Retrieves reposts of posts made by the authenticated user. ### Method GET ### Endpoint /users/me/reposts ### Parameters #### Query Parameters - **maxResults** (integer) - Optional - The maximum number of results to return (default 10, max 100). ### Response #### Success Response (200) - **data** (array of objects) - A list of repost objects. - **meta** (object) - Metadata about the results. #### Response Example ```json { "data": [ { "id": "repost-id", "author_id": "user-id" } ], "meta": { "result_count": 1 } } ``` ``` -------------------------------- ### Access Raw HTTP Responses Source: https://context7.com/xdevplatform/xdk-typescript/llms.txt Shows how to bypass standard response parsing to access raw HTTP status codes and headers. Useful for inspecting rate limits or custom response metadata. ```typescript const response = await client.users.getById('783214', { requestOptions: { raw: true } }); console.log(response.status); console.log(response.headers.get('x-rate-limit-remaining')); const data = await response.json(); ``` -------------------------------- ### Handle API Errors with XDK TypeScript Source: https://context7.com/xdevplatform/xdk-typescript/llms.txt Provides structured error handling for API requests using the ApiError class. Demonstrates how to catch errors, inspect error properties like status, message, and data, and implement logic for specific HTTP status codes. Requires importing ApiError. ```typescript import { ApiError } from '@xdevplatform/xdk'; try { const user = await client.users.getById('invalid-id'); } catch (error) { if (error instanceof ApiError) { console.log(`Status: ${error.status}`); console.log(`Message: ${error.message}`); console.log(`Status Text: ${error.statusText}`); console.log(`Error Data:`, error.data); // Handle specific error codes if (error.status === 429) { console.log('Rate limited - wait before retrying'); } else if (error.status === 401) { console.log('Authentication failed'); } else if (error.status === 403) { console.log('Forbidden - check permissions'); } else if (error.status === 404) { console.log('Resource not found'); } } } ``` -------------------------------- ### Post Engagement API Source: https://context7.com/xdevplatform/xdk-typescript/llms.txt Endpoints for retrieving and managing engagement metrics for posts, including likes, reposts, and quote tweets. ```APIDOC ## GET /posts/{id}/liking_users ### Description Retrieves a list of users who have liked a specific post. ### Method GET ### Endpoint /posts/{id}/liking_users ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the post. #### Query Parameters - **maxResults** (integer) - Optional - The maximum number of results to return (default 10, max 100). - **userFields** (array) - Optional - Fields to include for each user. ### Response #### Success Response (200) - **data** (array of objects) - A list of user objects who liked the post. - **meta** (object) - Metadata about the results. #### Response Example ```json { "data": [ { "id": "user-id-1", "name": "User One" } ], "meta": { "result_count": 1 } } ``` ## GET /posts/{id}/reposted_by ### Description Retrieves a list of users who have reposted a specific post. ### Method GET ### Endpoint /posts/{id}/reposted_by ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the post. #### Query Parameters - **userFields** (array) - Optional - Fields to include for each user. ### Response #### Success Response (200) - **data** (array of objects) - A list of user objects who reposted the post. - **meta** (object) - Metadata about the results. #### Response Example ```json { "data": [ { "id": "user-id-1", "name": "User One" } ], "meta": { "result_count": 1 } } ``` ## GET /posts/{id}/reposts ### Description Retrieves a list of reposts for a specific post. ### Method GET ### Endpoint /posts/{id}/reposts ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the post. ### Response #### Success Response (200) - **data** (array of objects) - A list of repost objects. #### Response Example ```json { "data": [ { "id": "repost-id", "author_id": "user-id" } ] } ``` ## GET /posts/{id}/quotes ### Description Retrieves a list of quote tweets for a specific post. ### Method GET ### Endpoint /posts/{id}/quotes ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the post. #### Query Parameters - **maxResults** (integer) - Optional - The maximum number of results to return (default 10, max 50). ### Response #### Success Response (200) - **data** (array of objects) - A list of quote tweet objects. - **meta** (object) - Metadata about the results. #### Response Example ```json { "data": [ { "id": "quote-tweet-id", "text": "Quoted tweet text" } ], "meta": { "result_count": 1 } } ``` ## POST /users/{id}/like ### Description Likes a specific post on behalf of a user. ### Method POST ### Endpoint /users/{id}/like ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the user performing the action. #### Request Body - **tweetId** (string) - Required - The ID of the post to like. ### Request Example ```json { "tweetId": "1234567890" } ``` ### Response #### Success Response (200) - **data** (object) - Confirmation of the like action, typically with a boolean success flag. #### Response Example ```json { "data": { "liked": true } } ``` ## DELETE /users/{id}/like ### Description Unlikes a specific post on behalf of a user. ### Method DELETE ### Endpoint /users/{id}/like ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the user performing the action. - **tweetId** (string) - Required - The ID of the post to unlike. ### Response #### Success Response (200) - **data** (object) - Confirmation of the unlike action, typically with a boolean success flag. #### Response Example ```json { "data": { "liked": false } } ``` ## POST /users/{id}/repost ### Description Reposts a specific post on behalf of a user. ### Method POST ### Endpoint /users/{id}/repost ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the user performing the action. #### Request Body - **tweetId** (string) - Required - The ID of the post to repost. ### Request Example ```json { "tweetId": "1234567890" } ``` ### Response #### Success Response (200) - **data** (object) - Confirmation of the repost action, typically with a boolean success flag. #### Response Example ```json { "data": { "reposted": true } } ``` ## DELETE /users/{id}/repost ### Description Unreposts a specific post on behalf of a user. ### Method DELETE ### Endpoint /users/{id}/repost ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the user performing the action. - **tweetId** (string) - Required - The ID of the post to unrepost. ### Response #### Success Response (200) - **data** (object) - Confirmation of the unrepost action, typically with a boolean success flag. #### Response Example ```json { "data": { "reposted": false } } ``` ```