All Swift tutorials

How to scrape X (Twitter) Search with Swift

Search X posts. X search operators work. This tutorial gets it with a short Swift program and the X (Twitter) Search API. Each successful call costs 1 credit; errors and not-found answers are free.

1. Get an API key

Sign in to get a key and 100 free credits, no card. Then put the key in an environment variable so it stays out of your code:

export SCRAPEIO_API_KEY="your_key_here"

2. Set up Swift

Swift 5.7 or newer (macOS or Linux)

3. Write the code

Save this as main.swift.

import Foundation
#if canImport(FoundationNetworking)
import FoundationNetworking
#endif

var components = URLComponents(string: "https://scrapeio.com/v1/twitter/search")!
components.queryItems = [URLQueryItem(name: "query", value: "coffee")]
var request = URLRequest(url: components.url!)
request.setValue(ProcessInfo.processInfo.environment["SCRAPEIO_API_KEY"], forHTTPHeaderField: "x-api-key")

let done = DispatchSemaphore(value: 0)
URLSession.shared.dataTask(with: request) { data, response, error in
    defer { done.signal() }
    guard let data = data, (response as? HTTPURLResponse)?.statusCode == 200 else {
        print("Request failed:", error?.localizedDescription ?? "HTTP \((response as? HTTPURLResponse)?.statusCode ?? 0)")
        return
    }
    print(String(data: data, encoding: .utf8) ?? "")
}.resume()
done.wait()

This prints the first page. To get the next one, send the value of data.cursor as the cursor parameter and call again until data.has_more is false.

4. Run it

swift main.swift

The response has the same envelope on every endpoint: success, cached, credits_used, credits_remaining and data. Shared fields such as handle, followers, plays, likes and created_at have the same names on every platform.

Parameters

NameTypeDescription
query (required)stringSearch text.
typetop, latestRanking. Default: top.
cursorstringCursor from the previous page's data.cursor.

Errors and what you pay

StatusMeaningCharged
200SuccessYes, unless cached
400A parameter is missing or wrongNo
401The key is missing or invalidNo
402Not enough creditsNo
403The account or post is privateNo
404Not found on the platformNo
429More than 300 requests a minuteNo
502Every source is down; retry shortlyNo

Same endpoint in other languages

Python · Node.js · JavaScript · TypeScript · Go · Rust · Java · C# · PHP · Ruby · Kotlin · R

Prefer no code?

Connect the MCP server to Claude Code, Cursor or Codex and ask in plain English. The agent uses the twitter_search tool for you.

100 free credits, no card. Credits never expire.

Get API key

More X (Twitter) tutorials in Swift