Twitter (X) API in Kotlin: Ktor, kotlinx.serialization and coroutines

By TwitterAPI.io Team•12 min read
Diagram: Android app calls a Kotlin backend that holds the X-API-Key and calls api.twitterapi.io user info, timeline and search endpoints
Keep the key on your Kotlin backend: Ktor client, kotlinx.serialization with ignoreUnknownKeys, one coroutine per account.
TL;DR
  • No official Kotlin SDK is needed: Ktor HttpClient + kotlinx.serialization + coroutines cover a typed read client in about 150 lines.
  • ignoreUnknownKeys = true is mandatory: a default Json {} decoded 0 of our 1,146 real tweets (31 tweet keys, 33 author keys seen).
  • Make optional links nullable with = null: inReplyToId was null on 94.3% of tweets, quoted_tweet on 91.7%, retweeted_tweet on 85.5%.
  • Coroutines parallelize accounts, not cursors: six timelines projected at 35 s concurrently vs 184 s one after another (5.2x).
  • Cost: $0.15 per 1,000 tweets returned (15 credits each, minimum 15 per request) vs $5.00 per 1,000 post reads on X's pay-per-usage rate card.
  • Android: never ship the X-API-Key in an APK; call your own Ktor or Spring backend, which calls api.twitterapi.io.

This guide is the Kotlin-specific companion to our Java guide. The Java page settles the type questions (why tweet ids must be strings, which counters need a long, how to parse createdAt); here we cover what is different in Kotlin: kotlinx.serialization instead of Jackson, null safety in data classes, suspend functions, Flow for cursor pagination, coroutines for parallel reads, and the Android rule of keeping the key on a server.

Searching for a Kotlin Twitter API library turns up community projects built for X's own OAuth API (twitter4kt, KTweet, Twitter4Kt, an alpha-stage Tweedle) and tutorials that start with a developer-portal app and consumer keys. X's official tools list a Java SDK and a TypeScript SDK, not a Kotlin one. None of those sources shows what happens when a Kotlin data class meets thousands of real tweets, so we measured it: we decoded 1,146 tweets against the data classes on this page under four Json configurations, and timed every cursor page.

Everything below uses read endpoints of TwitterAPI.io, which need only an API key and no X developer account. Each code block compiles against Ktor 3.6.2 and kotlinx.serialization 1.13.0 APIs as documented; we state exactly what we ran in the study section.

Real tweets a default kotlinx.serialization Json decoded, out of 1,146

0 of 1,146

01 — Section

Kotlin options for the Twitter (X) API in 2026

There are three routes from Kotlin to X data, and they differ in who authenticates and what you pay.

X's own API from a community library. Projects such as twitter4kt (Kotlin Multiplatform, JVM only today, per its listing), KTweet (API v2 with OAuth 2.0) and Twitter4Kt (API v1 with consumer and access tokens) wrap the official endpoints. You need an X developer account, app keys and the pay-per-usage rate card: $0.005 per post read and $0.010 per user read on docs.x.com/x-api/getting-started/pricing, capped at 3 million post reads a month before Enterprise.

X's Java XDK from Kotlin. X publishes an official Java SDK (com.x:xdk), and Kotlin can call any Java library. Our Java guide covers it; from Kotlin you would wrap its callbacks or blocking calls in coroutines yourself.

A plain HTTP client against TwitterAPI.io. No OAuth, one header, JSON over HTTPS. This is the route this guide takes, because Kotlin already ships the three pieces a read client needs: a coroutine-native HTTP client (Ktor), compile-time JSON serialization (kotlinx.serialization) and structured concurrency (kotlinx.coroutines).

RouteAuthRead priceKotlin fit
Community OAuth libraryX developer app + tokens$0.005 per post read (X rate card)Varies; several projects are alpha or v1-only
X Java XDK called from KotlinX developer app + tokens$0.005 per post read (X rate card)Java API, wrap in coroutines yourself
Ktor + TwitterAPI.ioOne X-API-Key header$0.15 per 1,000 tweets returnedSuspend functions, data classes, Flow

Library versions move fast, so we checked them this session: Ktor 3.6.2 is the latest release on the ktorio/ktor GitHub releases page (published 25 November 2026), and kotlinx.serialization's latest tag is v1.13.0.

