Twitter (X) API in Swift: URLSession, async/await and Codable models

By TwitterAPI.io Team•16 min read
Diagram: iOS app calls your backend, which holds the X-API-Key and calls api.twitterapi.io endpoints
Keep the key on your server: the app decodes Codable models, the backend talks to the API.
TL;DR
  • Two primitives: URLSession.data(for:) (async throws, iOS 15+ / macOS 12+) and JSONDecoder with Codable structs. No third-party Swift Twitter package is required.
  • Real data: 1,040 tweets from 6 organization accounts in 53 pages; our Swift 6 models decoded all 63 saved response files with 0 failures.
  • Decode is not your bottleneck: median 0.53 ms to decode a 20-tweet page offline, against a median 3.45 s wall time to fetch one through our paced client.
  • Optional where the data says so: card had a value in 27.6% of tweets, extendedEntities was an empty object in 48.3%, and place was {} in every tweet.
  • Errors arrive as HTTP 200: check status and read msg before trusting data; retry only on 429 and 5xx.
  • iOS rule: the API key lives on your server, never in the app bundle. Pricing: $0.15 per 1,000 tweets returned versus $0.005 per post read on the official X API pay-per-usage card.

Searching for a Swift Twitter library in 2026 mostly turns up packages that stopped moving years ago. That is less of a problem than it sounds: modern Swift already ships everything a read client needs. URLSession has an async/await API, Codable maps JSON to typed structs, and Swift 6 checks your concurrency for data races at compile time. What is missing from the search results is the boring, practical part: what the JSON really looks like at volume, which fields are null or empty often enough to crash a strict model, and how to keep the key out of an iOS app.

This guide builds a small Swift client for the TwitterAPI.io REST API (no X account needed for reads) and tests it against real responses. We pulled 1,040 tweets from six organization accounts with our rate-limited Python collector, saved every page, and decoded the saved pages with the exact Swift models shown below, compiled with Swift 6.1 in Swift 6 language mode. To be clear about what ran where: network timings come from the Python collector; the Swift code was compiled, type-checked for macOS 12 and run offline against the saved files, never against the network with a key.

Real tweets decoded by our Swift 6 Codable models, with zero failures

1,040

01 — Section

Swift Twitter libraries in 2026, and why URLSession is enough

Two names dominate older tutorials. TwitterAPIKit (a Swift library for the Twitter API v1 and v2) is archived on GitHub; its last push was in November 2022. Swifter, long the default answer on forums, now labels itself [DEPRECATED] in its GitHub description, with a last push in June 2022. Both were built around X's own OAuth flows and v1.1 / v2 endpoints, so even where they still compile, they assume an X developer account and X's pricing.

You do not need a wrapper to read data. Apple documents func data(for request: URLRequest, delegate: (any URLSessionTaskDelegate)? = nil) async throws -> (Data, URLResponse) as available from iOS 15.0, iPadOS 15.0, Mac Catalyst 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0 and visionOS 1.0. It suspends instead of taking a completion handler, throws on transport errors, and returns the raw Data plus a URLResponse you cast to HTTPURLResponse for the status code.

Swift 6 changes how you write the client more than any library would. The swift.org migration guide states that the Swift 6 language mode enables full data-race safety checking by default, and that targets in Swift 6 mode have complete checking enabled unconditionally. In practice that means two things for an API client: response models that cross task boundaries must be Sendable, and shared mutable state (the session, the key, a cache) is safer inside an actor. Every model on this page is Sendable, and the client is an actor; the whole set type-checks with swiftc -swift-version 6 targeting macOS 12.

