Skip to content

Google Search API in Ruby: Get Google Results with Net::HTTP

A 30 second timeout can cost you a search and still lose the answer. Fetch Google results in Ruby with Net::HTTP and the JustSERP API: a 90 second read timeout, retries with backoff, correct rank maths and a thread pool.

Google Search API in Ruby: Get Google Results with Net::HTTP

The most common way to waste a search API call is to hang up too early. Ruby's Net::HTTP gives up after 60 seconds by default and plenty of examples shorten that to 30, but a hard Google query can legitimately take longer than that on our side. If your script disconnects first, the call is still counted and you get nothing back. I'll show you how to fetch Google results from Ruby with the JustSERP API without that trap, using only the standard library.

Ruby code calling the JustSERP API with Net::HTTP

What you need

  • Ruby 2.7 or newer. Only net/http, json and openssl from the standard library are used.
  • A JustSERP API key. Sign up, then copy the key from your dashboard.

Keep the key out of your source code and read it from an environment variable:

export JUSTSERP_API_KEY="your-key-here"

Call the API from your server, never from code that reaches a visitor's browser. In Rails, call it from a controller, a job or a service object and send your own front end the results.

How a request works

You send a keyword and any options as JSON to https://api.justserp.com/v1/search. We fetch the Google results page, parse it, and return clean JSON. One request returns one results page, typically in 2 to 4 seconds. The typical case is not the worst case: when Google pushes back we retry the fetch before giving up, so a difficult query can take well over a minute. Set your read timeout to 90 seconds and you will not cut those off.

We always ask Google for unfiltered, non-personalised results, so you see the full list without "similar results omitted" and without anyone's search history shaping it. Nothing is cached on our side. Every call is a fresh fetch.

Diagram: your Ruby code sends a POST request to JustSERP, which returns parsed JSON

Your first request

Send the key in the X-API-Key header and the search in the JSON body. Only keyword is required.

require "net/http"
require "json"

uri = URI("https://api.justserp.com/v1/search")
request = Net::HTTP::Post.new(
  uri,
  "X-API-Key" => ENV.fetch("JUSTSERP_API_KEY"),
  "Content-Type" => "application/json"
)
request.body = JSON.generate(keyword: "best coffee grinder")

response = Net::HTTP.start(uri.host, uri.port, use_ssl: true, open_timeout: 10, read_timeout: 90) do |http|
  http.request(request)
end

abort "Request failed: #{response.code} #{response.body}" unless response.code == "200"

data = JSON.parse(response.body)
(data["organic_results"] || []).each do |result|
  puts "#{result["position"]}. #{result["title"]}"
  puts "    #{result["link"]}"
end

Always set the timeouts. open_timeout limits the connection and read_timeout limits the wait for the answer, so a stuck request can never hang your script. ENV.fetch raises a clear error if the variable is missing.

What comes back

The answer is a JSON object. A block only appears when Google showed it on that page, so default optional blocks to an empty value.

{
  "meta": {
    "status": 200,
    "query": "best coffee grinder",
    "device": "desktop",
    "googleURL": "https://www.google.com/search?...",
    "params": { "keyword": "best coffee grinder" },
    "time_taken": "3.41"
  },
  "totalResults": 48200000,
  "organic_results": [
    { "position": 1, "title": "...", "link": "https://...", "description": "..." }
  ],
  "paid_ads": [ { "position": 1, "title": "...", "link": "...", "description": "..." } ],
  "related_questions": [ "What is the best grinder for espresso?" ],
  "related_search": [ "best burr coffee grinder" ],
  "knowledge_graph": { "title": "...", "description": "..." },
  "inline_videos": [ { "position": 1, "source": "..." } ]
}
organic   = data["organic_results"] || []
ads       = data["paid_ads"] || []
questions = data["related_questions"] || []
knowledge = data["knowledge_graph"]

puts "#{organic.size} organic results, #{ads.size} ads"
questions.each { |question| puts "People also ask: #{question}" }

A few details worth knowing. paid_ads is one list in page order, with no top or bottom flag. related_questions holds the question text only, not the answers. Mobile answers have no inline_videos or totalResults. And meta.time_taken covers everything on our side, including any retries, which makes it a handy number to log.

A reusable method and the advanced parameters

Every option goes in the same JSON body. This small module wraps the request, merges any options you pass, and raises a JustSerp::Error on failure. The rest of the guide builds on it.

require "net/http"
require "json"
require "openssl"

module JustSerp
  URL = URI("https://api.justserp.com/v1/search")

  class Error < StandardError
    attr_reader :status

    def initialize(message, status = nil)
      super(message)
      @status = status
    end
  end

  def self.search(keyword, **options)
    request = Net::HTTP::Post.new(
      URL,
      "X-API-Key" => ENV.fetch("JUSTSERP_API_KEY"),
      "Content-Type" => "application/json"
    )
    request.body = JSON.generate({ keyword: keyword }.merge(options))

    response = Net::HTTP.start(URL.host, URL.port, use_ssl: true, open_timeout: 10, read_timeout: 90) do |http|
      http.request(request)
    end

    unless response.code == "200"
      raise Error.new("HTTP #{response.code}: #{response.body}", response.code.to_i)
    end

    JSON.parse(response.body)
  end
end
Table of JustSERP request parameters with defaults and descriptions

Country, language and location

country (default "United States") and language (default "English") take full English names such as "United Kingdom" or "Germany", not codes like "UK" or "de". A name we don't recognise is not an error. It falls back to United States and English, and the call is still used. When results look wrong, check meta["googleURL"] and meta["params"] in the answer.

