Skip to content
Closed
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
# Changelog
* [Unreleased] Identify the library, Ruby runtime, and platform in the `User-Agent` header (e.g. `serpapi-ruby/1.0.3 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
* [Unreleased] Set `SerpApiError#serpapi_error` and `#search_id` when using `symbolize_names: false`
* [Unreleased] Raise `SerpApiError` instead of `TypeError` for non-200 responses whose `error` or `search_metadata.id` is not a String
Expand Down
19 changes: 14 additions & 5 deletions lib/serpapi/client.rb
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,13 @@ class Client
# HTTP.rb client
:socket

# User-Agent sent with every request so SerpApi can report library usage by version, Ruby runtime, and platform.
#
# @return [String] e.g. "serpapi-ruby/1.0.3 ruby/3.4.1 (darwin; arm64)"
def self.user_agent
"serpapi-ruby/#{SerpApi::VERSION} #{RUBY_ENGINE}/#{RUBY_ENGINE_VERSION} (#{Gem::Platform.local.os}; #{Gem::Platform.local.cpu})"
end

# Constructor
# The `Serpapi::Client` constructor takes a hash of options as input.
#
Expand Down Expand Up @@ -91,16 +98,13 @@ def initialize(params = {})
# 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.timeout(timeout).persistent("https://#{BACKEND}")
@socket = http_client.persistent("https://#{BACKEND}")
end

# perform a search using SerpApi.com
Expand Down Expand Up @@ -341,11 +345,16 @@ def post(endpoint, decoder = :json, params = {}, form = {})
end

def execute_request(method, endpoint, options)
client = persistent? ? @socket : HTTP.timeout(timeout)
client = persistent? ? @socket : http_client
url = persistent? ? endpoint : "https://#{BACKEND}#{endpoint}"
client.public_send(method, url, **options)
end

# @return [HTTP::Client] HTTP client with the request timeout and the library User-Agent
def http_client
HTTP.timeout(timeout).headers('User-Agent' => self.class.user_agent)
end

def response_decoder(response, default)
content_type = response.headers['Content-Type'].to_s.split(';').first
CONTENT_TYPE_DECODERS.fetch(content_type, default)
Expand Down
2 changes: 1 addition & 1 deletion spec/serpapi/client/error_handling_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ def raw_response(status, body, content_type)
end

before do
allow(HTTP).to receive(:timeout).and_return(double(persistent: socket))
allow(HTTP).to receive(:timeout).and_return(double(headers: double(persistent: socket)))
end

describe 'searches with empty results' do
Expand Down
2 changes: 1 addition & 1 deletion spec/serpapi/client/extract_api_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ def sent_params
http = double
response = double(status: 200, body: '{}', headers: { 'Content-Type' => 'application/json' })
sent = nil
allow(HTTP).to receive(:timeout).and_return(http)
allow(HTTP).to receive(:timeout).and_return(double(headers: http))
allow(http).to receive(:get) do |_url, params:|
sent = params
response
Expand Down
2 changes: 1 addition & 1 deletion spec/serpapi/client/image_api_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
let(:client) { SerpApi::Client.new(api_key: api_key) }

before do
allow(HTTP).to receive(:timeout).and_return(double(persistent: socket))
allow(HTTP).to receive(:timeout).and_return(double(headers: double(persistent: socket)))
allow(response).to receive(:flush)
end

Expand Down
44 changes: 44 additions & 0 deletions spec/serpapi/client/user_agent_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
require 'spec_helper'

describe 'SerpApi client usage reporting' do
describe '.user_agent' do
{
['ruby', '3.4.1', 'arm64-darwin-23'] => 'serpapi-ruby/1.0.3 ruby/3.4.1 (darwin; arm64)',
['ruby', '3.3.6', 'x86_64-linux'] => 'serpapi-ruby/1.0.3 ruby/3.3.6 (linux; x86_64)',
['ruby', '3.4.1', 'aarch64-linux-musl'] => 'serpapi-ruby/1.0.3 ruby/3.4.1 (linux; aarch64)',
['ruby', '3.4.1', 'x64-mingw-ucrt'] => 'serpapi-ruby/1.0.3 ruby/3.4.1 (mingw; x64)',
['jruby', '9.4.9.0', 'universal-java-21'] => 'serpapi-ruby/1.0.3 jruby/9.4.9.0 (java; universal)'
}.each do |(engine, engine_version, platform), user_agent|
it "is #{user_agent} for #{engine} #{engine_version} on #{platform}" do
stub_const('SerpApi::VERSION', '1.0.3')
stub_const('RUBY_ENGINE', engine)
stub_const('RUBY_ENGINE_VERSION', engine_version)
allow(Gem::Platform).to receive(:local).and_return(Gem::Platform.new(platform))

expect(SerpApi::Client.user_agent).to eq(user_agent)
end
end
end

describe 'requests' do
let(:response) do
double(status: 200, body: '{}', headers: { 'Content-Type' => 'application/json' }, flush: nil)
end

[true, false].each do |persistent|
it "send the User-Agent header instead of a source parameter when persistent is #{persistent}" do
client = SerpApi::Client.new(api_key: 'dummy_secret_key', persistent: persistent)
sent = nil
allow_any_instance_of(HTTP::Client).to receive(:perform) do |_http, request, _options|
sent = request
response
end

client.search(q: 'Coffee')

expect(sent.headers['User-Agent']).to eq(SerpApi::Client.user_agent)
expect(URI.decode_www_form(sent.uri.query).to_h).to eq('api_key' => 'dummy_secret_key', 'q' => 'Coffee')
end
end
end
end
Loading