Good for this approach: apps and command-line tools that read profiles, timelines and search results; server-side Swift (Vapor, Hummingbird) that powers your own iOS app; scripts that export data for analysis. Not covered here: letting your users sign in with their X account (that is X's OAuth, a different product) and posting from the app, which is covered briefly in the FAQ.

02 — Section

Codable models that match the real JSON

The models below are the ones we compiled and used to decode every saved page. Property names match the JSON keys exactly, including the snake_case has_next_page, next_cursor, quoted_tweet and retweeted_tweet, so no CodingKeys and no keyDecodingStrategy are needed. If you prefer camelCase Swift names, add CodingKeys per type rather than .convertFromSnakeCase, because the payload mixes camelCase (likeCount) and snake_case (next_cursor) keys and the global strategy only rewrites the snake_case ones, which is easy to get subtly wrong.

Tweet is a final class rather than a struct for one reason: a tweet can contain another tweet in quoted_tweet or retweeted_tweet, and a struct cannot hold an optional of its own type without indirection. A final class with only let properties of Sendable types is itself Sendable, and Swift 6 accepts it without warnings. An indirect enum box or a separate NestedTweet struct works too; the class is the shortest version that compiles cleanly.

Envelopes differ by endpoint, and the shapes are worth memorizing. /twitter/user/last_tweets returns status, msg, data.tweets and a top-level has_next_page and next_cursor. /twitter/tweet/advanced_search returns tweets at the top level with the same two cursor fields. /twitter/user/info returns the profile object under data, in camelCase (userName, followers, statusesCount).

Timestamps arrive as strings like Thu Oct 16 12:34:56 +0000 2026. Keep createdAt as a String in the model and parse it with a DateFormatter using the format EEE MMM dd HH:mm:ss Z yyyy and the en_US_POSIX locale. Setting dateDecodingStrategy for the whole decoder would also hit the author's createdAt, which uses the same format, so a custom strategy works, but parsing on demand keeps decoding fast and failures local.

swift
// Codable models for twitterapi.io responses. Optionality follows the
// field-presence table in results.json (collected in 2026).

struct Author: Codable, Sendable {
    let id: String
    let userName: String
    let name: String
    let followers: Int?
    let following: Int?
    let isBlueVerified: Bool?
    let verifiedType: String?
    let createdAt: String?
}

struct Media: Codable, Sendable {
    let type: String            // photo | video | animated_gif
    let media_url_https: String?
}

struct ExtendedEntities: Codable, Sendable {
    let media: [Media]?
}

final class Tweet: Codable, Sendable {
    let id: String
    let url: String
    let text: String
    let createdAt: String       // "Thu Oct 16 12:34:56 +0000 2026"
    let lang: String?
    let likeCount: Int
    let retweetCount: Int
    let replyCount: Int
    let quoteCount: Int
    let viewCount: Int?
    let bookmarkCount: Int?
    let conversationId: String?
    let isReply: Bool
    let inReplyToId: String?
    let inReplyToUsername: String?
    let author: Author
    let extendedEntities: ExtendedEntities?
    let quoted_tweet: Tweet?    // class, so the type can nest itself
    let retweeted_tweet: Tweet?
}

// /twitter/user/last_tweets: tweets sit under data, cursor at top level
struct LastTweetsPage: Codable, Sendable {
    struct Payload: Codable, Sendable { let tweets: [Tweet] }
    let status: String
    let msg: String?
    let data: Payload?
    let has_next_page: Bool?
    let next_cursor: String?
}

// /twitter/tweet/advanced_search: tweets at top level
struct SearchPage: Codable, Sendable {
    let tweets: [Tweet]
    let has_next_page: Bool
    let next_cursor: String?
}

// /twitter/user/info: unknown user is HTTP 200 + status "error" + data null
struct UserInfoResponse: Codable, Sendable {
    struct User: Codable, Sendable {
        let id: String
        let userName: String
        let name: String
        let description: String?
        let followers: Int
        let following: Int
        let statusesCount: Int
        let createdAt: String
        let isBlueVerified: Bool
        let protected: Bool?
    }
    let status: String
    let msg: String?
    let data: User?
}
03 — Section

We decoded 1,040 real tweets: which fields must be optional

Optional properties are cheap; a wrong non-optional crashes the whole page decode, because JSONDecoder throws on the first valueNotFound and you lose all 20 tweets, not one. So instead of guessing, we counted. Across 1,040 timeline tweets, no key was ever missing from the JSON: every field in the table below was present as a key in every tweet. What varies is whether the value is real, null, or an empty object or string.

FieldHas a valuenullEmpty {} or ""Swift type that decoded
id100.0%0.0%0.0%String
text100.0%0.0%0.0%String
viewCount100.0%0.0%0.0%Int? (defensive)
bookmarkCount100.0%0.0%0.0%Int? (defensive)
entities96.8%0.0%3.2%struct with optional arrays
extendedEntities51.7%0.0%48.3%ExtendedEntities? with media: [Media]?
card27.6%72.4%0.0%skip or JSON value?
retweeted_tweet18.9%81.1%0.0%Tweet? (class)
quoted_tweet4.3%95.7%0.0%Tweet? (class)
article0.7%99.3%0.0%skip or optional
inReplyToId0.0%100.0%0.0%String?
place0.0%0.0%100.0%skip (always {})

Three rows decide the shape of your model. place was an empty object in every one of the 1,040 tweets, so if you model it as a struct with required properties, every page fails; skip it or make every property optional. extendedEntities (where photos and videos live) was empty in 48.3% of tweets, so its media array must be optional even though the parent object is always there. card (link previews) was null in 72.4%. In the sample, media items were 395 photos, 240 videos and 3 animated GIFs.

Counters were present on every tweet: likeCount, retweetCount, replyCount, quoteCount, viewCount and bookmarkCount all had integer values in 100% of the sample, and viewCount was exactly 0 on 2.0% of tweets. We still keep viewCount and bookmarkCount optional in the model, because a sample of organization timelines cannot prove what an older post or a different endpoint returns, and an optional costs one ?? 0 at the call site.

Reply fields depend on the endpoint and parameters. With the default includeReplies (false), inReplyToId was null in every timeline tweet. In the 60 search results we also checked (swiftui lang:en, Latest), inReplyToId had a value in 51.7% of tweets. A model built only from timeline samples would wrongly treat it as always-null; build from both.

Author objects follow the same pattern: id, userName, name, followers, following, isBlueVerified and createdAt were present in every author object, while verifiedType was null in 38.5% and description was an empty string in 19.2%. Empty strings decode fine into a non-optional String; just do not treat empty as missing data in your UI. The source key exists on tweets but is usually an empty string, so do not build anything on it.

Nesting is common enough to model on day one: 242 of the 1,040 timeline tweets (23.3%) carried a full quoted or reposted tweet, each with its own author. With Tweet? on both properties, those decode recursively with no extra code.

Bar chart of how often each tweet field had a value, was null, or was an empty object across 1,040 timeline tweets
Field presence across 1,040 timeline tweets from six organization accounts, collected in 2026. No key was absent; null and empty values decide which Swift properties must be optional.
04 — Section

An actor-based client: one request helper, typed errors, 429 backoff

The client keeps the key, the session and the decoder inside an actor, so Swift 6 can prove that no two tasks mutate them at once. Every endpoint goes through one generic get helper that builds the URL with URLComponents, sets the X-API-Key header, calls session.data(for:), and decodes into whatever Decodable & Sendable type the caller asks for.

Two kinds of failure. HTTP-level problems (a 400 for a missing parameter, a 401 for a bad key, a 429 when you exceed your rate limit) arrive with a non-200 status code; the body text is in detail for a 400 and usually in msg for the others. Application-level problems arrive as HTTP 200 with status: "error" and a message in msg. We confirmed the second case live: asking /twitter/user/info for a name that does not exist returned {"status": "error", "msg": "user not found", "data": null} with HTTP 200, and the UserInfoResponse model decoded it without throwing, because data is optional. The client then converts it into TwitterAPIError.api(message:) so the caller sees a readable reason instead of a DecodingError.

Retry only what is retryable. The helper retries 429 and 5xx responses with exponential backoff (1, 2, 4, 8 seconds) and gives up after four attempts. It does not retry 400 or 401, because those will fail the same way every time. Note the sleep call: Task.sleep(nanoseconds:) works on iOS 15 and macOS 12, while the nicer Task.sleep(for: .seconds(...)) needs newer OS versions; we type-checked the client against a macOS 12 deployment target to catch exactly that.

Rate limits on our side are per account: 0.2 requests per second before the first payment, 20 once paid, 50 on Scale, 500 on Business, and up to 1,000 on request. A single Swift client looping through pages sequentially stays far below the paid limits; if you fan out with a TaskGroup across many accounts, cap concurrency yourself (an AsyncSemaphore-style counter in the actor works) so the free tier does not answer with 429s.

swift
import Foundation

enum TwitterAPIError: Error {
    case http(status: Int, body: String)
    case api(message: String)          // HTTP 200 with status "error", text in msg
}

actor TwitterAPIClient {
    private let base = URL(string: "https://api.twitterapi.io")!
    private let apiKey: String
    private let session: URLSession
    private let decoder = JSONDecoder()

    init(apiKey: String, session: URLSession = .shared) {
        self.apiKey = apiKey
        self.session = session
    }

    private func get<T: Decodable & Sendable>(_ path: String, _ query: [String: String]) async throws -> T {
        var comps = URLComponents(url: base.appendingPathComponent(path), resolvingAgainstBaseURL: false)!
        comps.queryItems = query.map { URLQueryItem(name: $0.key, value: $0.value) }
        var req = URLRequest(url: comps.url!)
        req.setValue(apiKey, forHTTPHeaderField: "X-API-Key")
        req.timeoutInterval = 30
        for attempt in 0..<4 {
            let (data, resp) = try await session.data(for: req)   // iOS 15+, macOS 12+
            let code = (resp as? HTTPURLResponse)?.statusCode ?? 0
            if code == 429 || code >= 500 {                        // back off and retry
                try await Task.sleep(nanoseconds: UInt64(1 << attempt) * 1_000_000_000)
                continue
            }
            guard code == 200 else {
                throw TwitterAPIError.http(status: code, body: String(decoding: data, as: UTF8.self))
            }
            return try decoder.decode(T.self, from: data)
        }
        throw TwitterAPIError.http(status: 429, body: "retries exhausted")
    }

    func userInfo(_ userName: String) async throws -> UserInfoResponse.User {
        let r: UserInfoResponse = try await get("/twitter/user/info", ["userName": userName])
        guard r.status == "success", let user = r.data else {
            throw TwitterAPIError.api(message: r.msg ?? "unknown error")
        }
        return user
    }

    func lastTweets(_ userName: String, maxPages: Int = 5) async throws -> [Tweet] {
        var all: [Tweet] = []
        var cursor = ""
        for _ in 0..<maxPages {
            let page: LastTweetsPage = try await get("/twitter/user/last_tweets",
                                                     ["userName": userName, "cursor": cursor])
            guard page.status == "success" else {
                throw TwitterAPIError.api(message: page.msg ?? "unknown error")
            }
            all += page.data?.tweets ?? []
            guard page.has_next_page == true, let next = page.next_cursor, !next.isEmpty else { break }
            cursor = next
        }
        return all
    }

    func search(_ query: String, maxPages: Int = 5) async throws -> [Tweet] {
        var all: [Tweet] = []
        var cursor = ""
        for _ in 0..<maxPages {
            let page: SearchPage = try await get("/twitter/tweet/advanced_search",
                                                 ["query": query, "queryType": "Latest", "cursor": cursor])
            all += page.tweets
            guard page.has_next_page, let next = page.next_cursor, !next.isEmpty else { break }
            cursor = next
        }
        return all
    }
}
05 — Section

Both tweet endpoints page the same way. Send an empty cursor for the first page, read has_next_page and next_cursor from the response, and send next_cursor back as cursor for the next page. Stop when has_next_page is false or the cursor comes back empty. Always cap the loop with maxPages as well, because a busy search can page for a long time and every page with tweets is billed by the tweets it returns.

Expect empty and short pages. In our run, the GitHub timeline returned two full pages of 20 tweets and then a third page with zero tweets and has_next_page: false, so the account yielded 40 tweets in 3 requests. The loop above handles that correctly because it appends page.data?.tweets ?? [] before checking the cursor. That empty request is billed at the $0.00015 minimum, which is the cost of asking, not the cost of any tweet.

For SwiftUI, wrap the loop in an AsyncThrowingStream or expose a loadMore() method on an @MainActor view model that calls the client once per page and appends to a published array. Fetching one page per scroll position keeps memory flat and avoids paying for pages the user never reads.

Search queries use X's own operators: from:SwiftLang, lang:en, since: and until: dates, -filter:replies, min_faves: and so on. Pass the whole query string as the query parameter; URLComponents handles the percent-encoding. Set queryType to Latest for a chronological feed or Top for the ranked view.

swift
import Foundation

@main
struct Demo {
    static func main() async throws {
        guard let key = ProcessInfo.processInfo.environment["TWITTERAPI_IO_KEY"] else {
            print("set TWITTERAPI_IO_KEY"); return
        }
        let client = TwitterAPIClient(apiKey: key)
        let user = try await client.userInfo("SwiftLang")
        print(user.name, user.followers, user.statusesCount)
        let tweets = try await client.search("from:SwiftLang swiftui", maxPages: 3)
        for t in tweets { print(t.createdAt, t.likeCount, t.viewCount ?? 0, t.text.prefix(80)) }
    }
}
06 — Section

iOS apps: never ship the API key, route through a small backend

Anything inside an app bundle can be read by anyone who downloads the app: string constants, Info.plist entries, obfuscated byte arrays and xcconfig values all end up in the binary or its resources. A key that ships in an app is a key that will be found and used by someone else, and every tweet they fetch is billed to you. Treat the TwitterAPI.io key exactly like a payment provider's secret key.

The pattern. The iOS app authenticates its user against your own backend (Sign in with Apple, your existing session, or a device-scoped token). The backend holds the X-API-Key, accepts only the handful of operations your app needs (for example GET /feed?user=SwiftLang), calls api.twitterapi.io, and returns the JSON, or a slimmer version of it, to the app. The app reuses the same Codable models; only the base URL and the auth header change.

What the backend adds beyond hiding the key. An allowlist of paths and parameters, so a stolen app token cannot be turned into a general-purpose proxy; a per-user rate cap that matches your own budget; a short cache (for example 60 seconds for a feed) so a hundred users opening the same screen cost one fetch; and logging, so an unusual spike shows up before the bill does. Server-side Swift with Vapor or Hummingbird lets you share the model file between app and server; any other server stack works just as well.

Command-line tools and servers can read the key from the environment (ProcessInfo.processInfo.environment), as the demo above does, or from the macOS Keychain. Never commit it to a repository, and never put it in a Package.swift or a test fixture.

07 — Section

How long it takes, and how big the pages are

The network dominates. Through our Python collector, which spaces requests across several parallel jobs to stay at 5 requests per second in total, a 20-tweet timeline page took a median 3.45 s of wall time (range 3.26 to 4.59 s per account), a search page 3.39 s, and a profile lookup a median 1.72 s. Those numbers include waiting for the shared pacer, so a lone client with nothing else in flight may see shorter times; treat them as an upper bound for planning, not a latency benchmark.

AccountPagesTweetsWall s per pageMedian KB per page
NASA102004.59144
github3403.26139
nvidia102003.36147
Docker102003.26101
vercel102003.45166
SwiftLang102004.46136

Pages are larger than many developers expect: a median 144 KB of compact JSON per 20-tweet page, from 91 KB to 211 KB, or roughly 6.9 MB per 1,000 tweets. Nested quoted and reposted tweets, full author objects on every tweet, and media and URL entities all add up. On a cellular connection that is a reason to page lazily, and a reason for your backend to strip fields the app never shows before forwarding.

Decoding is cheap by comparison. Built with swiftc -O -swift-version 6 (Swift 6.1.2 on an arm64 Mac), JSONDecoder decoded all 52 saved timeline pages (1,040 tweets) in 29.0 ms in total, a median 0.53 ms per page and 27.9 ms per 1,000 tweets, using the median of seven runs per file. That is offline decoding of files on disk; it says nothing about device performance on an older iPhone, but it does show that decoding on the main actor is not where a feed screen loses time. Still decode off the main actor in an app, because the network await is where the time goes and the UI should stay responsive.

Two bar charts: wall seconds per 20-tweet page and median kilobytes per page for six organization accounts
Wall time per page through our paced Python client and median page size, six organization accounts, collected in 2026. Swift decode times come from offline runs on the saved pages.
08 — Section

What it costs, compared with the official X API

TwitterAPI.io bills per result: 15 credits per tweet returned, which is $0.15 per 1,000 tweets, and 18 credits per profile, which is $0.18 per 1,000 profiles. A request has a minimum of 15 credits, so a search or timeline call that returns nothing costs $0.00015; a full 20-tweet page costs $0.003. There is no per-request cap. Credits convert at $1 = 100,000 credits, purchased credits never expire, and new accounts that pass the automatic bot check get free starter credits (no card, one per person or network, expiring after 31 days); the current amount is on the pricing page.

The official X API 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, and $0.015 per post created ($0.20 with a URL). Pay-per-usage is capped at 3 million post reads a month, with Enterprise above that. Per 1,000 tweets that is $5.00 on X's card against $0.15 here, roughly 33 times the price.

JobTwitterAPI.ioOfficial X API (pay-per-usage card)
1,000 tweets (timeline or search results)$0.15$5.00 at $0.005 per post read
1,000 profile lookups$0.18$10.00 at $0.010 per user read
A poll that finds no new tweets$0.00015 minimumno post read billed
This study: 1,100 tweets + 7 profilesabout $0.17about $5.57

For a polling feed, the floor matters more than the per-tweet price: a check every 60 seconds for a month is 43,200 checks, or $6.48 if every one comes back empty; every 5 minutes it is $1.30. Subscriptions start at Starter $29 a month and run through Builder $99, Pro $199, Scale $499 and Business $1,499; see the pricing page for what each includes.

09 — Section

How we collected this

Question. What does a Swift client actually receive when it pages through about 1,000 tweets: how many requests, how long and how large each page is, how long Swift Codable takes to decode the saved pages, and which tweet and author fields are present, null or empty?

Accounts and queries. Recent timeline posts of six organization accounts (NASA, GitHub, NVIDIA, Docker, Vercel and the Swift project's own account) via /twitter/user/last_tweets with default parameters, up to 10 pages each; /twitter/user/info for the same six accounts plus one name that does not exist; and three pages of /twitter/tweet/advanced_search for swiftui lang:en (Latest), used only for envelope and field-presence checks.

Sample and cost. 63 requests in total (53 timeline, 7 profile, 3 search), 1,040 timeline tweets and 60 search tweets, for about $0.17 at the prices above. Collected in 2026.

Method. Requests went through our rate-limited Python collector (shared 5 requests per second across parallel jobs), timed per account with the wall clock. Each saved page was re-serialized as compact JSON to measure bytes. The Swift models and client on this page were compiled with Swift 6.1.2 in Swift 6 language mode on macOS; a small benchmark program decoded every saved file seven times and kept the median. The Swift client itself never called the network, because the study ran without exposing the API key to it, and we did not build for an iOS device (no iOS SDK on the build machine), only type-checked against a macOS 12 deployment target.

What the sample cannot show. Six organization timelines are not a random sample of X: they skew toward media-rich posts and contain no replies by default, so field rates for replies, polls, or personal accounts will differ. Wall times include waiting for a shared pacer and are not a latency benchmark. Decode times are for one Mac, not a phone.

Privacy. Aggregates only. Reposted and quoted tweets include authors who are not organizations, so raw pages were kept out of the published study folder; it holds the field-presence counts, de-identified per-tweet rows and the Swift source.

python
# Save real response pages as fixtures for Swift Codable unit tests.
# 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"]}
OUT = pathlib.Path("Tests/Fixtures")
OUT.mkdir(parents=True, exist_ok=True)


def get(url, params):
    r = requests.get(url, headers=HEADERS, params=params, timeout=30)
    r.raise_for_status()
    body = r.json()
    if body.get("status") == "error":
        raise RuntimeError(body.get("msg"))
    return body


# 1. profile: object under "data"
info = get(f"{BASE}/twitter/user/info", {"userName": "SwiftLang"})
(OUT / "user_info.json").write_text(json.dumps(info))
print(info["data"]["name"], info["data"]["followers"], info["data"]["statusesCount"])

# 2. timeline: tweets under data.tweets, cursor at the top level
cursor, page_no = "", 0
while page_no < 3:
    page = get(f"{BASE}/twitter/user/last_tweets", {"userName": "SwiftLang", "cursor": cursor})
    (OUT / f"last_tweets_{page_no}.json").write_text(json.dumps(page))
    tweets = page["data"]["tweets"]
    print("timeline page", page_no, len(tweets), "tweets")
    page_no += 1
    if not page.get("has_next_page") or not page.get("next_cursor"):
        break
    cursor = page["next_cursor"]

# 3. search: tweets at the top level
cursor, page_no = "", 0
while page_no < 2:
    page = get(f"{BASE}/twitter/tweet/advanced_search",
               {"query": "swiftui lang:en", "queryType": "Latest", "cursor": cursor})
    (OUT / f"search_{page_no}.json").write_text(json.dumps(page))
    print("search page", page_no, len(page["tweets"]), "tweets")
    page_no += 1
    if not page.get("has_next_page") or not page.get("next_cursor"):
        break
    cursor = page["next_cursor"]

# 4. an unknown user: HTTP 200, status "error", data null (good negative fixture)
r = requests.get(f"{BASE}/twitter/user/info", headers=HEADERS,
                 params={"userName": "no_such_user_123456789"}, timeout=30)
(OUT / "user_info_not_found.json").write_text(r.text)
print(r.status_code, r.json().get("msg"))

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

Not one this guide relies on. The community packages older tutorials use have stalled: TwitterAPIKit is archived on GitHub (last push November 2022) and Swifter describes itself as deprecated (last push June 2022). For reading data, URLSession with async/await and Codable models is enough, as this guide shows.

Which iOS version do I need for URLSession async/await?

Apple documents URLSession.data(for:delegate:) as available from iOS 15.0, iPadOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, Mac Catalyst 15.0 and visionOS 1.0. For older targets, wrap dataTask(with:completionHandler:) in withCheckedThrowingContinuation.

Can I put my API key in the iOS app?

No. Anything in the app bundle can be extracted, and every request made with a leaked key is billed to you. Keep the key on a small backend that authenticates your users, allowlists the endpoints the app needs, caches responses and enforces a per-user rate cap. The app talks only to your backend.

Why does JSONDecoder throw on some pages but not others?

Usually a property is non-optional in your model but null or an empty object in some tweets. In our 1,040-tweet sample, card was null in 72.4% of tweets, extendedEntities was empty in 48.3%, and place was an empty object in every tweet. Make those optional (or skip them) and decode errors on whole pages disappear.

How do I handle errors like user not found?

Check the status field on every response. An unknown user returns HTTP 200 with status: "error", msg: "user not found" and data: null, so model data as optional, then throw your own error with the msg text. Non-200 codes carry their message in msg, or in detail for a 400 on a missing or invalid parameter.

Does this work with Swift 6 strict concurrency?

Yes. The models are Sendable structs plus a final class Tweet with only immutable Sendable properties, and the client is an actor. The code compiles with swiftc -swift-version 6, which turns on full data-race checking, and type-checks against a macOS 12 deployment target.

Can I post tweets from Swift?

Yes, through your backend, never from the app with the key. Write actions use an authenticated session: one /twitter/user_login_v2 login ($0.10, with a proxy you supply) returns login_cookies, then calls such as /twitter/create_tweet_v2 cost 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 human pace, and expect the session to need a re-login now and then.

How much does it cost to load a feed of 1,000 tweets?

$0.15, because tweets are billed at 15 credits each, plus nothing for the decode. On the official X API pay-per-usage card the same 1,000 post reads cost $5.00 at $0.005 each. A poll that returns no new tweets costs the $0.00015 minimum.

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.