Skip to content

AsyncSerpAPIClient

Base classes

Name Children Inherits
HttpSessionMixin
searchly.http
Gives a provider one `anyenv.HttpSession`, opened on first use.
WebSearchProvider
searchly.base
Protocol for web search providers.
NewsSearchProvider
searchly.base
Protocol for news search providers.

â‹” Inheritance diagram

graph TD
  580396526["client.AsyncSerpAPIClient"]
  1226828128["http.HttpSessionMixin"]
  2751680898["builtins.object"]
  4037333726["base.WebSearchProvider"]
  1073422405["typing.Protocol"]
  3481597255["typing.Generic"]
  2831882376["base.NewsSearchProvider"]
  1226828128 --> 580396526
  2751680898 --> 1226828128
  4037333726 --> 580396526
  1073422405 --> 4037333726
  3481597255 --> 1073422405
  2751680898 --> 3481597255
  2831882376 --> 580396526
  1073422405 --> 2831882376

🛈 DocStrings

Bases: HttpSessionMixin, WebSearchProvider, NewsSearchProvider

Async client for SerpAPI.

Source code in src/searchly/providers/serpapi_provider/client.py
class AsyncSerpAPIClient(HttpSessionMixin, WebSearchProvider, NewsSearchProvider):
    """Async client for SerpAPI."""

    BACKEND = "https://serpapi.com"

    def __init__(self, *, api_key: str | None = None):
        """Initialize SerpAPI client.

        Args:
            api_key: SerpAPI key. Defaults to SERPAPI_KEY env var.
        """
        self.api_key = api_key or os.getenv("SERPAPI_KEY")
        if not self.api_key:
            msg = "No API key provided. Set SERPAPI_KEY env var or pass api_key"
            raise ValueError(msg)

    async def web_search(
        self,
        query: str,
        *,
        max_results: int = 10,
        country: CountryCode | None = None,
        language: LanguageCode | None = None,
        location: str | None = None,
        safe: bool = True,
        **kwargs: Any,
    ) -> WebSearchResponse:
        """Execute a web search query.

        Args:
            query: Search query string.
            max_results: Maximum number of results to return.
            country: Country code for regional results (converted to lowercase).
            language: Language code for results (converted to lowercase).
            location: Location string (e.g. "Austin, Texas").
            safe: Enable safe search.
            **kwargs: Additional SerpAPI-specific options.

        Returns:
            Unified web search response.
        """
        params: dict[str, Any] = {
            "q": query,
            "num": max_results,
            "engine": "google",
            "api_key": self.api_key,
            "output": "json",
            "source": "python",
            **kwargs,
        }

        if country:
            params["gl"] = country.lower()
        if language:
            params["hl"] = language.lower()
        if location:
            params["location"] = location
        if safe:
            params["safe"] = "active"

        session = await self._session()
        response = await session.get_json(f"{self.BACKEND}/search", params=params, return_type=dict)

        results = [
            WebSearchResult(
                title=item.get("title", ""),
                url=item.get("link", ""),
                snippet=item.get("snippet", ""),
            )
            for item in response.get("organic_results", [])
        ]
        return WebSearchResponse(results=results[:max_results])

    async def news_search(
        self,
        query: str,
        *,
        max_results: int = 10,
        country: CountryCode | None = None,
        language: LanguageCode | None = None,
        location: str | None = None,
        safe: bool = True,
        time_period: TimePeriod | None = None,
        **kwargs: Any,
    ) -> NewsSearchResponse:
        """Execute a news search query.

        Args:
            query: Search query string.
            max_results: Maximum number of results to return.
            country: Country code for regional results (converted to lowercase).
            language: Language code for results (converted to lowercase).
            location: Location string (e.g. "Austin, Texas").
            safe: Enable safe search.
            time_period: Time period filter ("d"=day, "w"=week, "m"=month, "y"=year).
            **kwargs: Additional SerpAPI-specific options.

        Returns:
            Unified news search response.
        """
        params: dict[str, Any] = {
            "q": query,
            "tbm": "nws",
            "num": max_results,
            "engine": "google",
            "api_key": self.api_key,
            "output": "json",
            "source": "python",
            **kwargs,
        }

        if country:
            params["gl"] = country.lower()
        if language:
            params["hl"] = language.lower()
        if location:
            params["location"] = location
        if safe:
            params["safe"] = "active"
        if time_period:
            params["tbs"] = f"qdr:{time_period}"

        session = await self._session()
        response = await session.get_json(f"{self.BACKEND}/search", params=params, return_type=dict)

        results = [
            NewsSearchResult(
                title=item.get("title", ""),
                url=item.get("link", ""),
                snippet=item.get("snippet", ""),
                source=item.get("source"),
                published=item.get("date"),
            )
            for item in response.get("news_results", [])
        ]
        return NewsSearchResponse(results=results[:max_results])

__init__

__init__(*, api_key: str | None = None)

Initialize SerpAPI client.

Parameters:

Name Type Description Default
api_key str | None

SerpAPI key. Defaults to SERPAPI_KEY env var.