For "near me" searches use location, a city in Google's canonical City,Region,Country form. We convert it into Google's uule parameter as-is and do not validate it. A misspelled location is not rejected: Google ignores it, you get non-local results and the call is used. Copy canonical names exactly, and send a matching country too, because location does not change the Google domain or language. You can also send a ready-made uule string, though location wins when both are present.

french = JustSerp.search("assurance auto", country: "France", language: "French")

local = JustSerp.search("plumber near me", country: "United States", location: "Austin,Texas,United States")

Pagination, devices, time filters and exact queries

page: 2 returns the second page. It overrides start: page N becomes start=(N-1)*10. Each page uses one API call. Position restarts at 1 on every page, so the absolute rank is (page - 1) * 10 + position, as long as Google returned ten organic results on that page. device is "desktop" or "mobile". tbs is passed straight to Google, so qdr:d is the past day and qdr:w the past week. nfpr set to "1" turns off Google's auto-correction. Both tbs and nfpr must be strings.

ranks = {}
[1, 2, 3].each do |page|
  data = JustSerp.search("project management software", page: page, device: "mobile")
  (data["organic_results"] || []).each do |item|
    ranks[item["link"]] ||= (page - 1) * 10 + item["position"]
  end
end
ranks.sort_by { |_link, rank| rank }.first(5).each { |link, rank| puts "#{rank}  #{link}" }

news  = JustSerp.search("openai announcement", tbs: "qdr:d")
exact = JustSerp.search("justserp", nfpr: "1")

Pass html: true to get the raw Google page in an html field as well. Responses get much larger, so only use it when you need it. The q alias also works in place of keyword. Unknown fields are dropped without a warning, so a typo like contry: silently does nothing.

Handling errors, and what is billed

Check the HTTP status before you read the body:

StatusMeaningWhat to do
200Success. One API call is used.Read the results.
400Invalid parameters. No call is used.Fix the request. Do not retry it unchanged.
401The API key is missing or invalid.Check the X-API-Key header.
429You have no API calls left.Top up or upgrade your plan.
500The page could not be fetched. No call is used.Retry after a short pause.

A 200 uses a call. A 400, a 500 or another server error does not, and a 401 or 429 never counts. Retrying a failure therefore costs nothing, apart from the request your own client abandons, which is still counted. A 500 reaches you only after we have retried on our side. This addition to the module retries a 500 and network failures with a growing delay, and fails at once on 400, 401 and 429:

module JustSerp
  NETWORK_ERRORS = [
    Net::OpenTimeout, Net::ReadTimeout, SocketError, EOFError,
    Errno::ECONNRESET, Errno::ECONNREFUSED, OpenSSL::SSL::SSLError
  ].freeze

  def self.search_with_retry(keyword, retries: 3, **options)
    attempt = 0
    begin
      search(keyword, **options)
    rescue Error => e
      raise unless e.status == 500 && attempt < retries

      attempt += 1
      sleep(2**(attempt - 1)) # 1s, 2s, 4s...
      retry
    rescue *NETWORK_ERRORS
      raise if attempt >= retries

      attempt += 1
      sleep(2**(attempt - 1))
      retry
    end
  end
end

Running searches in parallel with threads

Almost all of a search's time is spent waiting on the network, and Ruby threads release the interpreter lock while they wait, so plain threads give a real speed-up. Your plan sets how many requests may be in flight together: 10 on Free and Personal, 25 on Business, 50 on Enterprise. That counts requests in progress, not requests per second. A queue and a fixed number of worker threads keep you within that limit:

module JustSerp
  def self.search_many(keywords, workers: 5, **options)
    queue = Queue.new
    keywords.each_with_index { |keyword, index| queue << [keyword, index] }
    queue.close # pop returns nil once the queue is empty

    results = Array.new(keywords.size)

    threads = Array.new(workers) do
      Thread.new do
        while (job = queue.pop)
          keyword, index = job
          results[index] =
            begin
              data = search_with_retry(keyword, **options)
              { keyword: keyword, count: (data["organic_results"] || []).size }
            rescue StandardError => e
              { keyword: keyword, error: e.message }
            end
        end
      end
    end

    threads.each(&:join)
    results
  end
end

keywords = ["crm software", "email marketing tool", "invoice app", "seo checker"]
JustSerp.search_many(keywords, workers: 5).each do |row|
  puts row[:error] ? "#{row[:keyword]}: #{row[:error]}" : "#{row[:keyword]}: #{row[:count]} results"
end

Exactly workers requests run at once, however long the keyword list is, and the results keep the order of the input. Each thread writes to its own array slot, so no lock is needed.

Habits that save calls and headaches

  • Call the API from the server and keep the key in an environment variable or Rails credentials, never in a repository.
  • Set open_timeout to 10 and read_timeout to 90 so a stuck request cannot hang a worker, and a slow one is not abandoned while we are still working on it.
  • Cache results you will reuse, with Rails.cache or Redis. We do not cache searches, so a repeated search is a repeated call.
  • Default optional blocks with || []. Google does not show ads, knowledge panels or videos on every page.
  • Keep workers within your plan's concurrency limit, so requests are never rejected for sending too many at once.

Next steps

That covers what you need to put Google data into your Ruby projects. Create a free account for 2,000 free requests, no credit card needed, and try the examples above, or see the pricing when you are ready to scale. Prefer another language? Read the Python version of this guide or the JavaScript version.