SerpApi Swift Library
Integrate search data into your AI workflow, RAG / fine-tuning, or iOS/macOS application using this official wrapper for SerpApi.
SerpApi supports Google, Google Maps, Google Shopping, Baidu, Yandex, Yahoo, eBay, App Stores, and more.
Query a vast range of data at scale, including web search results, flight schedules, stock market data, news headlines, and more.
Features
-
Configurable Session Mode: Uses persistent
URLSessionpooling by default, with optional ephemeral mode via"persistent": "false". - Async/Await: Native Swift concurrency support for non-blocking operations.
- Type-Safe: Clean API design with error handling.
- Extensive Documentation: Easy to follow with real-world examples.
Installation
Swift Package Manager
Add the following to your Package.swift dependencies:
dependencies: [
.package(url: "https://github.com/serpapi/serpapi-swift", from: "1.0.0")
]
Or add it via Xcode: File > Add Packages... and search for https://github.com/serpapi/serpapi-swift.
Simple Usage
import SerpApi
// Initialize the client
let client = SerpApiClient(params: ["engine": "google", "api_key": "YOUR_API_KEY"])
// Perform a search
do {
let results = try await client.search(params: ["q": "coffee"])
print(results)
} catch {
print(error)
}
The SerpApi key can be obtained from serpapi.com/signup.
Demo of the Events example app (macOS GUI):
Advanced Usage
Configuration
You can configure the client with default parameters that will be applied to every request.
let client = SerpApiClient(params: [
"engine": "google",
"api_key": ProcessInfo.processInfo.environment["SERPAPI_KEY"] ?? "",
"timeout": "30", // HTTP timeout in seconds (default: 120)
"persistent": "true" // Use persistent session; set "false" for ephemeral mode
])
// Override specific parameters per request
let results = try await client.search(params: [
"q": "Coffee",
"location": "Austin, TX"
])
Retries & Exponential Backoff
Transient failures (HTTP 429/5xx and brief network errors) are retried automatically using full-jitter exponential backoff. The server's Retry-After header is honored when present. Retry behavior is optional and fully configurable — it defaults to max_retries = 3 and can be disabled by setting max_retries to "0".
let client = SerpApiClient(params: [
"engine": "google",
"api_key": "YOUR_API_KEY",
"max_retries": "3", // retry attempts for transient failures (default: 3, set "0" to disable)
"retry_base_delay": "0.5", // base delay in seconds for backoff (default: 0.5)
"retry_max_delay": "8.0" // cap for any single backoff wait, also caps Retry-After (default: 8.0)
])
Only transient failures are retried — client errors such as 401 (invalid key) fail immediately, and cancellation always propagates without being retried.
Async Search (Non-blocking)
SerpApi supports non-blocking search submission via async=true. This allows you to submit a batch of searches and retrieve them later.
// Submit search with async=true
let response = try await client.search(params: ["q": "Tesla", "async": "true"])
if let searchMetadata = response["search_metadata"] as? [String: Any],
let searchID = searchMetadata["id"] as? String {
// Retrieve results later using the Search Archive API
let archived = try await client.searchArchive(searchID: searchID)
print(archived)
}
HTML Output
Get the raw HTML from the search engine.
let html = try await client.html(params: ["q": "Coffee"])
print(html) // "<!doctype html>..."
APIs Supported
Location API
let locations = try await client.location(params: ["q": "Austin", "limit": "3"])
for location in locations {
print(location["name"] ?? "")
}
Search Archive API
Retrieve past search results (free of charge).
let results = try await client.searchArchive(searchID: "SEARCH_ID")
Account API
Get your account information and usage.
let account = try await client.account()
print(account)
Developer Guide
Dependencies
Ruby and Rake must be installed to run the tests and demo, as well Swift via Xcode command line tools.
brew install ruby
Tests
To run the tests, you need a SerpApi key set in your environment variables.
export SERPAPI_KEY="your_key"
rake test
To run tests with a coverage report:
export SERPAPI_KEY="your_key"
rake coverage
Demo
Run the command-line demo application to see the library in action.
rake demo
Examples
The repository includes standalone example packages in the Examples directory. Keeping examples in separate packages ensures the core library remains platform-agnostic and easy to integrate, while providing a "real-world" testing ground for the SDK.
- Demo: A command-line tool showing basic search, HTML output, and API interactions.
- EventsDemo: A full SwiftUI iOS / macOS application for searching local events with GPS support and date filtering.
To run the EventsDemo:
-
Via CLI (macOS Simulator):
(Requires full Xcode installation. The task will attempt to find/boot a simulator and launch the app.)rake ios -
Via CLI (macOS Desktop version):
rake events -
Via Xcode (Full iOS App):
- Open
Package.swiftin Xcode. - Select the
EventsDemoscheme. - Select an iOS Simulator and press
Run.
- Open
Documentation
Generate documentation using:
rake doc
For the full list of targets, run:
rake -T
License
MIT License.