Use the TwexAPI C# SDK to search tweets, scrape Twitter followers, and read X profiles, timelines, replies, and threads. Send DMs, search communities, fetch lists, articles, hashtags, cashtags, and global trending tweets with typed request objects. Like, retweet, follow, and post through documented REST routes. It is a Twitter API alternative for C# services and agents.
REST API | TypeScript SDK | Python SDK | Ruby SDK | Java SDK | Kotlin SDK | Dashboard
Speakeasy generates this SDK.
| Task | REST Route | C# client |
|---|---|---|
| Search tweets without the X API | POST /twitter/advanced_search/page |
sdk.Search.AdvancedAsync(...) |
| Search hashtags or cashtags | POST /twitter/hashtags, POST /twitter/cashtags |
sdk.Search.HashtagsAsync(), sdk.Search.CashtagsAsync() |
| Read an X profile | GET /twitter/{screen_name}/about |
sdk.Users.GetAboutAsync(...) |
| Read a profile timeline | GET /twitter/{screen_name}/timeline/page |
sdk.Timelines.UserPageAsync(...) |
| Scrape Twitter followers | POST /v3/twitter/users/followers |
sdk.Users.Followers.ListAsync(...) |
| Scrape following accounts | POST /v3/twitter/users/following |
sdk.Users.Following.ListAsync(...) |
| Read tweet replies | POST /twitter/tweets/{tweet_id}/replies/page |
sdk.Tweets.Replies.PageAsync(...) |
| Read a tweet thread | POST /twitter/tweets/thread_by_id |
sdk.Tweets.ThreadAsync(...) |
| Send or read DMs | /v3/twitter/send-dm, /v3/twitter/dm-history |
sdk.Dm |
| Search communities | POST /twitter/community/search |
sdk.Communities.SearchAsync(...) |
| Get global trending tweets | GET /twitter/global-trending/tweets |
sdk.Trending.TweetsAsync(...) |
| Post or reply | POST /twitter/tweets/create |
sdk.Tweets.Actions.CreateAsync(...) |
- Package:
XapiScraper - Source: twexapi-dev/x-api-scraper-csharp
- Docs: docs.twexapi.io
- License: MIT
- Dashboard: twexapi.io/dashboard
X API Scraper: Speakeasy-ready OpenAPI document for the x-api-scraper TypeScript SDK.
The SDK wraps TwexAPI's X/Twitter API surface with bearer-token authentication. Cookie/proxy based endpoints are excluded except tweet actions, follow/unfollow, and v3 DM operations. Paid engagement services, profile mutation, legacy-only operations, and non-v3 follower/following endpoints remain excluded.
Not affiliated with X Corp.
dotnet add package XapiScraper --version 0.1.0NuGet is not published yet. Install from GitHub source until it is:
git clone https://github.com/twexapi-dev/x-api-scraper-csharp.git
cd x-api-scraper-csharp
dotnet add reference src/XapiScraper/XapiScraper.csprojusing System;
using System.Collections.Generic;
using XapiScraper;
using XapiScraper.Models.Components;
var sdk = new XapiScraperSDK(
bearerAuth: Environment.GetEnvironmentVariable("X_API_SCRAPER_KEY")
);
var req = new AdvancedSearchCursorQuery()
{
SearchTerms = new List<string>() { "from:elonmusk" },
SortBy = "Latest",
NextCursor = "",
};
var res = await sdk.Search.AdvancedAsync(req);
Console.WriteLine(res);Get an API key from the TwexAPI dashboard. Pass it as bearerAuth, or set X_API_SCRAPER_KEY.
Write actions (tweet, follow, like, DM send) also need a Twitter cookie or auth_token on the request. Pass them on the operation input.
Keep API keys out of source code, URLs, and logs.
This SDK supports the following security scheme globally:
| Name | Type | Scheme |
|---|---|---|
BearerAuth |
http | HTTP Bearer |
To authenticate with the API the BearerAuth parameter must be set when initializing the SDK client instance. For example:
using System.Collections.Generic;
using XapiScraper;
using XapiScraper.Models.Components;
var sdk = new XapiScraperSDK(bearerAuth: "<YOUR_BEARER_TOKEN_HERE>");
AdvancedSearchCursorQuery req = new AdvancedSearchCursorQuery() {
SearchTerms = new List<string>() {
"<value 1>",
"<value 2>",
"<value 3>",
},
SortBy = "<value>",
NextCursor = "",
};
var res = await sdk.Search.AdvancedAsync(req);
// handle responseAvailable methods
- Balance - Get Balance
- Sentiment - Sentiment Analysis
- Members - Get Community Members
- MembersPage - Get Community Members by Page
- Tweets - Get Community Tweets
- TweetsPage - Get Community Tweets by Page
- Search - Search Community
- Get - Get Community
- SearchTweets - Search Community Tweets
- Status - Check DM Permissions
- Send - Send DM
- History - Get DM History
- Media - Get DM Media
- Conversations - Get Conversations
- Tweets - Get List Tweets
- TweetsPage - Get List Tweets by Page
- Subscribers - Get List Subscribers
- Members - Get List Members
- MembersPage - Get List Members by Page
- Search - Search List
- TweetsAndReplies - Get All Tweets and Replies by User
- UserPage - Get User Timeline by Page
- User - Get User Timeline and Fill Count
- TweetsAndRepliesPage - Get All Tweets and Replies by User by Page
- Countries - List Global Trend Countries
- Topics - List Global Trend Topics
- Contents - List Global Trend Content Tags
- Tweets - Get Global Trending Tweets
- ByCountry - Get Trending Topics
- Detail - Get Tweet Detail
- Thread - Get Tweet Thread by ID
- Lookup - Batch Get Tweets by ID
- Similar - Get Similar Tweets
- Like - Like a Tweet
- Unlike - Unlike a Tweet
- Retweet - Retweet a Tweet
- Unretweet - Delete Retweet
- CreateThread - Create a Tweet Thread
- Create - Create a Tweet or Reply
- Quote - Create a Quote Tweet
- CreateWithoutCookie - Post Tweet (Auto Cookie)
- Bookmark - Bookmark a Tweet
- Unbookmark - Delete Bookmark
- DeleteBatch - Delete One or More Tweets
- Retweeters - Get Retweeters
- RetweetersPage - Get Retweeters by Page
- Quotes - Get Quote Tweets
- QuotesPage - Get Quote Tweets by Page
- Page - Get Replies by Page
- GetByUsernames - Get Multiple Users by Usernames
- GetByIds - Users Details by ID
- VerifyAccount - Verify Account Status
- GetStatuses - Batch Get User account status
- Search - Search User
- Follow - Follow User
- Unfollow - Unfollow User
- GetAccountBased - Get Twitter Account Based in
- GetAbout - Get Twitter User About by Screen Name
- List - Get Following (v3)
Some of the endpoints in this SDK support retries. If you use the SDK without any configuration, it will fall back to the default retry strategy provided by the API. However, the default retry strategy can be overridden on a per-operation basis, or across the entire SDK.
To change the default retry strategy for a single API call, simply pass a RetryConfig to the call:
using System.Collections.Generic;
using XapiScraper;
using XapiScraper.Models.Components;
var sdk = new XapiScraperSDK(bearerAuth: "<YOUR_BEARER_TOKEN_HERE>");
AdvancedSearchCursorQuery req = new AdvancedSearchCursorQuery() {
SearchTerms = new List<string>() {
"<value 1>",
"<value 2>",
"<value 3>",
},
SortBy = "<value>",
NextCursor = "",
};
var res = await sdk.Search.AdvancedAsync(
retryConfig: new RetryConfig(
strategy: RetryConfig.RetryStrategy.BACKOFF,
backoff: new BackoffStrategy(
initialIntervalMs: 1L,
maxIntervalMs: 50L,
maxElapsedTimeMs: 100L,
exponent: 1.1
),
retryConnectionErrors: false
),
request: req
);
// handle responseIf you'd like to override the default retry strategy for all operations that support retries, you can use the RetryConfig optional parameter when intitializing the SDK:
using System.Collections.Generic;
using XapiScraper;
using XapiScraper.Models.Components;
var sdk = new XapiScraperSDK(
retryConfig: new RetryConfig(
strategy: RetryConfig.RetryStrategy.BACKOFF,
backoff: new BackoffStrategy(
initialIntervalMs: 1L,
maxIntervalMs: 50L,
maxElapsedTimeMs: 100L,
exponent: 1.1
),
retryConnectionErrors: false
),
bearerAuth: "<YOUR_BEARER_TOKEN_HERE>"
);
AdvancedSearchCursorQuery req = new AdvancedSearchCursorQuery() {
SearchTerms = new List<string>() {
"<value 1>",
"<value 2>",
"<value 3>",
},
SortBy = "<value>",
NextCursor = "",
};
var res = await sdk.Search.AdvancedAsync(req);
// handle responseXapiScraperException is the base exception class for all HTTP error responses. It has the following properties:
| Property | Type | Description |
|---|---|---|
Message |
string | Error message |
Request |
HttpRequestMessage | HTTP request object |
Response |
HttpResponseMessage | HTTP response object |
Some exceptions in this SDK include an additional Payload field, which will contain deserialized custom error data when present. Possible exceptions are listed in the Error Classes section.
using System.Collections.Generic;
using XapiScraper;
using XapiScraper.Models.Components;
using XapiScraper.Models.Errors;
var sdk = new XapiScraperSDK(bearerAuth: "<YOUR_BEARER_TOKEN_HERE>");
try
{
AdvancedSearchCursorQuery req = new AdvancedSearchCursorQuery() {
SearchTerms = new List<string>() {
"<value 1>",
"<value 2>",
"<value 3>",
},
SortBy = "<value>",
NextCursor = "",
};
var res = await sdk.Search.AdvancedAsync(req);
// handle response
}
catch (XapiScraperException ex) // all SDK exceptions inherit from XapiScraperException
{
// ex.ToString() provides a detailed error message
System.Console.WriteLine(ex);
// Base exception fields
HttpRequestMessage request = ex.Request;
HttpResponseMessage response = ex.Response;
var statusCode = (int)response.StatusCode;
var responseBody = ex.Body;
if (ex is HTTPValidationError) // different exceptions may be thrown depending on the method
{
// Check error data fields
HTTPValidationErrorPayload payload = ex.Payload;
List<ValidationError> Detail = payload.Detail;
HTTPMetadata HttpMeta = payload.HttpMeta;
}
// An underlying cause may be provided
if (ex.InnerException != null)
{
Exception cause = ex.InnerException;
}
}
catch (OperationCanceledException ex)
{
// CancellationToken was cancelled
}
catch (System.Net.Http.HttpRequestException ex)
{
// Check ex.InnerException for Network connectivity errors
}Primary exceptions:
XapiScraperException: The base class for HTTP error responses.HTTPValidationError: Validation Error. Status code422. *
Less common exceptions (2)
-
System.Net.Http.HttpRequestException: Network connectivity error. For more details about the underlying cause, inspect theex.InnerException. -
Inheriting from
XapiScraperException:ResponseValidationError: Thrown when the response data could not be deserialized into the expected type.
* Refer to the relevant documentation to determine whether an exception applies to a specific operation.
You can override the default server globally by passing a server name to the server: string optional parameter when initializing the SDK client instance. The selected server will then be used as the default on the operations that use it. This table lists the names associated with the available servers:
| Name | Server | Description |
|---|---|---|
production |
https://api.twexapi.io |
TwexAPI production API |
using System.Collections.Generic;
using XapiScraper;
using XapiScraper.Models.Components;
var sdk = new XapiScraperSDK(
server: SDKConfig.Server.Production,
bearerAuth: "<YOUR_BEARER_TOKEN_HERE>"
);
AdvancedSearchCursorQuery req = new AdvancedSearchCursorQuery() {
SearchTerms = new List<string>() {
"<value 1>",
"<value 2>",
"<value 3>",
},
SortBy = "<value>",
NextCursor = "",
};
var res = await sdk.Search.AdvancedAsync(req);
// handle responseThe default server can also be overridden globally by passing a URL to the serverUrl: string optional parameter when initializing the SDK client instance. For example:
using System.Collections.Generic;
using XapiScraper;
using XapiScraper.Models.Components;
var sdk = new XapiScraperSDK(
serverUrl: "https://api.twexapi.io",
bearerAuth: "<YOUR_BEARER_TOKEN_HERE>"
);
AdvancedSearchCursorQuery req = new AdvancedSearchCursorQuery() {
SearchTerms = new List<string>() {
"<value 1>",
"<value 2>",
"<value 3>",
},
SortBy = "<value>",
NextCursor = "",
};
var res = await sdk.Search.AdvancedAsync(req);
// handle responseThe C# SDK makes API calls using an ISpeakeasyHttpClient that wraps the native
HttpClient. This
client provides the ability to attach hooks around the request lifecycle that can be used to modify the request or handle
errors and response.
The ISpeakeasyHttpClient interface allows you to either use the default SpeakeasyHttpClient that comes with the SDK,
or provide your own custom implementation with customized configuration such as custom message handlers, timeouts,
connection pooling, and other HTTP client settings.
The following example shows how to create a custom HTTP client with request modification and error handling:
using XapiScraper;
using XapiScraper.Utils;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
// Create a custom HTTP client
public class CustomHttpClient : ISpeakeasyHttpClient
{
private readonly ISpeakeasyHttpClient _defaultClient;
public CustomHttpClient()
{
_defaultClient = new SpeakeasyHttpClient();
}
public async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken? cancellationToken = null)
{
// Add custom header and timeout
request.Headers.Add("x-custom-header", "custom value");
request.Headers.Add("x-request-timeout", "30");
try
{
var response = await _defaultClient.SendAsync(request, cancellationToken);
// Log successful response
Console.WriteLine($"Request successful: {response.StatusCode}");
return response;
}
catch (Exception error)
{
// Log error
Console.WriteLine($"Request failed: {error.Message}");
throw;
}
}
public void Dispose()
{
_httpClient?.Dispose();
_defaultClient?.Dispose();
}
}
// Use the custom HTTP client with the SDK
var customHttpClient = new CustomHttpClient();
var sdk = new XapiScraper(client: customHttpClient);You can also provide a completely custom HTTP client with your own configuration:
using XapiScraper.Utils;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
// Custom HTTP client with custom configuration
public class AdvancedHttpClient : ISpeakeasyHttpClient
{
private readonly HttpClient _httpClient;
public AdvancedHttpClient()
{
var handler = new HttpClientHandler()
{
MaxConnectionsPerServer = 10,
// ServerCertificateCustomValidationCallback = customCertValidation, // Custom SSL validation if needed
};
_httpClient = new HttpClient(handler)
{
Timeout = TimeSpan.FromSeconds(30)
};
}
public async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken? cancellationToken = null)
{
return await _httpClient.SendAsync(request, cancellationToken ?? CancellationToken.None);
}
public void Dispose()
{
_httpClient?.Dispose();
}
}
var sdk = XapiScraper.Builder()
.WithClient(new AdvancedHttpClient())
.Build();For simple debugging, you can enable request/response logging by implementing a custom client:
public class LoggingHttpClient : ISpeakeasyHttpClient
{
private readonly ISpeakeasyHttpClient _innerClient;
public LoggingHttpClient(ISpeakeasyHttpClient innerClient = null)
{
_innerClient = innerClient ?? new SpeakeasyHttpClient();
}
public async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken? cancellationToken = null)
{
// Log request
Console.WriteLine($"Sending {request.Method} request to {request.RequestUri}");
var response = await _innerClient.SendAsync(request, cancellationToken);
// Log response
Console.WriteLine($"Received {response.StatusCode} response");
return response;
}
public void Dispose() => _innerClient?.Dispose();
}
var sdk = new XapiScraper(client: new LoggingHttpClient());The SDK also provides built-in hook support through the SDKConfiguration.Hooks system, which automatically handles
BeforeRequestAsync, AfterSuccessAsync, and AfterErrorAsync hooks for advanced request lifecycle management.
This SDK is in beta, and there may be breaking changes between versions without a major version update. Therefore, we recommend pinning usage to a specific package version. This way, you can install the same version each time without breaking changes unless you are intentionally looking for the latest version.
While we value open-source contributions to this SDK, this library is generated programmatically. Any manual changes added to internal files will be overwritten on the next generation. We look forward to hearing your feedback. Feel free to open a PR or an issue with a proof of concept and we'll do our best to include it in a future release.