Skip to content

Commit 77edff3

Browse files
strzibnyclaude
andcommitted
Return searches with empty results instead of raising
BREAKING CHANGE: JSON responses with HTTP 200 and a top-level error key no longer raise SerpApiError. SerpApi returns searches with empty results this way (search_metadata.status Success), 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 or when search_metadata.status is Error. Code that rescued SerpApiError to detect empty results must check results[:error] instead. Also set SerpApiError#serpapi_error and #search_id when using symbolize_names: false. Fixes #17 Co-authored-by: Claude Opus 5.5 (xhigh effort) <noreply@anthropic.com>
1 parent 73322c6 commit 77edff3

4 files changed

Lines changed: 168 additions & 8 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
11
# Changelog
2+
* [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 or when `search_metadata.status` is `Error`. Code that rescued `SerpApiError` to detect empty results must check `results[:error]` instead #17
3+
* [Unreleased] Set `SerpApiError#serpapi_error` and `#search_id` when using `symbolize_names: false`
24
* [Unreleased] Add native Extract API support via the `extract` method
35
* [Unreleased] Apply the `timeout` option to persistent connections
46
* [Unreleased] Add Image API support

‎README.md‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -170,6 +170,34 @@ puts 'done'
170170

171171
This code shows a simple solution to batch searches asynchronously into a [queue](https://en.wikipedia.org/wiki/Queue_(abstract_data_type)). Each search may take up to a few seconds to complete. By the time the first element pops out of the queue, the search results might already be available in the archive. If not, the `search_archive` method blocks until the search results are available.
172172

173+
## Error handling
174+
175+
`SerpApi::SerpApiError` is raised when a request fails: the HTTP status is not `200` (for example, an invalid API key, a missing parameter, or no searches left) or the search finished with `search_metadata.status` set to `Error`. The error includes the details returned by SerpApi:
176+
177+
```ruby
178+
begin
179+
results = client.search(q: "coffee")
180+
rescue SerpApi::SerpApiError => e
181+
e.serpapi_error # => "Invalid API key. Your API key should be here: https://serpapi.com/manage-api-key"
182+
e.response_status # => 401
183+
e.search_id # => ID of the failed search, when SerpApi created one
184+
end
185+
```
186+
187+
A search with no results from the search engine is still successful, so it is returned like any other search, with the message in `results[:error]`:
188+
189+
```ruby
190+
results = client.search(q: "a query without results")
191+
results[:search_metadata][:status] # => "Success"
192+
results[:error] # => "Google hasn't returned any results for this query."
193+
```
194+
195+
The same applies to `search_archive`, so you can retrieve the metadata of archived searches with empty results.
196+
197+
> **Breaking change:** version 1.0.3 and earlier raised `SerpApiError` for any response with an `error` key, including searches with empty results. If you rescued `SerpApiError` to detect empty results, check `results[:error]` instead.
198+
199+
See [Status and Error Codes](https://serpapi.com/api-status-and-error-codes) for the full list of statuses.
200+
173201
## Examples
174202

175203
Here are some examples for some of our most popular APIs. You can find the full list of supported engines and parameters in our [documentation](https://serpapi.com/search-engine-apis).

‎lib/serpapi/client.rb‎

Lines changed: 24 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -110,9 +110,13 @@ def initialize(params = {})
110110
# note that the raw response
111111
# from the search engine is converted to JSON by SerpApi.com backend.
112112
# thus, most of the compute power is on the backsdend and not on the client side.
113+
# A search that completed with empty results (e.g. "Google hasn't returned any results for this query.")
114+
# is successful: it is returned with a top-level `error` key instead of raising.
115+
#
113116
# @param [Hash] params includes engine, api_key, search fields and more..
114117
# this override the default params provided to the constructor.
115118
# @return [Hash|String] search results formatted as a Hash or raw text.
119+
# @raise [SerpApiError] if the HTTP status is not 200 or `search_metadata.status` is `Error`.
116120
def search(params = {})
117121
get('/search', :json, params)
118122
end
@@ -222,9 +226,12 @@ def upload_image(image, params = {})
222226
# example: spec/serpapi/client/search_archive_api_spec.rb
223227
# doc: https://serpapi.com/search-archive-api
224228
#
229+
# Archived searches with empty results are returned with a top-level `error` key instead of raising.
230+
#
225231
# @param [String|Integer] search_id from original search `results[:search_metadata][:id]`
226232
# @param [Symbol] format :json, :html, or :md [default: json, optional]
227233
# @return [String|Hash] raw HTML, Markdown, or JSON / Hash
234+
# @raise [SerpApiError] if the HTTP status is not 200 or `search_metadata.status` is `Error`.
228235
def search_archive(search_id, format = :json)
229236
raise SerpApiError, 'format must be json, html, or md' unless [:json, :html, :md].include?(format)
230237

@@ -359,29 +366,38 @@ def process_text_response(response, endpoint, params, decoder)
359366
response.body.to_s
360367
end
361368

369+
# A top-level `error` key alone does not mean the request failed: SerpApi returns
370+
# HTTP 200 with `search_metadata.status: Success` and an `error` message for searches
371+
# with empty results. Failed searches have a non-200 status or `search_metadata.status: Error`.
372+
# see: https://serpapi.com/api-status-and-error-codes
362373
def validate_json_content!(data, response, endpoint, params)
363-
if data.is_a?(Hash) && data.key?(:error)
364-
raise_http_error(response, data, endpoint, params, explicit_error: data[:error])
365-
elsif response.status != 200
366-
raise_http_error(response, data, endpoint, params)
374+
if response.status != 200
375+
raise_http_error(response, data, endpoint, params, explicit_error: json_value(data, :error))
376+
elsif json_value(json_value(data, :search_metadata), :status) == 'Error'
377+
raise_http_error(response, data, endpoint, params, explicit_error: json_value(data, :error), failure: 'Search failed with status: Error')
367378
end
368379
end
369380

370381
# Centralized error raising to clean up the logic methods
371-
def raise_http_error(response, data, endpoint, params, explicit_error: nil, decoder: :json)
372-
msg = "HTTP request failed with status: #{response.status}"
382+
def raise_http_error(response, data, endpoint, params, explicit_error: nil, decoder: :json, failure: nil)
383+
msg = failure || "HTTP request failed with status: #{response.status}"
373384
msg += " error: #{explicit_error}" if explicit_error
374385

375386
raise SerpApiError.new(
376387
"#{msg} from url: https://#{BACKEND}#{endpoint}",
377-
serpapi_error: explicit_error || (data.is_a?(Hash) ? data[:error] : nil),
388+
serpapi_error: explicit_error || json_value(data, :error),
378389
search_params: params,
379390
response_status: response.status,
380-
search_id: data.is_a?(Hash) ? data&.dig(:search_metadata, :id) : nil,
391+
search_id: json_value(json_value(data, :search_metadata), :id),
381392
decoder: decoder
382393
)
383394
end
384395

396+
# Read a JSON value whether keys were symbolized or not (`symbolize_names: false`).
397+
def json_value(data, key)
398+
data.fetch(key) { data[key.to_s] } if data.is_a?(Hash)
399+
end
400+
385401
def raise_parser_error(response, endpoint, params)
386402
raise SerpApiError.new(
387403
"JSON parse error: #{response.body} from url: https://#{BACKEND}#{endpoint}",
Lines changed: 114 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,114 @@
1+
require 'spec_helper'
2+
3+
# SerpApi returns searches with empty results as HTTP 200 with `search_metadata.status: Success`
4+
# and a top-level `error` message. Only non-200 responses and `search_metadata.status: Error` are failures.
5+
# see: https://serpapi.com/api-status-and-error-codes
6+
describe 'JSON error handling' do
7+
let(:socket) { double }
8+
let(:client) { SerpApi::Client.new(api_key: 'test-key', engine: 'google') }
9+
10+
let(:empty_results) do
11+
{
12+
search_metadata: { id: '6935c0b9a0cb1015d74ef919', status: 'Success', created_at: '2025-12-07 18:00:57 UTC' },
13+
search_information: { organic_results_state: 'Fully empty' },
14+
error: "Google hasn't returned any results for this query."
15+
}
16+
end
17+
18+
let(:failed_search) do
19+
{
20+
search_metadata: { id: '64c32cfeb68f8bc186aaa013', status: 'Error' },
21+
error: "We couldn't get valid results for this search. Please try again later."
22+
}
23+
end
24+
25+
def json_response(status, body)
26+
double(
27+
status: status,
28+
body: JSON.generate(body),
29+
headers: { 'Content-Type' => 'application/json; charset=utf-8' },
30+
flush: nil
31+
)
32+
end
33+
34+
before do
35+
allow(HTTP).to receive(:timeout).and_return(double(persistent: socket))
36+
end
37+
38+
describe 'searches with empty results' do
39+
it 'returns search results with the error key instead of raising' do
40+
allow(socket).to receive(:get).with('/search', anything).and_return(json_response(200, empty_results))
41+
42+
expect(client.search(q: 'no results')).to eq(empty_results)
43+
end
44+
45+
it 'returns archived search results with the error key instead of raising' do
46+
allow(socket).to receive(:get)
47+
.with('/searches/6935c0b9a0cb1015d74ef919.json', anything)
48+
.and_return(json_response(200, empty_results))
49+
50+
results = client.search_archive('6935c0b9a0cb1015d74ef919')
51+
52+
expect(results[:error]).to eq("Google hasn't returned any results for this query.")
53+
expect(results[:search_metadata][:created_at]).to eq('2025-12-07 18:00:57 UTC')
54+
end
55+
56+
it 'returns search results with string keys' do
57+
allow(socket).to receive(:get).with('/search', anything).and_return(json_response(200, empty_results))
58+
59+
results = client.search(q: 'no results', symbolize_names: false)
60+
61+
expect(results['error']).to eq("Google hasn't returned any results for this query.")
62+
end
63+
end
64+
65+
describe 'failed searches' do
66+
it 'raises when search_metadata.status is Error with HTTP 200' do
67+
allow(socket).to receive(:get)
68+
.with('/searches/64c32cfeb68f8bc186aaa013.json', anything)
69+
.and_return(json_response(200, failed_search))
70+
71+
expect {
72+
client.search_archive('64c32cfeb68f8bc186aaa013')
73+
}.to raise_error(SerpApi::SerpApiError, /\ASearch failed with status: Error error: We couldn't get valid results/) do |error|
74+
expect(error.serpapi_error).to eq(failed_search[:error])
75+
expect(error.search_id).to eq('64c32cfeb68f8bc186aaa013')
76+
expect(error.response_status).to eq(200)
77+
end
78+
end
79+
80+
it 'raises when search_metadata.status is Error with string keys' do
81+
allow(socket).to receive(:get).with('/search', anything).and_return(json_response(200, failed_search))
82+
83+
expect {
84+
client.search(q: 'coffee', symbolize_names: false)
85+
}.to raise_error(SerpApi::SerpApiError) do |error|
86+
expect(error.serpapi_error).to eq(failed_search[:error])
87+
expect(error.search_id).to eq('64c32cfeb68f8bc186aaa013')
88+
end
89+
end
90+
91+
it 'raises for non-200 responses' do
92+
allow(socket).to receive(:get).with('/search', anything).and_return(json_response(503, failed_search))
93+
94+
expect {
95+
client.search(q: 'coffee')
96+
}.to raise_error(SerpApi::SerpApiError, /\AHTTP request failed with status: 503 error: We couldn't get valid results/) do |error|
97+
expect(error.serpapi_error).to eq(failed_search[:error])
98+
expect(error.search_id).to eq('64c32cfeb68f8bc186aaa013')
99+
expect(error.response_status).to eq(503)
100+
end
101+
end
102+
103+
it 'raises for non-200 responses without an error key' do
104+
allow(socket).to receive(:get).with('/account', anything).and_return(json_response(500, {}))
105+
106+
expect {
107+
client.account
108+
}.to raise_error(SerpApi::SerpApiError, %r{\AHTTP request failed with status: 500 from url: https://serpapi.com/account\z}) do |error|
109+
expect(error.serpapi_error).to be_nil
110+
expect(error.response_status).to eq(500)
111+
end
112+
end
113+
end
114+
end

0 commit comments

Comments
 (0)