Skip to content

Add static typing support via optional extra - #51

Open
adarshdigievo wants to merge 6 commits into
masterfrom
adarshdigievo-serpapi-stub-packaging
Open

adarshdigievo wants to merge 6 commits into
masterfrom
adarshdigievo-serpapi-stub-packaging

Conversation

@adarshdigievo

@adarshdigievo adarshdigievo commented Nov 16, 2026 •

Copy link
Copy Markdown
Member

Summary

Add serpapi-stubs, a separately published package that gives editors, mypy, and pyright engine-specific parameter and return types for 164 SerpApi engines. It covers both Client and AsyncClient.

This change does not affect the main serpapi library. It adds a new dedicate type stub package for static type checkers, installable as an extra.

A weekly workflow checks the SerpApi Playground for changes and opens or updates a refresh PR when the generated files differ. Stub updates can ship between SDK releases.

Type

  • Bug fix
  • Feature
  • Refactor / performance
  • Documentation / examples
  • Tests
  • Maintenance / packaging / CI

Related issue

No separate tracking issue. This is an alternative to #34: the stubs are built from this repository but distributed separately from the runtime SDK.

Affected SDK functionality

  • serpapi package version (if known): 1.3.0; matching stub series 1.3.0.*.
  • Python version and operating system: Python 3.13.12 on macOS locally; Ubuntu on GitHub Actions.
  • SDK methods or helpers affected: Type information for module-level helpers, Client, AsyncClient, search, extract, archive, uploads, locations, account, and pagination. JSON searches return result objects; HTML and Markdown searches return str. Async calls preserve that distinction after await.
  • SerpApi engine or endpoint involved (if applicable): All 164 engines in the checked-in Playground snapshot, plus the Search Archive. Keyword calls and explicitly typed parameter dictionaries get field-level checks; plain dictionaries remain supported for dynamic parameters.
  • Other affected Python versions or environments (confirmed or suspected): The SDK CI matrix covers Python 3.8–3.15. The optional async transport requires Python 3.11+ and is not installed by the typing extra alone.

Testing

  • Human testing: Tested on VSCode and Pycharm with eight scripts covering 50 engines using keyword arguments, typed dictionaries, and async calls.
Screenshot 2026-11-26 at 11 37 46 PM
  • AI-executed testing:
    • python -m pytest -q -p no:cacheprovider -o addopts= stubs/tests tests/test_typing_extra.py tests/test_async_client.py tests/test_exceptions.py — 247 passed.
    • python -B stubs/tools/generate_stubs.py --check — generated files are up to date.
    • Built fresh SDK and stub wheels from bd5f459 and installed them outside the checkout. Across all 164 engines, mypy 2.4.1 and pyright 1.1.414 each accepted 1,414 valid examples and rejected 604 invalid examples on the intended lines. Removing only serpapi-stubs made both checkers stop catching the same misspelled keyword.
    • In the standalone IDE project, both checkers flagged exactly the 50 intentionally invalid lines and none of the 50 valid examples. Mocked HTTP responses separately confirmed JSON, HTML, Markdown, and pagination behavior without live API calls.

AI disclosure

  • Model(s): Claude Fable 5.2 (xhigh) and Copilot Fusion Max for implementation. Review and validation also used Claude Opus 5.5, Gemini 4 Carbon and Neon, GPT-6.1 Sol, and GPT-6.2 Astra (extra high efforts).

  • Harness/app(s) (e.g., Codex, Claude Code, Cursor): GitHub Copilot Desktop, Copilot subagents, Claude Code.

  • Used for (e.g., coding, tests, review, documentation): Implementation, documentation, independent review, and test execution. Fable 5.2 Max and Gemini Neon Max independently reviewed the full change before the final fixes.

Evidence

The script below shows warnings on IDEs and on type checkers like Mypy.

from typing import assert_type
from serpapi import AsyncClient, Client, SerpResults

def sync_example(client: Client) -> None:
    assert_type(client.search(engine="google", q="coffee", device="mobile"), SerpResults)
    assert_type(client.search(engine="bing", q="coffee", output="html"), str)
    client.search(engine="google", q="coffee", device="watch")  # type error

async def async_example(client: AsyncClient) -> None:
    results = await client.search(engine="google", q="coffee")
    async for page in results.yield_pages(max_pages=2):
        print(page.as_dict())

adarshdigievo and others added 6 commits November 16, 2026 09:04
Adds serpapi-stubs, a separate type-stub package built from stubs/ and
installed with the serpapi[typing] extra. Engine parameter types are
generated from the SerpApi Playground, with workflows to check, refresh
and release the stubs.

Co-authored-by: Copilot App <[email protected]>
ubuntu-latest is now Ubuntu 26.04, where actions/setup-python has no Python 3.8 or 3.9. uv downloads its own builds of every version in the matrix.

Co-authored-by: Copilot App <[email protected]>
Skip an older stub release only when a newer compatible stub snapshot has its own release run, so a multi-commit push no longer drops or duplicates a release. Keep a refresh branch that has a maintainer commit anywhere in its history. Require a mutable mapping for proxies, which requests updates in place.