02 — Section

Gradle setup and data classes that match the real JSON

The client needs four Ktor artifacts, the JSON library and coroutines. The serialization compiler plugin must carry the same version as your Kotlin plugin, so we leave both as placeholders rather than guess your toolchain.

The data classes below are the ones our study checked against real pages. Three choices matter. Ids are String, never Double (the Java guide shows how often a double corrupts a tweet id). Counters are Long: the largest viewCount in our sample was 489,846,169, still under Int.MAX_VALUE, but view counts on large accounts keep climbing and a Long costs nothing. Optional links (inReplyToId, quoted_tweet, retweeted_tweet) are nullable and default to null.

The two list endpoints use different envelopes, which is the second classic decode bug. /twitter/user/last_tweets wraps tweets in data.tweets and adds status, code and msg; /twitter/tweet/advanced_search puts tweets at the top level and has no status field. Both put has_next_page and next_cursor at the top level. Model them as two classes instead of one class with everything optional.

kotlin
// build.gradle.kts (JVM backend or Android module)
plugins {
    kotlin("jvm") version "<your Kotlin version>"
    // The serialization plugin uses the same version as your Kotlin plugin
    kotlin("plugin.serialization") version "<your Kotlin version>"
}

dependencies {
    val ktor = "3.6.2"
    implementation("io.ktor:ktor-client-core:$ktor")
    implementation("io.ktor:ktor-client-cio:$ktor")
    implementation("io.ktor:ktor-client-content-negotiation:$ktor")
    implementation("io.ktor:ktor-serialization-kotlinx-json:$ktor")
    implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.13.0")
    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:<current version>")
}

import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json

// One Json instance for the whole app. ignoreUnknownKeys is not optional:
// a tweet carries 31 keys and an author 33, and new ones can appear any day.
val TwJson = Json {
    ignoreUnknownKeys = true
    explicitNulls = false      // a missing nullable key decodes as null
}

@Serializable
data class Author(
    val id: String,
    val userName: String,
    val name: String,
    val followers: Long,
    val following: Long,
    val isBlueVerified: Boolean = false,
    val createdAt: String,
)

@Serializable
data class Tweet(
    val id: String,                // keep ids as String, never Double
    val url: String,
    val text: String,
    val createdAt: String,         // "Thu Oct 16 12:34:56 +0000 2026"
    val lang: String = "",
    val likeCount: Long = 0,
    val retweetCount: Long = 0,
    val replyCount: Long = 0,
    val quoteCount: Long = 0,
    val viewCount: Long = 0,       // Long: view counts run into the hundreds of millions
    val bookmarkCount: Long = 0,
    val conversationId: String,
    val isReply: Boolean = false,
    val inReplyToId: String? = null,     // null on 94.3% of our sample
    val author: Author,
    @SerialName("quoted_tweet") val quotedTweet: Tweet? = null,       // null on 91.7%
    @SerialName("retweeted_tweet") val retweetedTweet: Tweet? = null, // null on 85.5%
)

// /twitter/user/last_tweets: tweets sit under data, the cursor at the top level
@Serializable
data class TimelineData(val tweets: List<Tweet> = emptyList())

@Serializable
data class TimelinePage(
    val status: String = "success",
    val msg: String? = null,
    val data: TimelineData? = null,
    @SerialName("has_next_page") val hasNextPage: Boolean = false,
    @SerialName("next_cursor") val nextCursor: String = "",
)

// /twitter/tweet/advanced_search: tweets at the top level, no status field
@Serializable
data class SearchPage(
    val tweets: List<Tweet> = emptyList(),
    @SerialName("has_next_page") val hasNextPage: Boolean = false,
    @SerialName("next_cursor") val nextCursor: String = "",
)

@Serializable
data class UserInfo(
    val id: String,
    val userName: String,
    val name: String,
    val followers: Long,
    val following: Long,
    val statusesCount: Long = 0,
    val createdAt: String = "",
    val isBlueVerified: Boolean = false,
)

@Serializable
data class UserInfoResponse(val status: String, val msg: String? = null, val data: UserInfo? = null)
03 — Section

