Metadata-Version: 2.4
Name: serpbit
Version: 0.3.0
Summary: Google Search, News, Shopping, Images, Videos, Maps, Autocomplete and AI Mode as data: the Serpbit API client.
Author-email: Serpbit <support@serpbit.com>
License-Expression: MIT
Project-URL: Homepage, https://serpbit.com
Project-URL: Documentation, https://serpbit.com/docs/#sdks
Keywords: serp,google search api,serp api,web search,ai agents,rag
Classifier: Programming Language :: Python :: 3
Classifier: Operating System :: OS Independent
Classifier: Intended Audience :: Developers
Classifier: Topic :: Internet :: WWW/HTTP :: Indexing/Search
Classifier: Typing :: Typed
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Dynamic: license-file

# serpbit

Google Search, News, Shopping, Images, Videos, Maps, Autocomplete and AI Mode as data, from
[Serpbit](https://serpbit.com). No dependencies: the standard library only, Python 3.9+.

```sh
pip install serpbit
```

```python
from serpbit import Serpbit

sb = Serpbit()  # reads SERPBIT_API_KEY; make a key at https://app.serpbit.com/keys

answer = sb.search("espresso grinder", gl="de", hl="de", pages=2)
for r in answer["organic"]:
    print(r["position"], r["title"], r["url"])

# The first three results' pages, as Markdown text: 1 credit a page read.
answer = sb.search("how to descale an espresso machine", content=3)
print(answer["organic"][0]["content"]["text"][:500])

# Markdown instead of JSON, for a language model's context.
print(sb.news("wildfire", sort="date", output="md"))
```

Every door of the API has a method: `search`, `news`, `shopping`, `shopping_product`, `images`, `videos`, `maps`,
`autocomplete`, `ai_mode`, and `custom_search` (Google's Custom Search JSON API, drop-in). Keyword arguments are the
door's parameters, as the [docs](https://serpbit.com/docs/)
name them:
- `True` is sent as `true`;
- `None` and `False` are left out;
- a list is joined with commas.

A method returns the API's JSON as a dict, or a `str` with `output="md"`. `sb.last_request_id` and
`sb.last_credits` give the last answer's id and the credits it spent.

## Browser API

Real browsers on residential connections, billed by the traffic they move (your browser plan's GB). The connect URL
opens a session when a client connects and ends it when the client goes:

```python
from playwright.sync_api import sync_playwright
from serpbit import Serpbit

sb = Serpbit()
with sync_playwright() as p:
    browser = p.chromium.connect_over_cdp(sb.browser_connect_url(country="de"))
    page = browser.contexts[0].pages[0]
    page.goto("https://example.com")
```

Or open one yourself and keep it: `s = sb.create_browser_session(country="us", engine="auto", site="hermes.com")`
gives `s["ws_url"]` for Playwright or Puppeteer and `s["live_url"]` for a person to watch or take over; end it with
`sb.end_browser_session(s["id"])`. `engine="auto"` picks the engine measured to pass the site. Saved profiles keep
cookies and logins between sessions: `create_browser_profile`, then `profile=` on a session.

## Errors and retries

A failed call raises a `SerpbitError`. The subclasses are:
- `BadRequestError` (400);
- `AuthenticationError` (401);
- `InsufficientCreditsError` (402: no credits, or for the browser `out_of_traffic`);
- `PermissionDeniedError` (403);
- `NotFoundError` (404);
- `UnprocessableEntityError` (422, such as a CAPTCHA call with no widget on the page);
- `RateLimitError` (429, with `retry_after`);
- `APIError` (5xx);
- `APIConnectionError`.

Each carries `status`, `code` and `request_id`. Quote the `request_id` to support.

Calls are retried twice on 429 and 5xx (set with `max_retries`), waiting as `Retry-After` says. Every attempt of one
call carries the same `Idempotency-Key`, so an answer lost on the way is given back free instead of being billed
twice. You can pass your own with `idempotency_key=`.

## Batches

```python
b = sb.batch([{"path": "/v1/search", "params": {"q": kw, "gl": "us"}, "id": kw} for kw in keywords],
             webhook="https://example.com/serpbit")
sb.get_batch(b["id"])                     # status, and each call's
sb.batch_results(b["id"], offset=0)       # the answers, 100 at a time, for a day after it ends

# In your webhook: check the event is Serpbit's before you trust it.
from serpbit import verify_webhook
ok = verify_webhook(request.body, request.headers["Serpbit-Signature"], api_key)
```
