|
| 1 | +from __future__ import annotations |
| 2 | +from typing import Iterator, Optional, Union, Mapping, Any |
| 3 | + |
| 4 | +from .schema.businesses import BusinessFilters, BusinessSearchResult |
| 5 | + |
| 6 | + |
| 7 | +FiltersLike = Union[BusinessFilters, Mapping[str, Any], None] |
| 8 | + |
| 9 | + |
| 10 | +class BusinessesAPI: |
| 11 | + def __init__(self, client: OutscraperClient) -> None: |
| 12 | + self._client = client |
| 13 | + |
| 14 | + def search(self, *, filters: FiltersLike = None, limit: int = 10, cursor: Optional[str] = None, include_total: bool = False, |
| 15 | + fields: Optional[list[str]] = None) -> BusinessSearchResult: |
| 16 | + ''' |
| 17 | + Retrieve business records with optional enrichment data. |
| 18 | +
|
| 19 | + This endpoint provides access to millions of business listings with support for |
| 20 | + pagination and selective data enrichment. Use `cursor` from the previous response |
| 21 | + to fetch the next page. |
| 22 | +
|
| 23 | + Parameters: |
| 24 | + filters (BusinessFilters | dict | None): Filtering criteria. You can pass either |
| 25 | + BusinessFilters (recommended) or a raw dict matching the API schema. |
| 26 | + limit (int): Maximum number of business records to return for this page. |
| 27 | + Default: 10. |
| 28 | + cursor (str | None): Cursor for pagination to retrieve the next set of results. |
| 29 | + Default: None. |
| 30 | + include_total (bool): Whether to include the total count of matching records in the response. This could increase response time. |
| 31 | + Default: False. |
| 32 | + fields (list[str] | None): List of fields to include in the response. If not specified, all fields will be returned. |
| 33 | +
|
| 34 | + Returns: |
| 35 | + BusinessSearchResult: Page of businesses with pagination info. |
| 36 | +
|
| 37 | + See: https://app.outscraper.com/api-docs |
| 38 | + ''' |
| 39 | + |
| 40 | + if limit < 1 or limit > 1000: |
| 41 | + raise ValueError('limit must be in range [1, 1000]') |
| 42 | + |
| 43 | + if filters is None: |
| 44 | + filters_payload = {} |
| 45 | + elif isinstance(filters, BusinessFilters): |
| 46 | + filters_payload = filters.to_payload() |
| 47 | + else: |
| 48 | + filters_payload = dict(filters) |
| 49 | + |
| 50 | + payload = { |
| 51 | + 'filters': filters_payload, |
| 52 | + 'limit': limit, |
| 53 | + 'cursor': cursor, |
| 54 | + 'include_total': include_total, |
| 55 | + } |
| 56 | + if fields: |
| 57 | + payload['fields'] = list(fields) |
| 58 | + |
| 59 | + response = self._client._request('POST', '/businesses', use_handle_response=False, json=payload) |
| 60 | + data = response.json() |
| 61 | + |
| 62 | + if data.get('error'): |
| 63 | + error_message = data.get('errorMessage') |
| 64 | + raise Exception(f'error: {error_message}') |
| 65 | + |
| 66 | + return BusinessSearchResult( |
| 67 | + items=data.get('items') or [], |
| 68 | + next_cursor=data.get('next_cursor'), |
| 69 | + has_more=bool(data.get('has_more')) or bool(data.get('next_cursor')), |
| 70 | + ) |
| 71 | + |
| 72 | + def iter_search(self, *, filters: FiltersLike = None, limit: int = 10, start_cursor: Optional[str] = None, |
| 73 | + include_total: bool = False, fields: Optional[list[str]] = None) -> Iterator[dict]: |
| 74 | + ''' |
| 75 | + Iterate over businesses across all pages (auto-pagination). |
| 76 | +
|
| 77 | + This is a convenience generator over `search()`: |
| 78 | + - calls search() |
| 79 | + - yields each Business from the returned page |
| 80 | + - continues while next_cursor/has_more indicates more pages |
| 81 | +
|
| 82 | + Parameters: |
| 83 | + filters (BusinessFilters | dict | None): Same as `search()`. |
| 84 | + limit (int): Page size per request. Default: 10. |
| 85 | + start_cursor (str | None): If provided, iteration starts from this cursor. |
| 86 | + Default: None (start from first page). |
| 87 | + include_total (bool): Passed to `search()` (if supported by API). |
| 88 | + Default: False. |
| 89 | + fields (list[str] | None): Passed to `search()`. |
| 90 | +
|
| 91 | + Yields: |
| 92 | + item (dict): Each business record from all pages. |
| 93 | +
|
| 94 | + See: https://app.outscraper.com/api-docs |
| 95 | + ''' |
| 96 | + |
| 97 | + cursor = start_cursor |
| 98 | + |
| 99 | + while True: |
| 100 | + business_search_result = self.search(filters=filters, |
| 101 | + limit=limit, |
| 102 | + cursor=cursor, |
| 103 | + include_total=include_total, |
| 104 | + fields=fields) |
| 105 | + |
| 106 | + for item in business_search_result.items: |
| 107 | + yield item |
| 108 | + if not business_search_result.next_cursor and not business_search_result.has_more: |
| 109 | + break |
| 110 | + |
| 111 | + cursor = business_search_result.next_cursor |
| 112 | + |
| 113 | + def get(self, business_id: str, *, fields: Optional[list[str]] = None) -> dict: |
| 114 | + ''' |
| 115 | + Get Business Details |
| 116 | +
|
| 117 | + Retrieves detailed information for a specific business by business_id. |
| 118 | + According to the API docs, business_id can be: |
| 119 | + - os_id |
| 120 | + - place_id |
| 121 | + - google_id |
| 122 | +
|
| 123 | + Parameters: |
| 124 | + business_id (str): Business identifier (os_id, place_id, or google_id). |
| 125 | + fields (list[str] | None): List of fields to include in the response. |
| 126 | + If not provided, API returns all fields. |
| 127 | +
|
| 128 | + Returns: |
| 129 | + data (dict): business with full details. |
| 130 | +
|
| 131 | + See: https://app.outscraper.com/api-docs |
| 132 | + ''' |
| 133 | + |
| 134 | + params = None |
| 135 | + if fields: |
| 136 | + params = {'fields': ','.join(fields)} |
| 137 | + |
| 138 | + resp = self._client._request('GET', f'/businesses/{business_id}', use_handle_response=False, params=params) |
| 139 | + data = resp.json() |
| 140 | + if data.get('error'): |
| 141 | + error_message = data.get('errorMessage') |
| 142 | + raise Exception(f'error: {error_message}') |
| 143 | + |
| 144 | + if not isinstance(data, dict): |
| 145 | + raise Exception(f'Unexpected response for /businesses/{business_id}: {type(data)}') |
| 146 | + |
| 147 | + return data |
0 commit comments