What breaks: 1,146 real tweets under four Json configurations

We collected 1,146 tweets (986 from six organization timelines and 160 from a kotlin -is:retweet search) and checked each one against the Tweet class above under four kotlinx.serialization setups. The check applies the library's documented rules: unknown keys raise an error unless ignoreUnknownKeys is on, a JSON null in a non-null property throws "even when the property has a default value", and a missing property without a default cannot be decoded.

Json setupTweets decodedFirst failure
Json {} (default)0 of 1,146Unknown key on every tweet
ignoreUnknownKeys, every field non-null0 of 1,146null into a non-null property
ignoreUnknownKeys, optional links nullable1,146 of 1,146none
ignoreUnknownKeys + explicitNulls = false, nullable = null1,146 of 1,146none

Why the default fails on every tweet. The tweets in our sample carried 31 distinct keys (displayTextRange, entities, card, place, article, isQuote, isRetweet and more), and author objects 33. A class that declares the 18 fields you use leaves 13 tweet keys and 26 author keys undeclared, and the default Json treats each as an error.

Why "every field non-null" also fails on every tweet. A tweet is rarely a reply, a quote and a retweet at once, so at least one of the three links is null on every single tweet in the sample. The keys were always present (missing on 0% of tweets); they come back as JSON null, not absent, so explicitNulls = false is a safety net for future payloads rather than a requirement today.

Empty objects are not null. extendedEntities was present on every tweet but an empty object on 52.9% of them, and place was an empty object on 100.0%. If you model them, give every inner field a default, or a strict class will throw on {}.

Bar chart: tweets decoded out of 1,146 under four kotlinx.serialization setups; default Json and all-non-null decode 0, the nullable setups decode all 1,146
Default Json and all-non-null classes decode none of 1,146 real tweets; ignoreUnknownKeys plus nullable optional links decode all of them. Collected in 2026.
04 — Section

A Ktor client with typed errors and fixed back-off

Create one HttpClient for the life of the process; Ktor's documentation notes that creating a client is costly and recommends reusing one instance across requests. Install ContentNegotiation with the shared TwJson, set the X-API-Key header once with defaultRequest, and keep paths as full literal URLs so each call is greppable.

Error handling has three layers. Transport errors and HTTP 429 or 5xx get a short, fixed back-off (one, then two seconds) before giving up. HTTP 400 means a missing or invalid parameter, and the reason is in the body's detail field. Logical errors arrive as HTTP 200 with status: "error" and a msg: an unknown user, for example, is a 200 with msg: "user not found" and data: null, never a 404, so the client checks status before trusting data.

Writes exist too, as a separate product: one /twitter/user_login_v2 login ($0.10, with a proxy you supply) returns login_cookies, and each post, like, follow or DM through /twitter/create_tweet_v2, /twitter/follow_user_v2 and similar endpoints is 60 credits ($0.0006) per successful call; calls that return status: error are not charged. The call acts as that account, so X can rate-limit, lock or suspend it; keep a normal human pace on your own account, and expect the session to need a re-login now and then. This guide stays on reads, which need no X account.

kotlin
import io.ktor.client.HttpClient
import io.ktor.client.call.body
import io.ktor.client.engine.cio.CIO
import io.ktor.client.plugins.contentnegotiation.ContentNegotiation
import io.ktor.client.plugins.defaultRequest
import io.ktor.client.request.get
import io.ktor.client.request.header
import io.ktor.client.request.parameter
import io.ktor.client.statement.HttpResponse
import io.ktor.client.statement.bodyAsText
import io.ktor.http.HttpStatusCode
import io.ktor.serialization.kotlinx.json.json
import kotlinx.coroutines.delay

class TwitterApiException(val httpStatus: Int, message: String) : Exception(message)

class TwitterApi(apiKey: String) : AutoCloseable {
    // Ktor's docs: creating a client is costly, reuse one instance for many requests
    private val http = HttpClient(CIO) {
        install(ContentNegotiation) { json(TwJson) }
        defaultRequest { header("X-API-Key", apiKey) }
        expectSuccess = false   // we read the status ourselves
    }

