Integrate search data into your AI workflow, RAG, fine-tuning, or Ruby application using this official SerpApi Ruby SDK. SerpApi supports Google, Google Maps, Google Shopping, Baidu, Yandex, Yahoo, eBay, App Stores, and many more.
Ruby 2.7 or later is required.
Install the SDK directly with RubyGems:
gem install serpapiOr add it to your application's Gemfile:
gem "serpapi"Then install it with Bundler:
bundle installCreate a SerpApi account to get your API key, then store it in an environment variable:
export SERPAPI_KEY="your_api_key"Run a Google search and access the results as a Ruby Hash:
require "serpapi"
require "pp"
client = SerpApi::Client.new(
engine: "google",
api_key: ENV.fetch("SERPAPI_KEY")
)
results = client.search(q: "coffee")
pp results[:organic_results]
client.close- Asynchronous searches for submitting non-blocking jobs and retrieving completed results from the Search Archive API.
- Persistent connections and connection pooling for reusing HTTP connections across searches.
- Search results as Ruby hashes with
search, token-efficient Markdown withmd, or raw search-engine HTML withhtml. - SDK methods for the Extract API, Image API, Location API, Search Archive API, and Account API.
- Configurable HTTP timeouts and symbolized or string JSON keys.
Use search for structured results decoded into a Ruby Hash:
results = client.search(q: "coffee")Use md for a token-efficient Markdown String optimized for LLMs and AI agents:
markdown = client.md(q: "coffee")Use html when you need the raw search-engine response:
raw_html = client.html(q: "coffee")Archived results are also available as Markdown with client.search_archive(search_id, :md).
Learn more about SerpApi Markdown output.
Set defaults when creating a client, then override search parameters in individual calls:
client = SerpApi::Client.new(
api_key: ENV.fetch("SERPAPI_KEY"),
engine: "google",
hl: "en",
gl: "us",
persistent: true,
timeout: 120
)
results = client.search(
q: "coffee",
gl: "gb",
async: false,
symbolize_names: true
)| Option | Default | Description |
|---|---|---|
api_key |
None | Your SerpApi API key. Use an environment variable rather than committing it to source control. |
engine |
None | The search engine used by default, such as google or google_maps. |
persistent |
true |
Reuses the HTTP connection between requests. Call client.close when finished. |
timeout |
120 |
Timeout in seconds for HTTP requests. |
async |
false |
Submits searches without waiting for them to complete. It can be set on the client or per search. |
symbolize_names |
true |
Returns JSON object keys as symbols. Pass false to a search to receive string keys. |
Search-engine-specific parameters can also be supplied when creating the client or calling search. Parameters passed to search override client defaults.
Search API features non-blocking search using the option: async=true.
- Non-blocking - async=true - a single parent process can handle unlimited concurrent searches.
- Blocking - async=false - many processes must be forked and synchronized to handle concurrent searches. This strategy is I/O usage because each client would hold a network connection.
Search API enables async search.
- Non-blocking (
async=true): the development is more complex, but this allows handling many simultaneous connections. - Blocking (
async=false): it is easy to write the code, but more compute-intensive when the parent process needs to hold many connections.
Here is an example of asynchronous searches using Ruby
require 'serpapi'
company_list = %w[meta amazon apple netflix google]
client = SerpApi::Client.new(engine: 'google', async: true, persistent: true, api_key: ENV['SERPAPI_KEY'])
schedule_search = Queue.new
result = nil
company_list.each do |company|
result = client.search(q: company)
puts "#{company}: search results found in cache for: #{company}" if result[:search_metadata][:status] =~ /Cached/
schedule_search.push(result[:search_metadata][:id])
end
puts "Last search submited at: #{result[:search_metadata][:created_at]}"
puts 'wait 10s for all requests to be completed '
sleep(10)
puts 'wait until all searches are cached or successful'
until schedule_search.empty?
search_id = schedule_search.pop
search_archived = client.search_archive(search_id)
company = search_archived[:search_parameters][:q]
if search_archived[:search_metadata][:status] =~ /Cached|Success/
puts "#{search_archived[:search_parameters][:q]}: search results found in archive for: #{company}"
next
end
schedule_search.push(search_id)
end
schedule_search.close
puts 'done'- source code: demo/demo_async.rb
This code shows a simple solution to batch searches asynchronously into a queue. Each search may take up to a few seconds to complete. By the time the first element pops out of the queue, the search results might already be available in the archive. If not, the search_archive method blocks until the search results are available.
Here are some examples for some of our most popular APIs. You can find the full list of supported engines and parameters in our documentation.
Get the main content of any public web page as Markdown, along with page information, meta tags, structured data (Open Graph, Twitter Card, Dublin Core, JSON-LD, microdata), inline links, images, videos, audios, and feeds.
require 'serpapi'
client = SerpApi::Client.new(api_key: ENV['SERPAPI_KEY'])
results = client.extract(url: 'https://example.com/')
pp results[:page_information]
puts results[:markdown]Use output: 'md' to get only the page's Markdown as a String:
markdown = client.extract(url: 'https://example.com/', output: 'md')The same method exposes two additional modes:
maplists the website's URLs from page links and sitemaps, and returns aurlsarray. Setinclude_sitemap: falseto skip the sitemaps and list only URLs linked from the page. Setinclude_subdomains: trueto include other subdomains, such asblog.example.comwhen starting fromwww.example.com; this also applies to crawl mode.crawlfollows links on the same website up tomax_pages/max_depthand returns the extracted pages in apagesarray. Crawl mode consumes one search credit per successfully extracted page, including the starting page.max_pagesdefaults to10(maximum100), so a crawl without it can consume up to 10 credits.
# list the URLs of a website
results = client.extract(url: 'https://books.toscrape.com/', mode: 'map')
pp results[:urls]
# list only the URLs linked from the page, including other subdomains
results = client.extract(url: 'https://books.toscrape.com/', mode: 'map', include_sitemap: false, include_subdomains: true)
pp results[:urls]
# crawl a website and extract every visited page
results = client.extract(url: 'https://books.toscrape.com/', mode: 'crawl', max_pages: 3, max_depth: 1)
pp results[:pages]A timeout passed to extract is the Extract API fetch timeout in milliseconds. The client timeout is the HTTP timeout in seconds for the whole request, so raise it as well for slow pages or crawls:
client = SerpApi::Client.new(api_key: ENV['SERPAPI_KEY'], timeout: 180)
results = client.extract(url: 'https://example.com/', timeout: 60_000)To extract a page found in the results, pass its URL to extract again. Settings such as device or include_tags are not carried over, so pass them again if needed:
results = client.extract(url: 'https://example.com/')
linked_page = client.extract(url: results[:inline_links].first[:link])- source code: demo/demo_extract.rb
Note: URLs of pages covered by a dedicated SerpApi engine (such as Google, Bing, eBay, or Walmart search pages) are redirected to that engine and return its results.
Scrape Google Shopping results with product names, prices, ratings, and merchant information.
require 'serpapi'
client = SerpApi::Client.new(engine: 'google_shopping', api_key: ENV['SERPAPI_KEY'])
results = client.search(q: 'Macbook M4')
pp results[:shopping_results]Google Shopping Light
A light variant engine called google_shopping_light is also available for faster, lower-cost shopping searches.
Scrape Google Images search results, including image URLs, thumbnails, titles, and source pages.
require 'serpapi'
client = SerpApi::Client.new(engine: 'google_images', api_key: ENV['SERPAPI_KEY'])
results = client.search(q: 'coffee')
pp results[:images_results]Google Images Light
A light variant engine called google_images_light is also available for faster, lower-cost image searches.
Upload an image with the Image API, then use its image ID in a Google Lens search. Uploaded image IDs expire after 10 minutes.
require 'serpapi'
client = SerpApi::Client.new(api_key: ENV['SERPAPI_KEY'])
upload = client.upload_image('./image.jpg')
results = client.search(engine: 'google_lens', image_id: upload[:image_id])
pp results[:visual_matches]See Image API documentation · See Google Lens image upload documentation
Track search interest over time and compare the popularity of search terms.
require 'serpapi'
client = SerpApi::Client.new(engine: 'google_trends', api_key: ENV['SERPAPI_KEY'])
results = client.search(q: 'coffee', data_type: 'TIMESERIES')
pp results[:interest_over_time]Search flight routes, schedules, prices, and booking options.
Note: The
google_flightsengine does not useq. Specify route and date parameters such asdeparture_id,arrival_id,outbound_date, andreturn_date.
require 'date'
require 'serpapi'
outbound_date = (Date.today + 30).iso8601
return_date = (Date.today + 37).iso8601
client = SerpApi::Client.new(engine: 'google_flights', api_key: ENV['SERPAPI_KEY'])
results = client.search(
departure_id: 'LAX',
arrival_id: 'AUS',
outbound_date: outbound_date,
return_date: return_date
)
flights = results[:best_flights] || results[:other_flights]
pp flightsThe Google AI Mode API returns AI-generated answers with structured text blocks, references, images, products, and more.
require 'serpapi'
client = SerpApi::Client.new(engine: 'google_ai_mode', api_key: ENV['SERPAPI_KEY'])
results = client.search(q: 'best coffee maker')
pp results[:reconstructed_markdown]Scrape Bing web search results, including organic results, ads, related searches, and more.
require 'serpapi'
client = SerpApi::Client.new(engine: 'bing', api_key: ENV['SERPAPI_KEY'])
results = client.search(q: 'coffee')
pp results[:organic_results]Scrape DuckDuckGo search results, including organic results, ads, knowledge graphs, and related searches.
require 'serpapi'
client = SerpApi::Client.new(engine: 'duckduckgo', api_key: ENV['SERPAPI_KEY'])
results = client.search(q: 'coffee')
pp results[:organic_results]Scrape Baidu search results, including organic results, answer boxes, and related searches.
require 'serpapi'
client = SerpApi::Client.new(engine: 'baidu', api_key: ENV['SERPAPI_KEY'])
results = client.search(q: 'coffee')
pp results[:organic_results]Scrape Amazon product search results, including product names, prices, ratings, reviews, and availability.
Note: The
amazonengine uses thekparameter for a keyword search, notq.
require 'serpapi'
client = SerpApi::Client.new(engine: 'amazon', api_key: ENV['SERPAPI_KEY'])
results = client.search(k: 'coffee')
pp results[:organic_results]SerpApi supports Google Search, Google Maps, Google Shopping, Baidu, Yandex, Yahoo, eBay, Apple App Store, and many other APIs. Browse the SerpApi documentation to find supported APIs and parameters, or use the Playground to build a request and generate Ruby code.
Additional SDK resources:
| Metric | Ruby 2.7.8 | Ruby 3.4.4 | Ruby 4.0.0 | Improvement (3.4.4 vs 2.7.8) | Improvement (4.0.0 vs 3.4.4) |
|---|---|---|---|---|---|
| SerpApi Non-Persistent | 100.93 req/s | 114.97 req/s | 120.09 req/s | +13.9% | +4.5% |
| SerpApi Persistent | 226.82 req/s | 255.07 req/s | 296.05 req/s | +12.4% | +16.1% |
| HTTP.rb Non-Persistent | 270.62 req/s | 294.01 req/s | 319.81 req/s | +8.6% | +8.8% |
| HTTP.rb Persistent | 347.04 req/s | 570.95 req/s | 456.93 req/s | +64.5% | -20.0% |
The older library (google-search-results-ruby) was performing at 55 req/s on Ruby 2.7.8, which is 2x slower than the current version (serpapi-ruby) on Ruby 3.4.4 or 4.0.0.
This benchmark was performed on warmup search results using a MacBook Pro 2025 connected via Wi-Fi 6.0 home network on AT&T fiber from Austin, TX (no network optimization).
Contributions are welcome. Make sure to read our contributing guide.
© 2026 SerpApi