Twitter (X) API in Rust with reqwest, serde and tokio

By TwitterAPI.io Team•14 min read
Diagram of a Rust Twitter (X) API client: tokio tasks with a Semaphore and rate limiter feed one reqwest::Client with an X-API-Key header, which calls api.twitterapi.io endpoints, whose JSON is decoded by serde structs with Option and serde(default), with next_cursor paging looping back.
The client this guide builds; the struct rules come from 1,133 real tweets collected in 2026.
TL;DR
  • No official Rust SDK. egg-mode (last release 0.16.1, 2023) is marked abandoned in its README; twitter-v2 (0.1.8, 2022) targets X's OAuth API v2. This guide uses plain reqwest + serde against TwitterAPI.io.
  • reqwest 0.13 changed the defaults. json and query are opt-in features, and default-tls now means rustls. Forget query and .query() simply does not exist.
  • Measure your structs. Across 1,133 tweets, 93.9% failed without #[serde(default)] on Vec fields; with it, 26 still failed and sank 15 of 68 pages. An all-default TweetRef for nested tweets got both to 0.
  • Ids are strings. Every id, conversationId and author.id arrived as a JSON string. Keep them String.
  • Paging: loop on has_next_page, never on page size. 46 of 68 pages held fewer than 20 tweets yet had more to come, and 9 ids repeated across pages.
  • Cost: $0.15 per 1,000 tweets returned, versus $0.005 per post read ($5 per 1,000) on X's pay-per-usage rate card, about 33x.

Searching for a Rust Twitter crate in 2026 largely turns up crate listings: wrappers around X's own API that ask for a developer app, OAuth tokens and X's per-read billing, several of them untouched for years. If what you want is tweets, profiles or followers in a Rust service, you do not need any of them. Three crates you already know, reqwest, serde and tokio, are the whole client.

This guide builds that client against TwitterAPI.io step by step: a Cargo.toml that compiles with reqwest 0.13, serde structs whose Option and #[serde(default)] choices come from a measurement rather than a guess, an error enum, 429 backoff, cursor paging as a futures Stream, and bounded concurrency that respects the request-rate tiers. The structs were checked against 1,133 real tweets from 14 Rust-ecosystem accounts, and the numbers below show exactly which fields will panic a strict decoder.

One honest note up front: no Rust toolchain was available where this page was written, so the Rust code was not compiled or run here. The serde behavior it relies on was verified against the serde and docs.rs documentation, and the schema test was run as a Python simulation of serde's rules over the real responses. Build it, run cargo test against your own recorded pages (the Python script at the end records them), and treat a decode error as a fixture to keep.

Tweets that fail a serde struct whose Vec fields lack #[serde(default)]

93.9% of 1,133

01 — Section

Which Rust Twitter crates exist in 2026, and what they talk to

egg-mode. The long-time Rust Twitter library. Its crates.io page lists 0.16.1, published in February 2023, as the latest release, and the first line of its README now reads "abandoned", pointing to an issue that explains why. It was built for X's v1.1 API with consumer keys and access tokens from a developer app.

twitter-v2. Bindings for X's API v2, latest release 0.1.8 from October 2022, last push to its GitHub repository in December 2022. Its README authenticates with a bearer token or OAuth 2.0 user token and notes that many endpoints remain "fairly untested". It works, but every call it makes is billed by X: $0.005 per post read and $0.010 per user read on the current pay-per-usage rate card.

Smaller crates. Search results also surface single-author crates for posting or for v1.1. Before adopting one, check three things on crates.io and GitHub: the date of the last release, whether the README marks it archived or abandoned, and which host it calls. All of them need an X developer account.

What this page builds instead. TwitterAPI.io is a REST API over public X data with flat JSON responses and one header for auth. No SDK is needed for it in any language: an HTTP client and a JSON decoder are the whole integration. In Rust that is reqwest for HTTP, serde for decoding, tokio for the runtime and futures for streams. You can keep a crate like twitter-v2 for the endpoints that require X's own OAuth, and use the client below for reads.

02 — Section

Cargo.toml for reqwest 0.13: json and query are now opt-in

The current releases on crates.io are reqwest 0.13.5, serde 1.0.229, serde_json 1.0.154, tokio 1.54.1, futures 0.3.34 and thiserror 2.0.21. reqwest 0.13 and tokio 1.54 both declare a minimum Rust version of 1.85, which is also the version that introduced the 2024 edition.

The 0.13 trap. reqwest's default features are default-tls, charset, http2 and system-proxy. RequestBuilder::json and RequestBuilder::query are each marked on docs.rs as "available on crate feature" json and query only. Copy a reqwest 0.11 or 0.12 example without those features and you get a "no method named query" compile error, not a runtime one. Turn both on.