    // Fixed back-off on 429 and 5xx; no randomness, three tries
    private suspend fun send(block: suspend () -> HttpResponse): HttpResponse {
        var wait = 1_000L
        repeat(3) { attempt ->
            val r = block()
            val retry = r.status == HttpStatusCode.TooManyRequests || r.status.value >= 500
            if (!retry || attempt == 2) {
                if (r.status.value >= 400) {
                    // HTTP 400 for a missing or invalid parameter carries the text in "detail"
                    throw TwitterApiException(r.status.value, r.bodyAsText().take(300))
                }
                return r
            }
            delay(wait)
            wait *= 2
        }
        error("unreachable")
    }

    suspend fun userInfo(userName: String): UserInfo {
        val res: UserInfoResponse = send {
            http.get("https://api.twitterapi.io/twitter/user/info") { parameter("userName", userName) }
        }.body()
        // An unknown user is HTTP 200 with status "error" and data null, never a 404
        if (res.status != "success" || res.data == null) {
            throw TwitterApiException(200, res.msg ?: "user not found")
        }
        return res.data
    }

    suspend fun timelinePage(userName: String, cursor: String = ""): TimelinePage {
        val page: TimelinePage = send {
            http.get("https://api.twitterapi.io/twitter/user/last_tweets") {
                parameter("userName", userName)
                parameter("cursor", cursor)
            }
        }.body()
        if (page.status != "success") throw TwitterApiException(200, page.msg ?: "error")
        return page
    }

    suspend fun searchPage(query: String, cursor: String = ""): SearchPage = send {
        http.get("https://api.twitterapi.io/twitter/tweet/advanced_search") {
            parameter("query", query)
            parameter("queryType", "Latest")
            parameter("cursor", cursor)
        }
    }.body()

    override fun close() = http.close()
}
05 — Section

Both list endpoints return up to 20 tweets per page plus has_next_page and next_cursor. The first request sends an empty cursor; each next request sends the cursor from the previous page. A cold Flow<Tweet> is a natural fit: nothing is fetched until a collector asks, and take(200) stops the requests as soon as it has enough, so you never pay for a page you do not read.

Stop on three conditions, not one: has_next_page false, an empty next_cursor, or an empty page. In our run 2 of the 60 list pages came back empty (one at the end of the @kotlin chain, one at the end of @intellijidea), and an empty request still costs the 15-credit minimum ($0.00015), so a loop that trusts only has_next_page can burn requests at the tail.

EndpointWhere tweets areStatus fieldMedian s per page
/twitter/user/last_tweetsdata.tweetsstatus, msg3.48
/twitter/tweet/advanced_searchtweets (top level)none2.59
/twitter/user/infodata (one profile)status, msg1.39

Page times include the 5 requests per second pacing our study client shares across parallel jobs, so treat them as an upper-bound budget, not raw latency. For deeper cursor mechanics (cursor lifetime, resuming a crawl, deduplicating by id) see our pagination guide.

kotlin
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.take
import kotlinx.coroutines.flow.toList

// Each page needs the previous next_cursor, so one chain is always sequential.
fun TwitterApi.timeline(userName: String, maxPages: Int = 10): Flow<Tweet> = flow {
    var cursor = ""
    repeat(maxPages) {
        val page = timelinePage(userName, cursor)
        val tweets = page.data?.tweets.orEmpty()
        tweets.forEach { emit(it) }
        // Stop on an empty page too: 2 of our 60 pages came back empty
        if (!page.hasNextPage || page.nextCursor.isEmpty() || tweets.isEmpty()) return@flow
        cursor = page.nextCursor
    }
}

fun TwitterApi.search(query: String, maxPages: Int = 10): Flow<Tweet> = flow {
    var cursor = ""
    repeat(maxPages) {
        val page = searchPage(query, cursor)
        page.tweets.forEach { emit(it) }
        if (!page.hasNextPage || page.nextCursor.isEmpty() || page.tweets.isEmpty()) return@flow
        cursor = page.nextCursor
    }
}

// Usage: the first 200 posts that mention Kotlin, newest first
suspend fun latestKotlinPosts(api: TwitterApi): List<Tweet> =
    api.search("kotlin -is:retweet", maxPages = 10).take(200).toList()