None
Source code in src/searchly/providers/serpapi_provider/client.py
def __init__(self, *, api_key: str | None = None):
    """Initialize SerpAPI client.

    Args:
        api_key: SerpAPI key. Defaults to SERPAPI_KEY env var.
    """
    self.api_key = api_key or os.getenv("SERPAPI_KEY")
    if not self.api_key:
        msg = "No API key provided. Set SERPAPI_KEY env var or pass api_key"
        raise ValueError(msg)
news_search(
    query: str,
    *,
    max_results: int = 10,
    country: CountryCode | None = None,
    language: LanguageCode | None = None,
    location: str | None = None,
    safe: bool = True,
    time_period: TimePeriod | None = None,
    **kwargs: Any,
) -> NewsSearchResponse

Execute a news search query.

Parameters:

Name Type Description Default
query str

Search query string.

required
max_results int

Maximum number of results to return.

10
country CountryCode | None

Country code for regional results (converted to lowercase).

None
language LanguageCode | None

Language code for results (converted to lowercase).

None
location str | None

Location string (e.g. "Austin, Texas").

None
safe bool

Enable safe search.

True
time_period TimePeriod | None

Time period filter ("d"=day, "w"=week, "m"=month, "y"=year).

None
**kwargs Any

Additional SerpAPI-specific options.

{}

Returns:

Type Description
NewsSearchResponse

Unified news search response.

Source code in src/searchly/providers/serpapi_provider/client.py
async def news_search(
    self,
    query: str,
    *,
    max_results: int = 10,
    country: CountryCode | None = None,
    language: LanguageCode | None = None,
    location: str | None = None,
    safe: bool = True,
    time_period: TimePeriod | None = None,
    **kwargs: Any,
) -> NewsSearchResponse:
    """Execute a news search query.

    Args:
        query: Search query string.
        max_results: Maximum number of results to return.
        country: Country code for regional results (converted to lowercase).
        language: Language code for results (converted to lowercase).
        location: Location string (e.g. "Austin, Texas").
        safe: Enable safe search.
        time_period: Time period filter ("d"=day, "w"=week, "m"=month, "y"=year).
        **kwargs: Additional SerpAPI-specific options.

    Returns:
        Unified news search response.
    """
    params: dict[str, Any] = {
        "q": query,
        "tbm": "nws",
        "num": max_results,
        "engine": "google",
        "api_key": self.api_key,
        "output": "json",
        "source": "python",
        **kwargs,
    }

    if country:
        params["gl"] = country.lower()
    if language:
        params["hl"] = language.lower()
    if location:
        params["location"] = location
    if safe:
        params["safe"] = "active"
    if time_period:
        params["tbs"] = f"qdr:{time_period}"

    session = await self._session()
    response = await session.get_json(f"{self.BACKEND}/search", params=params, return_type=dict)

    results = [
        NewsSearchResult(
            title=item.get("title", ""),
            url=item.get("link", ""),
            snippet=item.get("snippet", ""),
            source=item.get("source"),
            published=item.get("date"),
        )
        for item in response.get("news_results", [])
    ]
    return NewsSearchResponse(results=results[:max_results])
web_search(
    query: str,
    *,
    max_results: int = 10,
    country: CountryCode | None = None,
    language: LanguageCode | None = None,
    location: str | None = None,
    safe: bool = True,
    **kwargs: Any,
) -> WebSearchResponse

Execute a web search query.

Parameters:

Name Type Description Default
query str

Search query string.

required
max_results int

Maximum number of results to return.

10
country CountryCode | None

Country code for regional results (converted to lowercase).

None
language LanguageCode | None

Language code for results (converted to lowercase).

None
location str | None

Location string (e.g. "Austin, Texas").

None
safe bool

Enable safe search.

True
**kwargs Any

Additional SerpAPI-specific options.

{}

Returns:

Type Description
WebSearchResponse

Unified web search response.

Source code in src/searchly/providers/serpapi_provider/client.py
async def web_search(
    self,
    query: str,
    *,
    max_results: int = 10,
    country: CountryCode | None = None,
    language: LanguageCode | None = None,
    location: str | None = None,
    safe: bool = True,
    **kwargs: Any,
) -> WebSearchResponse:
    """Execute a web search query.

    Args:
        query: Search query string.
        max_results: Maximum number of results to return.
        country: Country code for regional results (converted to lowercase).
        language: Language code for results (converted to lowercase).
        location: Location string (e.g. "Austin, Texas").
        safe: Enable safe search.
        **kwargs: Additional SerpAPI-specific options.

    Returns:
        Unified web search response.
    """
    params: dict[str, Any] = {
        "q": query,
        "num": max_results,
        "engine": "google",
        "api_key": self.api_key,
        "output": "json",
        "source": "python",
        **kwargs,
    }

    if country:
        params["gl"] = country.lower()
    if language:
        params["hl"] = language.lower()
    if location:
        params["location"] = location
    if safe:
        params["safe"] = "active"

    session = await self._session()
    response = await session.get_json(f"{self.BACKEND}/search", params=params, return_type=dict)

    results = [
        WebSearchResult(
            title=item.get("title", ""),
            url=item.get("link", ""),
            snippet=item.get("snippet", ""),
        )
        for item in response.get("organic_results", [])
    ]
    return WebSearchResponse(results=results[:max_results])

:fa-brands-github: Show source on GitHub