Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
# Changelog
* [Unreleased] Apply the client's `symbolize_names` default to JSON responses, including `search_archive`, `account`, and `upload_image`. Before, only a `symbolize_names` passed to a search was used #44
* [Unreleased] Override client defaults with search parameters given with the other key type (String or Symbol). Before, both values were sent, and a `nil` didn't remove the default #45
* [Unreleased] Decode response media types case-insensitively and allow whitespace before parameters
* [Unreleased] Identify the library, Ruby runtime, and platform in the `User-Agent` header (e.g. `serpapi-ruby/1.1.0 ruby/3.4.1 (darwin; arm64)`) instead of the `source` query parameter
* [Unreleased] **BREAKING:** JSON responses with HTTP 200 and a top-level `error` key no longer raise `SerpApiError`. SerpApi returns searches with empty results this way (e.g. "Google hasn't returned any results for this query."), so `search`, `search_archive`, and `extract` now return them as a Hash with the message in `results[:error]`. `SerpApiError` is raised only for non-200 responses. Code that rescued `SerpApiError` to detect empty results must check `results[:error]` instead. With `symbolize_names: false`, these responses were already returned, with the message in `results["error"]` #17
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ results = client.search(
| `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. |
| `symbolize_names` | `true` | Returns JSON object keys as symbols. Pass `false` to receive string keys. It can be set on the client or per search. |

Search-engine-specific parameters can also be supplied when creating the client or calling `search`. Parameters passed to `search` override client defaults.

Expand Down
23 changes: 13 additions & 10 deletions lib/serpapi/client.rb
Original file line number Diff line number Diff line change
Expand Up @@ -187,9 +187,7 @@ def extract(params = {})
raise SerpApiError, "params must be hash, not: #{params.class}" unless params.instance_of?(Hash)
raise SerpApiError, 'url parameter is required by the extract API' if params[:url].to_s.empty? && params['url'].to_s.empty?

# also drop string-keyed engines; 'engine' => nil removes one inherited
# from the client defaults, since query compacts nil values
search(params.reject { |key, _| key.to_s == 'engine' }.merge('engine' => nil, engine: 'extract'))
search(params.reject { |key, _| key.to_s == 'engine' }.merge(engine: 'extract'))
end

# Get location using Location API
Expand Down Expand Up @@ -298,22 +296,27 @@ def force_output(params, format)
end

# @param [Hash] params to merge with default parameters provided to the constructor.
# @return [Hash] merged query parameters after cleanup
# @return [Hash] merged query parameters after cleanup, with Symbol keys
def query(params)
raise SerpApiError, "params must be hash, not: #{params.class}" unless params.instance_of?(Hash)

# merge default params with custom params
q = @params.clone.merge(params)
q.delete('output') if params.key?(:output)
q.delete(:output) if params.key?('output') && !params.key?(:output)
# merge default params with custom params, which override a default
# given with either key type (String or Symbol)
q = symbolize_keys(@params).merge(symbolize_keys(params))

# do not pollute default params with custom params
q.delete_if { |key, _| key.to_s == 'symbolize_names' }
q.delete(:symbolize_names)

# delete empty key/value
q.compact
end

# A String and a Symbol key name the same request parameter. When a hash has both,
# the Symbol key wins, as in #option.
def symbolize_keys(hash)
hash.reject { |key, _| key.is_a?(String) && hash.key?(key.to_sym) }.transform_keys(&:to_sym)
end

# @return [Boolean] HTTP session persistent enabled
def persistent?
persistent
Expand Down Expand Up @@ -396,7 +399,7 @@ def error_details(response)
end

def parse_json(response, endpoint, params)
JSON.parse(response.body, symbolize_names: option(params, :symbolize_names, true))
JSON.parse(response.body, symbolize_names: option(params, :symbolize_names, option(@params, :symbolize_names, true)))
rescue JSON::ParserError, EncodingError
raise_parser_error(response, endpoint, params)
end
Expand Down
59 changes: 59 additions & 0 deletions spec/serpapi/client/query_params_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
require 'spec_helper'
require 'stringio'

# These specs stub HTTP::Client#perform, so they make no HTTP request to serpapi.com.
describe 'query parameters' do
let(:response) do
double(status: 200, body: '{}', headers: { 'Content-Type' => 'application/json' }, flush: nil)
end
let(:requests) { [] }

before do
allow_any_instance_of(HTTP::Client).to receive(:perform) do |_http, request, _options|
requests << request
response
end
end

# Query string of the last request as [name, value] pairs, duplicates included
def sent_query
URI.decode_www_form(requests.last.uri.query)
end

[['engine', :engine], [:engine, 'engine']].each do |default_key, call_key|
it "overrides a #{default_key.inspect} client default with #{call_key.inspect}" do
client = SerpApi::Client.new(default_key => 'google', api_key: 'test-key', persistent: false)

client.search(call_key => 'bing', q: 'coffee')

expect(sent_query).to contain_exactly(%w[engine bing], %w[api_key test-key], %w[q coffee])
expect(client.params).to eq(default_key => 'google', api_key: 'test-key')
end
end

it 'removes a client default when a search sets it to nil with the other key type' do
client = SerpApi::Client.new('location' => 'Austin, TX', api_key: 'test-key', persistent: false)

client.search(q: 'coffee', location: nil)

expect(sent_query).to contain_exactly(%w[api_key test-key], %w[q coffee])
end

it 'sends the Symbol key value when a search has both key types' do
client = SerpApi::Client.new(api_key: 'test-key', persistent: false)

client.search(q: 'coffee', 'output' => 'html', output: 'json')

expect(sent_query).to contain_exactly(%w[api_key test-key], %w[q coffee], %w[output json])
end

it 'overrides a client default API key in an image upload' do
client = SerpApi::Client.new('api_key' => 'default-key', persistent: false)

client.upload_image(StringIO.new('image data'), api_key: 'call-key')

body = +''
requests.last.body.each { |chunk| body << chunk }
expect(body.scan(/name="api_key"\r\n\r\n(.*?)\r\n/)).to eq([['call-key']])
end
end
25 changes: 25 additions & 0 deletions spec/serpapi/client/symbolize_names_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -27,4 +27,29 @@
it 'returns Symbol keys by default' do
expect(client.search(q: 'coffee')).to eq(search_metadata: { id: '1' })
end

describe 'client default' do
[:symbolize_names, 'symbolize_names'].each do |key|
it "returns String keys and keeps #{key.inspect} out of the request" do
client = SerpApi::Client.new(api_key: 'test-key', persistent: false, key => false)

expect(client.search(q: 'coffee')).to eq('search_metadata' => { 'id' => '1' })
expect(http).to have_received(:get) do |_url, options|
expect(options[:params].keys.map(&:to_s)).not_to include('symbolize_names')
end
end
end

it 'is overridden by the search option' do
client = SerpApi::Client.new(api_key: 'test-key', persistent: false, symbolize_names: false)

expect(client.search(q: 'coffee', 'symbolize_names' => true)).to eq(search_metadata: { id: '1' })
end

it 'applies to search_archive, which has no search option' do
client = SerpApi::Client.new(api_key: 'test-key', persistent: false, symbolize_names: false)

expect(client.search_archive('1')).to eq('search_metadata' => { 'id' => '1' })
end
end
end