06 — Section

Coroutines: parallel accounts, sequential cursors

Kotlin makes concurrency cheap to write: coroutineScope waits for every child, and async starts a concurrent computation that returns a Deferred. The catch for any cursor API is that page two needs page one's next_cursor, so pages inside one chain cannot run in parallel. What can run in parallel is separate chains: one coroutine per account, per search query or per tweet id batch.

We timed six real timeline chains (52 requests). Read one after another they took 184 s in total; with one coroutine per account the wall time is bounded by the longest chain, 35 s for @AndroidDev, a 5.2x speed-up. That figure is a projection from the measured chains, not a concurrent run: it assumes your plan's rate limit has room for six requests in flight.

AccountPagesTweetsSeconds per page
@kotlin91603.2
@AndroidDev91803.91
@jetbrains91803.56
@intellijidea71064.28
@gradle91803.39
@Android91803.09

Size the Semaphore from your rate limit. Before the first payment an account gets 0.2 requests per second, so parallel coroutines just queue; once paid it is 20 requests per second (50 on Scale, 500 on Business), which comfortably covers a handful of chains running at about one page every few seconds each. The rate limit calculator turns a page budget into the QPS you need.

kotlin
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.flow.toList
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.sync.Semaphore
import kotlinx.coroutines.sync.withPermit

// One coroutine per account; the Semaphore caps requests in flight so the
// fan-out stays inside your plan's rate limit (0.2 req/s before the first
// payment, 20 req/s once paid).
suspend fun TwitterApi.timelines(
    accounts: List<String>,
    maxPages: Int = 9,
    inFlight: Int = 6,
): Map<String, List<Tweet>> = coroutineScope {
    val gate = Semaphore(inFlight)
    accounts.map { name ->
        async { name to gate.withPermit { timeline(name, maxPages).toList() } }
    }.awaitAll().toMap()
}

fun main() = runBlocking {
    val key = System.getenv("TWITTERAPI_IO_KEY") ?: error("set TWITTERAPI_IO_KEY")
    TwitterApi(key).use { api ->
        val who = api.userInfo("kotlin")
        println("@${who.userName}: ${who.followers} followers")

        val byAccount = api.timelines(listOf("kotlin", "AndroidDev", "jetbrains", "gradle"))
        byAccount.forEach { (name, tweets) ->
            val top = tweets.maxByOrNull { it.likeCount }
            println("@$name ${tweets.size} posts, top post ${top?.likeCount ?: 0} likes ${top?.url ?: ""}")
        }
    }
}
Horizontal bars: six timelines read sequentially take 184 seconds, one coroutine per account takes 35 seconds
Six measured cursor chains: 184 s one after another vs 35 s with one coroutine per account (5.2x). Collected in 2026.
07 — Section

Android: keep the API key on a backend

Kotlin is the default language for Android, which makes the key question unavoidable. Android's own security guidance on hardcoded secrets warns that "an attacker with access to reverse engineering tools can retrieve a hard-coded secret very easily". A key in BuildConfig, local.properties or strings.xml ends up in the APK, and anyone who extracts it spends your credits.

The fix is architectural: the app authenticates to your server with its own session or token, and the server holds the X-API-Key and calls api.twitterapi.io. Because the client above is plain Kotlin, the same TwitterApi class runs inside a Ktor server, a Spring Boot service or a serverless function. The server can also cache responses, validate handles before spending a request, and return only the fields the app renders.

On the app side, the models stay useful: share the @Serializable classes in a Kotlin Multiplatform or plain JVM module so the Android client decodes your backend's trimmed response with the same TwJson configuration.

kotlin
// A tiny Ktor server endpoint: the Android app calls this, never api.twitterapi.io.
// Your own auth (session, Firebase token, ...) protects the route.
import io.ktor.server.application.Application
import io.ktor.server.response.respond
import io.ktor.server.routing.get
import io.ktor.server.routing.routing
import kotlinx.coroutines.flow.take
import kotlinx.coroutines.flow.toList