Co-authored-by: Copilot App <[email protected]>
Type a Playground choice list as str when an example list in its description mixes options with other values, as Walmart's sort does with new. Accept output="json_with_pixel_position" for google, google_ads and the Search Archive, where SerpApi documents it.

Co-authored-by: Copilot App <[email protected]>
@adarshdigievo
adarshdigievo marked this pull request as ready for review November 26, 2026 18:20
Copilot AI balanced review requested due to automatic review settings November 26, 2026 18:20

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Unresolved version-ordering defects can prevent upgrades from selecting the fix, while pagination and format-override annotations misrepresent runtime return types.

3 open issues
What changed in this PR

Adds a separately published serpapi-stubs package for engine-specific typing across synchronous and asynchronous SDK APIs, without changing runtime behavior.

Changes:

  • Adds stub packaging, generation tools, and an optional typing extra.
  • Introduces type-checking tests and workflows for validation, weekly refreshes, and independent stub releases.
  • Documents installation, typed usage, and release procedures, and adjusts examples for compatibility.
File Description
tests/​test_typing_extra.py Checks that the stub pin matches the SDK version.
stubs/​tools/​release_version.py Computes stub versions and checks published releases.
stubs/​tools/​generate_stubs.py Generates engine parameter types and API overloads.
stubs/​tools/​fetch_engines.py Fetches and normalizes Playground metadata.
stubs/​tests/​typecheck/​check_usage.py Checks valid synchronous calls and inferred types.
stubs/​tests/​typecheck/​check_errors.py Checks rejection of invalid calls.
stubs/​tests/​typecheck/​check_async.py Checks asynchronous APIs and transport types.
stubs/​tests/​test_release_version.py Tests versioning and publication checks.
stubs/​tests/​test_packaging.py Tests packaging and workflow safeguards.
stubs/​tests/​test_generate_stubs.py Tests generated signatures and freshness.
stubs/​tests/​test_fetch_engines.py Tests metadata extraction and normalization.
stubs/​tests/​stubtest_allowlist.txt Allows the typing-only parameter module.
stubs/​tests/​conftest.py Makes tooling modules available to tests.
stubs/​serpapi-stubs/​utils.pyi Types the environment API-key helper.
stubs/​serpapi-stubs/​textui.pyi Types JSON formatting utilities.
stubs/​serpapi-stubs/​models.pyi Types result objects and pagination.
stubs/​serpapi-stubs/​http.pyi Types clients and transport options.
stubs/​serpapi-stubs/​exceptions.pyi Types SDK exceptions.
stubs/​serpapi-stubs/​__version__.pyi Declares the SDK version type.
stubs/​serpapi-stubs/​__init__.pyi Exposes typed public SDK exports.
stubs/​README.md Documents stub installation, usage, and limitations.
stubs/​pyproject.toml Configures packaging and type checkers.
stubs/​MANIFEST.in Controls source distribution contents.
stubs/​LICENSE Includes the SDK’s MIT license.
stubs/​.gitignore Excludes generated version and build artifacts.
README.md Adds typing installation guidance.
pyproject.toml Adds the version-matched typing extra.
docs/​user_guide/​async-search-archive.md Passes the reserved async parameter through a dictionary.
docs/​examples/​google-play-store-apps.md Uses a dictionary for dynamic search parameters.
docs/​examples/​google-lens-image-upload.md Removes the product-search suggestion from prose.
docs/​examples/​google-images-search.md Uses a dictionary for image-search parameters.
CONTRIBUTING.md Documents stub checks, refreshes, releases, and hotfixes.
.github/​workflows/​stubs.yml Validates generated and installed stubs.
.github/​workflows/​stubs-release.yml Publishes compatible stub-only updates.
.github/​workflows/​stubs-refresh.yml Opens or updates weekly metadata refresh PRs.
.github/​workflows/​stubs-build.yml Builds versioned stub distributions.
.github/​workflows/​release.yml Publishes matching stubs before SDK releases.

Review effort: Balanced

Comment on lines +34 to +39
def next_page(self) -> Optional[SerpResults]: ...
def yield_pages(self, max_pages: int = 1000) -> Iterator[SerpResults]: ...

class AsyncSerpResults(_BaseSerpResults[AsyncHTTPClient]):
async def next_page(self) -> Optional[AsyncSerpResults]: ...
def yield_pages(self, max_pages: int = 1000) -> AsyncGenerator[AsyncSerpResults, None]: ...
if not engine.engine_required:
lines.extend(keyword_overloads("search", surface, list(engine.params), engine.json_output))
# The engine in an untyped mapping is unknown, so the fallback takes every JSON output value.
params_type = surface.mapping if surface == ASYNC_CLIENT else f"Union[SearchParams, {surface.mapping}]"
Comment on lines +39 to +46
published = set(existing)
base = f"{sdk_version}.{date:%Y%m%d}"
if base not in published:
return base
serial = 1
while f"{base}.{serial}" in published:
serial += 1
return f"{base}.{serial}"

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants