Skip to content

client

Class info

Classes

Name Children Inherits
AsyncSerpAPIClient
searchly.providers.serpapi_provider.client
Async client for SerpAPI.

    🛈 DocStrings

    SerpAPI client implementing search protocols.

    AsyncSerpAPIClient

    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])
    

    example async

    example() -> None
    

    Example usage of AsyncSerpAPIClient.

    Source code in src/searchly/providers/serpapi_provider/client.py
    async def example() -> None:
        """Example usage of AsyncSerpAPIClient."""
        client = AsyncSerpAPIClient()
    
        web_results = await client.web_search("Python programming", max_results=5, language="en")
        print(f"Web results: {len(web_results.results)}")
        for result in web_results.results:
            print(f"  - {result.title}: {result.url}")
    
        news_results = await client.news_search("Python programming", max_results=5, time_period="d")
        print(f"News results: {len(news_results.results)}")