fun Application.twitterRoutes(api: TwitterApi) {
    routing {
        get("/feed/{user}") {
            val user = call.parameters["user"].orEmpty()
            if (!Regex("^[A-Za-z0-9_]{1,15}$").matches(user)) {
                return@get call.respond(io.ktor.http.HttpStatusCode.BadRequest, "bad handle")
            }
            val tweets = api.timeline(user, maxPages = 1).take(20).toList()
            // Return only what the app shows, not the whole upstream payload
            call.respond(tweets.map { mapOf("text" to it.text, "likes" to it.likeCount.toString(), "url" to it.url) })
        }
    }
}
08 — Section

What it costs, compared with the official X API

TwitterAPI.io bills per item returned: 15 credits per tweet ($0.15 per 1,000 tweets) with a minimum of 15 credits per request, and 18 credits per profile ($0.18 per 1,000). $1 buys 100,000 credits. The official X API's pay-per-usage rate card on docs.x.com/x-api/getting-started/pricing lists $0.005 per post read and $0.010 per user read, so 1,000 tweets cost $5.00 there, about 33x more.

WorkloadTwitterAPI.ioOfficial X API (pay-per-usage)
1,000 tweets from timelines or search$0.15$5.00
1,000 user profiles$0.18$10.00
This study: 1,146 tweets + 6 profiles$0.17$5.79
Polling one account every 60 s for a month, nothing new$6.48 (43,200 empty checks)billed per post read

A full 20-tweet page costs $0.003 and an empty check $0.00015, so polling cost is driven by frequency: every 5 minutes is about $1.30 a month per query, every 5 seconds about $77.76. X's rate card also caps pay-per-usage at 3 million post reads per monthly billing cycle, with Enterprise above that.

New accounts that pass the automatic bot check get free starter credits (no card, one per person or network, expiring after 31 days); the pricing page has the current amount. Purchased credits never expire.

09 — Section

How we collected this

Question. What breaks a Kotlin client built on kotlinx.serialization when it decodes real pages, which fields must be nullable, and how much do coroutines help across accounts?

Accounts and query. Timelines of six organization accounts (@kotlin, @AndroidDev, @jetbrains, @intellijidea, @gradle, @Android) via /twitter/user/last_tweets, up to 9 pages each, plus 8 pages of /twitter/tweet/advanced_search for kotlin -is:retweet (Latest) and one /twitter/user/info call per account.

Sample and cost. 66 requests returned 1,146 tweets (986 timeline, 160 search) and 6 profiles, collected in 2026, for about $0.17 at list prices. Each request was timed with a wall clock through our rate-limited study client.

What we ran, precisely. No Kotlin compiler, Gradle or JVM was available on the collection machine, so no Kotlin code was compiled or executed for this study. The decode results come from a Python checker that applies the documented kotlinx.serialization rules (unknown key, null into non-null, missing field without default) to the data classes printed on this page. The coroutine speed-up is a projection from measured sequential chains, not a concurrent run.

What the sample cannot show. Six developer-brand accounts and one keyword search are not all of X: accounts that post long articles, polls or heavy media may carry keys we did not see, which is exactly why ignoreUnknownKeys stays on. Page times include shared pacing on our side and vary with load.

Privacy. Only aggregates are published. Search results and nested quoted or retweeted posts include private individuals, so raw pages stayed off the repository; the committed sample holds de-identified rows without ids, URLs, text or handles.

python
# Contract check for your Kotlin data classes: fetch real pages, then report which
# keys your model does not declare (needs ignoreUnknownKeys) and which declared
# fields come back null (must be nullable in Kotlin). Save the pages as test fixtures.
# pip install requests ; export TWITTERAPI_IO_KEY=...
import json
import os
import pathlib
import requests

BASE = "https://api.twitterapi.io"
HEADERS = {"X-API-Key": os.environ["TWITTERAPI_IO_KEY"]}
DECLARED = {"id", "url", "text", "createdAt", "lang", "likeCount", "retweetCount",
            "replyCount", "quoteCount", "viewCount", "bookmarkCount", "conversationId",
            "isReply", "inReplyToId", "author", "quoted_tweet", "retweeted_tweet"}
OUT = pathlib.Path("src/test/resources/fixtures")
OUT.mkdir(parents=True, exist_ok=True)


def timeline(user, max_pages=3):
    tweets, cursor = [], ""
    for n in range(max_pages):
        r = requests.get(f"{BASE}/twitter/user/last_tweets",
                         params={"userName": user, "cursor": cursor},
                         headers=HEADERS, timeout=30)
        r.raise_for_status()
        body = r.json()
        if body.get("status") != "success":
            raise SystemExit(body.get("msg"))
        (OUT / f"last_tweets_{user}_{n}.json").write_text(json.dumps(body))
        page = (body.get("data") or {}).get("tweets") or []
        tweets += page
        if not body.get("has_next_page") or not body.get("next_cursor") or not page:
            break
        cursor = body["next_cursor"]
    return tweets


def search(query, max_pages=2):
    tweets, cursor = [], ""
    for n in range(max_pages):
        r = requests.get(f"{BASE}/twitter/tweet/advanced_search",
                         params={"query": query, "queryType": "Latest", "cursor": cursor},
                         headers=HEADERS, timeout=30)
        r.raise_for_status()
        body = r.json()
        (OUT / f"search_{n}.json").write_text(json.dumps(body))
        page = body.get("tweets") or []
        tweets += page
        if not body.get("has_next_page") or not body.get("next_cursor") or not page:
            break
        cursor = body["next_cursor"]
    return tweets


tweets = timeline("kotlin") + search("kotlin -is:retweet")
seen = set().union(*(t.keys() for t in tweets)) if tweets else set()
print(f"{len(tweets)} tweets, {len(seen)} keys, {len(seen - DECLARED)} not in the data class:")
print("  ", sorted(seen - DECLARED))
for key in sorted(DECLARED):
    nulls = sum(1 for t in tweets if t.get(key) is None)
    if nulls:
        print(f"  {key}: null on {nulls}/{len(tweets)} -> declare it nullable with = null")

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 Kotlin SDK for the Twitter (X) API?

No. X's official tools list a Java SDK and a TypeScript SDK; Kotlin can call the Java one. Community Kotlin libraries such as twitter4kt, KTweet and Twitter4Kt wrap X's OAuth API. For reads through TwitterAPI.io you only need Ktor and kotlinx.serialization, as shown here.

Why does kotlinx.serialization throw on Twitter API responses?

Two reasons. By default unknown keys are an error, and a tweet carries 31 keys; set ignoreUnknownKeys = true. And a JSON null in a non-null property throws even with a default value; declare inReplyToId, quoted_tweet and retweeted_tweet as nullable. In our 1,146-tweet sample those two changes took decoding from 0 to every tweet.

Should I use Ktor or OkHttp/Retrofit for the X API in Kotlin?

Either works, since the API is plain HTTPS with one header. Ktor is coroutine-native and multiplatform, which keeps the client usable from a JVM backend and shared Kotlin modules. With any other client, read the body as a string and call TwJson.decodeFromString<TimelinePage>(body): the data classes and the Json setup are what matter.

Can I fetch pages of one timeline in parallel with coroutines?

No. Each request needs the next_cursor of the previous page, so a single chain is sequential. Parallelize across accounts, queries or id batches instead: our six measured chains projected 184 s sequential vs 35 s with one coroutine each.

Can I put the API key in my Android app?

No. Anything in the APK can be extracted with reverse-engineering tools, and Android's security guidance says so about hardcoded secrets. Keep the key on your server and have the app call your own authenticated endpoint.

Do I need an X developer account to read tweets from Kotlin?

Not with TwitterAPI.io: reads need only its API key in the X-API-Key header. Writes (post, like, follow) are a separate product that acts through a logged-in session of your own X account.

How much does it cost to read 1,000 tweets from Kotlin?

$0.15 per 1,000 tweets returned on TwitterAPI.io (15 credits each, minimum 15 credits per request), vs $5.00 for 1,000 post reads on the official X API pay-per-usage rate card. The language makes no difference to the price.

Should tweet counters be Int or Long in Kotlin?

Use Long. The largest view count in our sample was 489,846,169, still under Int.MAX_VALUE, but popular posts grow and an overflow fails silently or throws mid-crawl. Keep ids as String; the Java guide shows why a floating-point id corrupts values.

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.