Class: SerpApi::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/serpapi/client.rb

Overview

Client for SerpApi.com powered by HTTP.rb

features:

  • async non-block search
  • persistent HTTP connection
  • search API
  • location API
  • account API
  • search archive API

Constant Summary collapse

BACKEND =

Backend service URL

'serpapi.com'.freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(params = {}) ⇒ Client

Constructor The Serpapi::Client constructor takes a hash of options as input.

Example:

require 'serpapi'

client = SerpApi::Client.new(
  api_key: "secure API key",
  engine: "google",
  timeout: 30,
  persistent: true
)

result = client.search(q: "coffee")

client.close

Parameters:

  • api_key: [String] User secret API key.
  • engine: [String] Search engine selected.
  • persistent: [Boolean] Keep socket connection open to save on SSL handshake / connection reconnectino (2x faster). [default: true]
  • async: [Boolean] Support non-blocking job submission. [default: false]
  • timeout: [Integer] HTTP get max timeout in seconds [default: 120s == 2m]
  • symbolize_names: [Boolean] Convert JSON keys to symbols. [default: true]

Key:kr

The key parameter can be either a symbol or a string.

Note:

  • All parameters are optional.
  • The close method should be called when the client is no longer needed.

Parameters:

  • params (Hash) (defaults to: {})

    default for the search

Raises:



69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
# File 'lib/serpapi/client.rb', line 69

def initialize(params = {})
  raise SerpApiError, 'params cannot be nil' if params.nil?
  raise SerpApiError, "params must be hash, not: #{params.class}" unless params.instance_of?(Hash)

  # store client HTTP request timeout
  @timeout = params[:timeout] || 120
  @timeout.freeze

  # enable HTTP persistent mode
  @persistent = true
  @persistent = params[:persistent] if params.key?(:persistent)
  @persistent.freeze

  # delete this client only configuration keys
  %i[timeout persistent].each do |option|
    params.delete(option) if params.key?(option)
  end

  # set default query parameters
  @params = params.clone || {}

  # track ruby library as a client for statistic purpose
  @params[:source] = 'serpapi-ruby:' << SerpApi::VERSION

  # ensure default parameter would not be modified later
  @params.freeze

  # create connection socket
  return unless persistent?

  @socket = HTTP.persistent("https://#{BACKEND}")
end

Instance Attribute Details

#paramsObject (readonly)

HTTP timeout requests



20
21
22
# File 'lib/serpapi/client.rb', line 20

def params
  @params
end

#persistentObject (readonly)

HTTP timeout requests



20
21
22
# File 'lib/serpapi/client.rb', line 20

def persistent
  @persistent
end

#socketObject (readonly)

HTTP timeout requests



20
21
22
# File 'lib/serpapi/client.rb', line 20

def socket
  @socket
end

#timeoutObject (readonly)

HTTP timeout requests



20
21
22
# File 'lib/serpapi/client.rb', line 20

def timeout
  @timeout
end

Instance Method Details

#account(api_key = nil) ⇒ Hash

Get account information using Account API

example: spec/serpapi/client/account_api_spec.rb doc: https://serpapi.com/account-api

Parameters:

  • api_key (String) (defaults to: nil)

    secret key [optional if already provided to the constructor]

Returns:

  • (Hash)

    account information



164
165
166
167
# File 'lib/serpapi/client.rb', line 164

def (api_key = nil)
  params = (api_key.nil? ? {} : { api_key: api_key })
  get('/account', :json, params)
end

#api_keyString

Returns api_key user secret API key as provided to the constructor.

Returns:

  • (String)

    api_key user secret API key as provided to the constructor



175
176
177
# File 'lib/serpapi/client.rb', line 175

def api_key
  @params[:api_key]
end

#closeObject

close open connection if active



180
181
182
# File 'lib/serpapi/client.rb', line 180

def close
  @socket.close if @socket
end

#engineString

Returns default search engine.

Returns:

  • (String)

    default search engine



170
171
172
# File 'lib/serpapi/client.rb', line 170

def engine
  @params[:engine]
end

#html(params = {}) ⇒ String

html search perform a search using SerpApi.com the output is raw HTML from the search engine. it is useful for training AI models, RAG, debugging or when you need to parse the HTML yourself.

Returns:

  • (String)

    raw html search results directly from the search engine.



122
123
124
# File 'lib/serpapi/client.rb', line 122

def html(params = {})
  get('/search', :html, params)
end

#location(params = {}) ⇒ Array<Hash>

Get location using Location API

example: spec/serpapi/location_api_spec.rb doc: https://serpapi.com/locations-api

Parameters:

  • params (Hash) (defaults to: {})

    must includes fields: q, limit

Returns:

  • (Array<Hash>)

    list of matching locations



133
134
135
# File 'lib/serpapi/client.rb', line 133

def location(params = {})
  get('/locations.json', :json, params)
end

#search(params = {}) ⇒ Hash

perform a search using SerpApi.com

see: https://serpapi.com/search-api

note that the raw response from the search engine is converted to JSON by SerpApi.com backend. thus, most of the compute power is on the backsdend and not on the client side.

Parameters:

  • params (Hash) (defaults to: {})

    includes engine, api_key, search fields and more.. this override the default params provided to the constructor.

Returns:

  • (Hash)

    search results formatted as a Hash.



112
113
114
# File 'lib/serpapi/client.rb', line 112

def search(params = {})
  get('/search', :json, params)
end

#search_archive(search_id, format = :json) ⇒ String|Hash

Retrieve search result from the Search Archive API

client = SerpApi::Client.new(engine: 'google', api_key: ENV['SERPAPI_KEY'])
results = client.search(q: 'Coffee', location: 'Portland')
search_id = results[:search_metadata][:id]
archive_search = client.search_archive(search_id)

example: spec/serpapi/client/search_archive_api_spec.rb doc: https://serpapi.com/search-archive-api

Parameters:

  • search_id (String|Integer)

    from original search results[:search_metadata][:id]

  • format (Symbol) (defaults to: :json)

    :json or :html [default: json, optional]

Returns:

  • (String|Hash)

    raw html or JSON / Hash

Raises:



151
152
153
154
155
# File 'lib/serpapi/client.rb', line 151

def search_archive(search_id, format = :json)
  raise SerpApiError, 'format must be json or html' unless [:json, :html].include?(format)

  get("/searches/#{search_id}.#{format}", format)
end