From 189cce3d4598c5378f66236cb5110a4a36ca0b37 Mon Sep 17 00:00:00 2001 From: Josef Strzibny Date: Wed, 2 Dec 2026 14:54:31 +0100 Subject: [PATCH 1/2] Apply the client's symbolize_names default to JSON responses Client.new(symbolize_names: false) is documented, but parse_json only read the option from the call params, so the constructor value was ignored. search_archive takes no params, so its responses always had Symbol keys. Fall back to the client default when the call doesn't set the option. Fixes #44 Co-authored-by: Claude Opus 5.5 (xhigh effort) --- CHANGELOG.md | 1 + README.md | 2 +- lib/serpapi/client.rb | 2 +- spec/serpapi/client/symbolize_names_spec.rb | 25 +++++++++++++++++++++ 4 files changed, 28 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 019b28f..a946ece 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,4 +1,5 @@ # 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] 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 diff --git a/README.md b/README.md index 5579f46..e9a65fc 100644 --- a/README.md +++ b/README.md @@ -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. diff --git a/lib/serpapi/client.rb b/lib/serpapi/client.rb index e48f70f..6d6ce82 100644 --- a/lib/serpapi/client.rb +++ b/lib/serpapi/client.rb @@ -396,7 +396,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 diff --git a/spec/serpapi/client/symbolize_names_spec.rb b/spec/serpapi/client/symbolize_names_spec.rb index da76a0b..e9c1c3a 100644 --- a/spec/serpapi/client/symbolize_names_spec.rb +++ b/spec/serpapi/client/symbolize_names_spec.rb @@ -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 From ec09a056b7396477dd0e425ef1bc77b665924ef9 Mon Sep 17 00:00:00 2001 From: Josef Strzibny Date: Wed, 2 Dec 2026 14:54:42 +0100 Subject: [PATCH 2/2] Override client defaults whatever the key type of search parameters String and Symbol keys are both accepted, but query merged the client defaults and the search params as plain Hashes. A default given with one key type and an override given with the other were both sent under the same parameter name, and a nil override didn't remove the default. Convert the keys of both Hashes to Symbols before merging. When one Hash has both key types, the Symbol key wins, as it already did for output. This replaces the output special cases in query and the 'engine' => nil workaround in extract. client.params still has the keys given to the constructor. Fixes #45 Co-authored-by: Claude Opus 5.5 (xhigh effort) --- CHANGELOG.md | 1 + lib/serpapi/client.rb | 21 +++++---- spec/serpapi/client/query_params_spec.rb | 59 ++++++++++++++++++++++++ 3 files changed, 72 insertions(+), 9 deletions(-) create mode 100644 spec/serpapi/client/query_params_spec.rb diff --git a/CHANGELOG.md b/CHANGELOG.md index a946ece..604f4d9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +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 diff --git a/lib/serpapi/client.rb b/lib/serpapi/client.rb index 6d6ce82..9a0d626 100644 --- a/lib/serpapi/client.rb +++ b/lib/serpapi/client.rb @@ -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 @@ -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 diff --git a/spec/serpapi/client/query_params_spec.rb b/spec/serpapi/client/query_params_spec.rb new file mode 100644 index 0000000..e3c746a --- /dev/null +++ b/spec/serpapi/client/query_params_spec.rb @@ -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