TLS. In 0.13 the default-tls feature maps to rustls, so a default build links no OpenSSL. If you need the platform TLS stack, disable default features and enable native-tls.

toml
[package]
name = "x-reader"
version = "0.1.0"
edition = "2024"            # needs Rust 1.85+, the same MSRV reqwest 0.13 and tokio 1.54 declare

[dependencies]
# reqwest 0.13: .json() and .query() are behind opt-in features; default TLS is rustls
reqwest = { version = "0.13", features = ["json", "query"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
tokio = { version = "1", features = ["macros", "rt-multi-thread", "time", "sync"] }
futures = "0.3"
thiserror = "2"
03 — Section

We decoded 1,133 real tweets with four serde schemas

Many Rust tutorials write the struct from one sample response. To see how that holds up, we pulled 1,133 tweets on 68 pages of /twitter/user/last_tweets from 14 public Rust-ecosystem accounts (@rustlang, @tokio_rs, @rust_foundation, @BevyEngine, @zeddotdev and others listed in the method section) and ran every tweet through four schemas, applying serde's rules: a missing field that is not Option or #[serde(default)] is an error, null into a non-Option is an error, and a wrong JSON type is an error.

serde schematweets failingpages failing
Every field a plain type, no Option1,133 of 1,133 (100%)67 of 68 (98.5%)
Option<T> on nullable fields, Vec without #[serde(default)]1,064 (93.9%)67 (98.5%)
Option<T> + #[serde(default)], nested tweets reuse Tweet26 (2.3%)15 (22.1%)
Same, plus an all-default TweetRef for nested tweets0 (0%)0 (0%)

Why pages fail more often than tweets. A page decodes into Vec<Tweet>, and serde aborts the whole Vec on the first bad element. In the third schema only 26 tweets (2.3%) failed, yet they sat on 15 different pages, so 22.1% of pages returned an error and their good tweets were lost too.

What those 26 tweets had in common. Each carried a quoted tweet that arrived as a stub: author was an empty object {} and text was empty, and a few stubs had no id at all. Usually this is a quote of a quote, two levels down. If nested tweets reuse the top-level Tweet struct with required author.userName, that stub fails the page. Giving nested tweets their own struct with #[serde(default)] on the container brought failures to 0 of 1,133.

Make it a test. Record a few pages from the accounts you read (the Python script at the end of this page saves them to tests/fixtures) and decode them in a cargo test. When a new response shape appears, the failing fixture tells you which field to relax.

The middle row is the common mistake. Marking nullable fields Option<T> is the obvious step. The less obvious one is that the arrays inside entities and extendedEntities are frequently missing rather than empty: extendedEntities.media was absent on 75.6% of tweets and entities.hashtags on 66.3%. A Vec<T> field without #[serde(default)] turns each of those into a "missing field" error.

rust
// tests/decode_fixtures.rs: decode every page you recorded (see the Python script below).
use std::fs;
use x_reader::LastTweetsPage;

#[test]
fn recorded_pages_decode() {
    for entry in fs::read_dir("tests/fixtures").unwrap() {
        let path = entry.unwrap().path();
        let raw = fs::read_to_string(&path).unwrap();
        let page: Result<LastTweetsPage, _> = serde_json::from_str(&raw);
        assert!(page.is_ok(), "{}: {}", path.display(), page.unwrap_err());
    }
}
Bar chart of four serde schemas against 1,133 tweets: every field required fails 100% of tweets; Option without default on Vec fails 93.9%; Option plus default fails 2.3% of tweets but 22.1% of pages; an all-default nested struct fails 0.
Share of tweets and of pages that fail to deserialize under each schema; 1,133 tweets on 68 pages collected in 2026 (Python simulation of serde's rules).
04 — Section

Serde structs that match the JSON field by field

The structs below encode what the measurement found. Three details matter more than the rest.

rename_all is not enough. Tweet fields are camelCase (likeCount, createdAt, viewCount), so #[serde(rename_all = "camelCase")] maps like_count correctly. But quoted_tweet and retweeted_tweet arrive in snake_case, and rename_all would look for quotedTweet. Those two need an explicit #[serde(rename = "quoted_tweet")]. Follower records are snake_case throughout (screen_name, followers_count), so that struct has no rename_all at all.

Where the tweets live depends on the endpoint. /twitter/user/last_tweets returns them under data.tweets; /twitter/tweet/advanced_search returns a top-level tweets array; /twitter/user/info returns the profile under data; /twitter/user/followers returns a top-level followers array. has_next_page and next_cursor are top level in all the list responses. One generic page type would hide that difference, so each response gets its own small struct.

Option<T> versus #[serde(default)]. serde's documentation defines default as "if the value is not present when deserializing, use the Default::default()"; it says nothing about null. So use Option<T> where the API sends null (card, quoted_tweet, inReplyToId) and #[serde(default)] where it omits the key (entities.hashtags, extendedEntities.media). The counters were integers on every tweet; the largest viewCount was 178,658,594, inside u32, but u64 costs nothing and removes the question.

fieldhow it arrivedRust type that survives
id, conversationId, author.idJSON string in 1,133 of 1,133String
inReplyToIdnull in 100% (top-level, replies excluded)Option<String>
cardnull in 84%, object in 16%Option<serde_json::Value>
quoted_tweet / retweeted_tweetnull in 85.3% / 63.2%Option<Box<TweetRef>>
extendedEntities{} in 75.6%, media absent in 75.6%struct + #[serde(default)]
entities.hashtags / urls / user_mentionsabsent in 66.3% / 53.1% / 47.7%Vec<T> + #[serde(default)]
place{} in 100%omit, or Option<serde_json::Value>
author.description"" in 100% (use /twitter/user/info for bios)String + default
rust
use serde::Deserialize;

/// One page of /twitter/user/last_tweets: tweets live under `data.tweets`.
#[derive(Debug, Deserialize)]
pub struct LastTweetsPage {
    pub status: Option<String>,
    pub msg: Option<String>,
    pub data: Option<LastTweetsData>,
    #[serde(default)]
    pub has_next_page: bool,
    pub next_cursor: Option<String>,
}

#[derive(Debug, Default, Deserialize)]
pub struct LastTweetsData {
    #[serde(default)]
    pub tweets: Vec<Tweet>,
}

/// One page of /twitter/tweet/advanced_search: `tweets` is top level.
#[derive(Debug, Deserialize)]
pub struct SearchPage {
    #[serde(default)]
    pub tweets: Vec<Tweet>,
    #[serde(default)]
    pub has_next_page: bool,
    pub next_cursor: Option<String>,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Tweet {
    pub id: String,                       // ids are JSON strings: keep them String, never u64
    pub url: String,
    pub text: String,
    pub created_at: String,               // "Thu Oct 16 12:34:56 +0000 2026"
    pub lang: Option<String>,
    #[serde(default)]
    pub like_count: u64,
    #[serde(default)]
    pub retweet_count: u64,
    #[serde(default)]
    pub reply_count: u64,
    #[serde(default)]
    pub quote_count: u64,
    pub view_count: Option<u64>,
    #[serde(default)]
    pub bookmark_count: u64,
    pub conversation_id: Option<String>,
    #[serde(default)]
    pub is_reply: bool,
    pub in_reply_to_id: Option<String>,   // null on every top-level tweet in our sample
    pub in_reply_to_username: Option<String>,
    pub author: Author,
    #[serde(default)]
    pub entities: Entities,               // {} on some tweets, keys inside often absent
    #[serde(default)]
    pub extended_entities: ExtendedEntities,
    pub card: Option<serde_json::Value>,  // null or a large nested object: keep it untyped
    // rename_all would ask for "quotedTweet"; the API sends snake_case here
    #[serde(rename = "quoted_tweet")]
    pub quoted_tweet: Option<Box<TweetRef>>,
    #[serde(rename = "retweeted_tweet")]
    pub retweeted_tweet: Option<Box<TweetRef>>,
}

/// Nested quoted / reposted tweet. Every field defaults, because some arrive as stubs
/// with an empty author object and an empty text.
#[derive(Debug, Default, Deserialize)]
#[serde(rename_all = "camelCase", default)]
pub struct TweetRef {
    pub id: String,
    pub url: String,
    pub text: String,
    pub created_at: String,
    pub like_count: u64,
    pub view_count: Option<u64>,
    pub author: Author,
    pub entities: Entities,
    pub extended_entities: ExtendedEntities,
    #[serde(rename = "quoted_tweet")]
    pub quoted_tweet: Option<Box<TweetRef>>,
}

#[derive(Debug, Default, Deserialize)]
#[serde(rename_all = "camelCase", default)]
pub struct Author {
    pub id: String,
    pub user_name: String,
    pub name: String,
    pub followers: u64,
    pub following: u64,
    pub is_blue_verified: bool,
    pub location: String,
}

#[derive(Debug, Default, Deserialize)]
#[serde(default)]
pub struct Entities {
    pub hashtags: Vec<Hashtag>,
    pub urls: Vec<UrlEntity>,
    pub user_mentions: Vec<Mention>,
}

#[derive(Debug, Default, Deserialize)]
#[serde(default)]
pub struct Hashtag { pub text: String }

#[derive(Debug, Default, Deserialize)]
#[serde(default)]
pub struct UrlEntity { pub expanded_url: String, pub display_url: String }

#[derive(Debug, Default, Deserialize)]
#[serde(default)]
pub struct Mention { pub screen_name: String, pub id_str: String }

#[derive(Debug, Default, Deserialize)]
#[serde(default)]
pub struct ExtendedEntities { pub media: Vec<Media> }

#[derive(Debug, Default, Deserialize)]
#[serde(default)]
pub struct Media {
    #[serde(rename = "type")]
    pub kind: String,                     // photo | video | animated_gif
    pub media_url_https: String,
    pub video_info: Option<serde_json::Value>,
}

/// /twitter/user/info: the profile sits under `data`, camelCase.
#[derive(Debug, Deserialize)]
pub struct UserInfoResponse {
    pub status: Option<String>,
    pub msg: Option<String>,
    pub data: Option<UserInfo>,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct UserInfo {
    pub id: String,
    pub user_name: String,
    pub name: String,
    #[serde(default)]
    pub followers: u64,
    #[serde(default)]
    pub statuses_count: u64,
    pub created_at: Option<String>,
    pub description: Option<String>,
}

/// /twitter/user/followers: snake_case, so no rename_all.
#[derive(Debug, Deserialize)]
pub struct FollowersPage {
    #[serde(default)]
    pub followers: Vec<Follower>,
    #[serde(default)]
    pub has_next_page: bool,
    pub next_cursor: Option<String>,
}

#[derive(Debug, Deserialize)]
pub struct Follower {
    pub id: String,
    pub screen_name: String,
    pub name: Option<String>,
    #[serde(default)]
    pub followers_count: u64,
    pub created_at: Option<String>,
}
Stacked bar chart of twelve tweet fields showing the share present, empty, null and absent across 1,133 tweets: inReplyToId and article null on every tweet, place an empty object on every tweet, extendedEntities.media absent on 75.6%, entities.hashtags absent on 66.3%, viewCount present on every tweet.
How twelve fields arrived across 1,133 tweets collected in 2026: null means use Option<T>, absent means use #[serde(default)].
05 — Section

One shared reqwest::Client, an error enum and 429 backoff

Build the client once. reqwest::Client holds a connection pool behind an Arc, so create it at startup and clone it into tasks; creating one per request throws away keep-alive and TLS sessions. Put the key in a default X-API-Key header and call set_sensitive(true) on the HeaderValue so it never shows up in Debug output or logs. Set both a connect timeout and an overall request timeout.

Map the API's three error styles. A missing or invalid parameter returns HTTP 400 with the reason in detail. A lookup that finds nothing, such as an unknown user on /twitter/user/info, returns HTTP 200 with "status": "error" and the text in msg (user not found), never a 404, so the client checks the envelope before decoding. Too many requests returns HTTP 429. thiserror 2 turns these into one ApiError enum, with #[from] conversions so ? works on reqwest::Error and serde_json::Error.

Back off on 429. The get method below honors a Retry-After header if one is present and otherwise waits 1, 2, 4, 8 and 16 seconds before giving up. Decoding first into serde_json::Value costs one extra pass, but it lets the same method read status, msg and detail for any endpoint before handing the value to the typed struct.

Pace every request. The pace method keeps one shared "next allowed slot" behind a tokio::sync::Mutex, so all clones of the client together stay under the rate you give it. Use 0.2 requests per second before your first payment and up to 20 once paid; higher tiers allow 50 on Scale, 500 on Business and up to 1,000 on request.

rust
use std::{sync::Arc, time::Duration};

use reqwest::header::{HeaderMap, HeaderValue, RETRY_AFTER};
use reqwest::StatusCode;
use serde::de::DeserializeOwned;
use tokio::sync::Mutex;
use tokio::time::{sleep, Instant};

const BASE: &str = "https://api.twitterapi.io";

#[derive(Debug, thiserror::Error)]
pub enum ApiError {
    #[error("transport: {0}")]
    Http(#[from] reqwest::Error),
    #[error("bad request (400): {0}")]
    BadRequest(String),
    #[error("still rate limited (429) after {0} retries")]
    RateLimited(u32),
    #[error("api error: {0}")]
    Api(String),                          // HTTP 200 with "status": "error", text in msg
    #[error("unexpected HTTP {status}: {body}")]
    Status { status: u16, body: String },
    #[error("decode: {0}")]
    Decode(#[from] serde_json::Error),
    #[error("invalid API key header: {0}")]
    Header(#[from] reqwest::header::InvalidHeaderValue),
}

/// Cheap to clone: reqwest::Client is an Arc inside, the pacer is shared on purpose.
#[derive(Clone)]
pub struct XClient {
    http: reqwest::Client,
    next_slot: Arc<Mutex<Instant>>,
    min_gap: Duration,
}

impl XClient {
    /// `requests_per_sec`: 0.2 before your first payment, 20 once paid (see the QPS tiers).
    pub fn new(api_key: &str, requests_per_sec: f64) -> Result<Self, ApiError> {
        let mut key = HeaderValue::from_str(api_key)?;
        key.set_sensitive(true);              // keeps the key out of Debug output
        let mut headers = HeaderMap::new();
        headers.insert("X-API-Key", key);
        let http = reqwest::Client::builder()
            .default_headers(headers)
            .connect_timeout(Duration::from_secs(10))
            .timeout(Duration::from_secs(30))
            .build()?;
        Ok(Self {
            http,
            next_slot: Arc::new(Mutex::new(Instant::now())),
            min_gap: Duration::from_secs_f64(1.0 / requests_per_sec),
        })
    }

    /// Spaces requests across every clone of the client and every task.
    async fn pace(&self) {
        let mut slot = self.next_slot.lock().await;
        let now = Instant::now();
        if *slot > now {
            sleep(*slot - now).await;
        }
        *slot = Instant::now() + self.min_gap;
    }

    pub async fn get<T: DeserializeOwned>(&self, url: &str, query: &[(&str, &str)]) -> Result<T, ApiError> {
        let mut retries = 0u32;
        loop {
            self.pace().await;
            let resp = self.http.get(url).query(query).send().await?;
            let status = resp.status();
            if status == StatusCode::TOO_MANY_REQUESTS {
                retries += 1;
                if retries > 5 {
                    return Err(ApiError::RateLimited(retries - 1));
                }
                let wait = resp
                    .headers()
                    .get(RETRY_AFTER)
                    .and_then(|v| v.to_str().ok())
                    .and_then(|s| s.parse::<u64>().ok())
                    .map(Duration::from_secs)
                    .unwrap_or(Duration::from_millis(500 * 2u64.pow(retries)));
                sleep(wait).await;
                continue;
            }
            let body = resp.text().await?;
            if status == StatusCode::BAD_REQUEST {
                // a missing or invalid parameter: the reason is in "detail"
                let detail = serde_json::from_str::<serde_json::Value>(&body)
                    .ok()
                    .and_then(|v| v.get("detail").and_then(|d| d.as_str()).map(str::to_owned))
                    .unwrap_or(body);
                return Err(ApiError::BadRequest(detail));
            }
            if !status.is_success() {
                return Err(ApiError::Status { status: status.as_u16(), body });
            }
            let value: serde_json::Value = serde_json::from_str(&body)?;
            if value.get("status").and_then(|s| s.as_str()) == Some("error") {
                let msg = value.get("msg").and_then(|m| m.as_str()).unwrap_or("unknown");
                return Err(ApiError::Api(msg.to_owned()));   // e.g. "user not found"
            }
            return Ok(serde_json::from_value(value)?);
        }
    }

    pub async fn user_info(&self, user: &str) -> Result<UserInfo, ApiError> {
        let r: UserInfoResponse = self
            .get(&format!("{BASE}/twitter/user/info"), &[("userName", user)])
            .await?;
        r.data.ok_or_else(|| ApiError::Api(r.msg.unwrap_or_else(|| "no data".into())))
    }
}
06 — Section

Cursor paging as a futures Stream (and why short pages are not the end)

futures::stream::unfold fits cursor paging exactly: its closure takes the current state and returns a future of Option<(Item, State)>, where None ends the stream. Here the state is Option<String>, the cursor for the next request, and each item is one page of tweets or an error. Callers get a Stream they can take(n), filter, or merge with other streams.

Loop on has_next_page, not on page size. In our sample, 46 of 68 pages returned fewer than 20 tweets while has_next_page was still true; the median page held 18 tweets. A client that stops at the first short page would have read a fraction of each timeline. The one page with zero tweets was also the last one, so the code below stops on an empty page as a guard against paying the per-request minimum in a loop.

Deduplicate by id. 9 of 1,133 tweet ids appeared twice across consecutive pages (1,124 distinct). A HashSet<String> of seen ids, as in the main function in the next section, handles it. The search stream is the same pattern for /twitter/tweet/advanced_search, with queryType set to Latest or Top.

rust
use futures::stream::{self, Stream};

impl XClient {
    /// Pages of a user's timeline, newest first. Ends when has_next_page is false,
    /// the cursor is empty, a page comes back with zero tweets, or a call fails.
    pub fn last_tweets(&self, user: String) -> impl Stream<Item = Result<Vec<Tweet>, ApiError>> + '_ {
        stream::unfold(Some(String::new()), move |cursor| {
            let user = user.clone();
            async move {
                let cursor = cursor?;             // None = finished
                let mut query = vec![("userName", user.as_str())];
                if !cursor.is_empty() {
                    query.push(("cursor", cursor.as_str()));
                }
                let page: LastTweetsPage = match self
                    .get(&format!("{BASE}/twitter/user/last_tweets"), &query)
                    .await
                {
                    Ok(p) => p,
                    Err(e) => return Some((Err(e), None)),
                };
                let tweets = page.data.map(|d| d.tweets).unwrap_or_default();
                // Do NOT stop on tweets.len() < 20: short pages with has_next_page = true are normal.
                let next = match (page.has_next_page, page.next_cursor) {
                    (true, Some(c)) if !c.is_empty() && !tweets.is_empty() => Some(c),
                    _ => None,
                };
                Some((Ok(tweets), next))
            }
        })
    }

    /// Same shape for search, except `tweets` is top level.
    pub fn search(&self, q: String, query_type: &'static str) -> impl Stream<Item = Result<Vec<Tweet>, ApiError>> + '_ {
        stream::unfold(Some(String::new()), move |cursor| {
            let q = q.clone();
            async move {
                let cursor = cursor?;
                let mut query = vec![("query", q.as_str()), ("queryType", query_type)];
                if !cursor.is_empty() {
                    query.push(("cursor", cursor.as_str()));
                }
                let page: SearchPage = match self
                    .get(&format!("{BASE}/twitter/tweet/advanced_search"), &query)
                    .await
                {
                    Ok(p) => p,
                    Err(e) => return Some((Err(e), None)),
                };
                let next = match (page.has_next_page, page.next_cursor) {
                    (true, Some(c)) if !c.is_empty() && !page.tweets.is_empty() => Some(c),
                    _ => None,
                };
                Some((Ok(page.tweets), next))
            }
        })
    }
}
07 — Section

Many accounts at once: a Semaphore, the pacer and real posting rates

Two limits, two tools. tokio::sync::Semaphore caps how many timelines are in flight at once (here four, through acquire_owned, which gives each spawned task a permit it owns). The pacer inside XClient caps requests per second across all of them. You need both: the semaphore bounds memory and open connections, the pacer keeps you inside your QPS tier. An equivalent design uses futures::StreamExt::buffer_unordered(4) over a stream of account names instead of spawning tasks.

How often should you poll? It depends on the account. Posting rates in the same sample ranged from more than two posts a day to one every couple of weeks:

accountposts in sampleposts per daymedian gap (hours)
@cloudflare1002.643.6
@zeddotdev652.412.5
@warpdotdev891.393.3
@BevyEngine1000.980
@rustconf600.9220.4
@discord860.921.6
@deno_land780.2847.6
@TauriApps940.2724.4
@tursodatabase530.2750.5
@rust_foundation920.1525.1
@ThisWeekInRust1000.13169
@rustlang940.09171
@tokio_rs930.05146.4
@astral_sh290.03382.9

@BevyEngine's median gap of 0 hours reflects bursts of reposts in the same minute. @rustlang's newest post in our sample dates from 2025 and points followers to Mastodon and Bluesky, a reminder that the quiet accounts in a watchlist cost almost nothing to read but still cost a minimum per check. Polling a quiet account every minute burns empty checks; polling a busy one every hour returns full pages. Match the interval to the measured rate.

rust
use std::collections::HashSet;
use std::sync::Arc;

use futures::StreamExt;
use tokio::sync::Semaphore;
use tokio::task::JoinSet;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    let key = std::env::var("TWITTERAPI_IO_KEY")?;
    // 18 req/s leaves headroom under the paid tier's 20; use 0.2 before your first payment.
    let client = XClient::new(&key, 18.0)?;
    let accounts = ["rust_foundation", "tokio_rs", "zeddotdev", "TauriApps", "BevyEngine"];
    let gate = Arc::new(Semaphore::new(4));      // up to 4 timelines in flight

    let mut tasks = JoinSet::new();
    for acct in accounts {
        let client = client.clone();
        let gate = gate.clone();
        tasks.spawn(async move {
            let _permit = gate.acquire_owned().await.expect("semaphore closed");
            let info = client.user_info(acct).await?;        // fails fast on "user not found"
            let mut seen = HashSet::new();                    // ids can repeat across pages
            let mut pages = std::pin::pin!(client.last_tweets(acct.to_string()).take(5));
            while let Some(page) = pages.next().await {
                for t in page? {
                    if seen.insert(t.id.clone()) && t.retweeted_tweet.is_none() {
                        // original posts and quotes only; work with t here
                    }
                }
            }
            Ok::<_, ApiError>((info.user_name, info.followers, seen.len()))
        });
    }

    while let Some(joined) = tasks.join_next().await {
        match joined? {
            Ok((user, followers, n)) => println!("{user}: {followers} followers, {n} distinct tweets"),
            Err(e) => eprintln!("error: {e}"),
        }
    }
    Ok(())
}
08 — Section

What it costs, compared with the official X API

TwitterAPI.io bills per result: 15 credits per tweet returned on tweet endpoints, which is $0.15 per 1,000 tweets, and 18 credits per profile, $0.18 per 1,000 profiles. A full 20-tweet page costs $0.003. Each request has a minimum of 15 credits, so a check that finds nothing costs $0.00015; polling one account every 60 seconds for a month is 43,200 checks, or $6.48 if every one came back empty, and every 5 minutes is $1.30.

X's own pay-per-usage rate card lists $0.005 per post read and $0.010 per user read, with post reads capped at 3 million per monthly billing cycle (Enterprise above that). Per 1,000 tweets that is $5.00 against $0.15, about 33x.

workloadTwitterAPI.ioX API pay-per-usage
This study: 1,133 tweets$0.17$5.67
1,000 tweets$0.15$5.00
1,000 profiles$0.18$10.00

New accounts that pass the automatic bot check get up to $1 of free credits (up to 100,000 credits, no card, one per person or network, expiring after 31 days). Purchased credits never expire. Monthly plans run from Starter at $29 to Business at $1,499; see the pricing page for what each includes.

Writing from Rust. Posting is a separate product that runs through an authenticated session: one /twitter/user_login_v2 call ($0.10, with a proxy you supply) returns login_cookies, and each post, delete, like, repost, follow or media upload through endpoints such as /twitter/create_tweet_v2 or /twitter/follow_user_v2 then costs 60 credits ($0.0006). The same XClient can send those requests with .post(...).json(...). Every such call acts as that X account, so X can rate-limit, lock or suspend it; keep a human pace, expect the session to need a fresh login now and then, and note that each HTTP 200 call is billed. Reads need no X account at all.

09 — Section

How we collected this

Question. How strict can a Rust serde struct for tweets be before real responses stop deserializing, which fields are absent, null, empty or a different type, how many tweets and pages a strict versus lenient schema loses, and how often Rust-ecosystem accounts post?

Accounts. 14 public organization accounts, each verified first with /twitter/user/info: @rustlang, @tokio_rs, @rust_foundation, @BevyEngine, @zeddotdev, @astral_sh, @deno_land, @TauriApps, @cloudflare, @discord, @ThisWeekInRust, @rustconf, @tursodatabase and @warpdotdev. Handles that did not resolve or belonged to unrelated accounts were dropped and are listed in the study protocol.

Method and window. /twitter/user/last_tweets with default settings, newest first, up to five pages per account, following next_cursor while has_next_page was true: 1,133 tweets (1,124 distinct) on 68 pages. Each account's window runs from its oldest to its newest post in the sample. Collected in 2026 with 88 requests (20 profile checks and 68 timeline pages), about $0.17 in credits.

The schema test. The four schemas were written as field lists (name, expected JSON type, required or optional) and applied to every tweet, including nested quoted and reposted tweets, with serde's rules re-implemented in Python: a missing non-optional field, a null into a non-Option field, or a wrong JSON type fails the tweet, and one failing tweet fails its page. No Rust toolchain was available, so this is a simulation, not a cargo run, and the Rust code on this page was not compiled here.

What the sample cannot show. Organization timelines exclude replies by default, which is why inReplyToId was always null at the top level; a reply-heavy feed or a search for replies will populate it. Fields such as article, place and card can carry content on other accounts. Treat the percentages as a picture of these 14 accounts, not of X as a whole, and record fixtures from the accounts you actually read.

Privacy. Aggregates only. Only organization accounts are named; reposted, quoted and mentioned authors were not analyzed. Raw pages are kept only for timelines with five or fewer distinct authors.

python
"""record_fixtures.py - save raw TwitterAPI.io timeline pages as JSON fixtures, so your Rust
structs can be tested with `cargo test` against real responses before they meet production.

    pip install requests
    export TWITTERAPI_IO_KEY=...        # from the twitterapi.io dashboard
    python record_fixtures.py rust_foundation tokio_rs zeddotdev
"""
import json
import os
import pathlib
import sys
import time

import requests

BASE = "https://api.twitterapi.io"
HEADERS = {"X-API-Key": os.environ["TWITTERAPI_IO_KEY"]}
OUT = pathlib.Path("tests/fixtures")


def get(url, params):
    for attempt in range(5):
        r = requests.get(url, headers=HEADERS, params=params, timeout=30)
        if r.status_code == 429:
            time.sleep(2 ** attempt)
            continue
        if r.status_code == 400:
            raise SystemExit(f"bad request: {r.json().get('detail')}")
        r.raise_for_status()
        body = r.json()
        if body.get("status") == "error":
            raise SystemExit(body.get("msg"))      # e.g. "user not found" arrives as HTTP 200
        return body
    raise SystemExit("still rate limited after 5 tries")


def record(user_name, max_pages=3):
    info = get(f"{BASE}/twitter/user/info", {"userName": user_name})["data"]
    print(f"@{info['userName']}: {info['followers']} followers")
    cursor, saved = None, 0
    for n in range(max_pages):
        params = {"userName": user_name}
        if cursor:
            params["cursor"] = cursor
        page = get(f"{BASE}/twitter/user/last_tweets", params)
        tweets = (page.get("data") or {}).get("tweets") or []
        (OUT / f"{user_name}-{n}.json").write_text(json.dumps(page))
        saved += len(tweets)
        # short pages are normal: follow has_next_page, not len(tweets) == 20
        cursor = page.get("next_cursor")
        if not page.get("has_next_page") or not cursor or not tweets:
            break
    print(f"  saved {saved} tweets; cost about ${saved * 15 / 100000:.4f}")


if __name__ == "__main__":
    OUT.mkdir(parents=True, exist_ok=True)
    for user in sys.argv[1:] or ["rust_foundation"]:
        record(user)

Researching this?Free starter credits cover end-to-end testing — Google sign-in, no card. Get a key.

10 — Questions

Questions readers ask

Is there an official Rust SDK for the Twitter (X) API?

No. X does not publish one. The community crates target X's own OAuth API: egg-mode (0.16.1, 2023) now marks itself abandoned in its README, and twitter-v2 (0.1.8, 2022) covers API v2 with bearer or OAuth 2.0 tokens. For TwitterAPI.io no SDK is needed; reqwest and serde are the whole client.

Which reqwest features do I need for a Twitter API client?

With reqwest 0.13, enable json and query. Both methods are feature-gated on docs.rs, and neither is in the default set (default-tls, charset, http2, system-proxy). The default TLS backend is rustls.

Should tweet ids be u64 or String in Rust?

String. In our sample every id, conversationId and author.id arrived as a JSON string (1,133 of 1,133), and serde will not decode a JSON string into u64 without a custom deserializer. Strings also round-trip safely into URLs and query parameters.

Why does serde fail with "missing field" on some tweets?

Usually because an array such as extendedEntities.media or entities.hashtags is absent rather than empty. Option<T> covers null, but a missing key on a plain Vec<T> is an error. Add #[serde(default)]. In our sample that single change took failures from 93.9% of tweets to 2.3%.

Why does one bad tweet break a whole page?

Because the page decodes into Vec<Tweet> and serde stops at the first failing element. Either make the struct tolerant of everything the API can send (an all-default struct for nested quoted and reposted tweets did that here), or decode the array as Vec<serde_json::Value> and convert each element separately so you can log and skip the odd one.

How do I paginate tweets in Rust?

Pass cursor from the previous response's next_cursor, and continue while has_next_page is true. futures::stream::unfold turns that into a Stream of pages. Do not stop on a short page: many pages hold fewer than 20 tweets and still have more after them.

How many requests per second can a Rust client send?

0.2 requests per second before your first payment, 20 once paid, 50 on Scale, 500 on Business and up to 1,000 on request. Share one pacer across all tasks, as in the XClient above, and add a Semaphore to cap how many timelines run at once.

Can I post tweets from Rust with this API?

Yes, through an authenticated session: log in once with /twitter/user_login_v2 ($0.10, with your own proxy), then call write endpoints such as /twitter/create_tweet_v2 at 60 credits ($0.0006) each. Each call acts as that account, so X can rate-limit, lock or suspend it; keep a human pace and expect occasional re-logins.

11 — Further reading

Continue

Sources & further reading
More from this series

Writing about something you built with TwitterAPI.io? Our community rewards program pays API credits for honest tutorials, build logs and videos.

Build it

Stop reading. Start building.

Starter credits cover real testing on real data. Google sign-in, no card, no application queue.

Get an API key

Already building with TwitterAPI.io? Publish an honest tutorial or build log about it and earn up to $200 a month in API credits.