google-images-api 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,37 @@
1
+ name: Test and publish
2
+
3
+ on:
4
+ push:
5
+ branches: [main]
6
+ pull_request:
7
+ release:
8
+ types: [published]
9
+
10
+ jobs:
11
+ test:
12
+ runs-on: ubuntu-latest
13
+ strategy:
14
+ matrix:
15
+ python-version: ["3.10", "3.12", "3.13"]
16
+ steps:
17
+ - uses: actions/checkout@v4
18
+ - uses: actions/setup-python@v5
19
+ with:
20
+ python-version: ${{ matrix.python-version }}
21
+ - run: pip install -e ".[dev]"
22
+ - run: pytest
23
+
24
+ publish:
25
+ if: github.event_name == 'release'
26
+ needs: test
27
+ runs-on: ubuntu-latest
28
+ environment: pypi
29
+ permissions:
30
+ id-token: write # PyPI Trusted Publishing, no API token needed
31
+ steps:
32
+ - uses: actions/checkout@v4
33
+ - uses: actions/setup-python@v5
34
+ with:
35
+ python-version: "3.12"
36
+ - run: pip install build && python -m build
37
+ - uses: pypa/gh-action-pypi-publish@release/v1
@@ -0,0 +1,8 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ dist/
4
+ build/
5
+ *.egg-info/
6
+ .pytest_cache/
7
+ .venv/
8
+ .env
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 cognifyapi
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,167 @@
1
+ Metadata-Version: 2.5
2
+ Name: google-images-api
3
+ Version: 0.1.0
4
+ Summary: Python client for the CognifyAPI Google Images API: search Google Images and get image URLs, sizes and MIME types as JSON.
5
+ Project-URL: Homepage, https://cognifyapi.com/google-images
6
+ Project-URL: Documentation, https://cognifyapi.com/docs/google-images-docs
7
+ Project-URL: Source, https://github.com/cognifyapi/google-images-api
8
+ Project-URL: Issues, https://github.com/cognifyapi/google-images-api/issues
9
+ Author-email: CognifyAPI <support@cognifyapi.com>
10
+ License-Expression: MIT
11
+ License-File: LICENSE
12
+ Keywords: cognifyapi,google image search,google images api,image scraper,image search api,serp api,web scraping
13
+ Classifier: Development Status :: 4 - Beta
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3 :: Only
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Programming Language :: Python :: 3.13
22
+ Classifier: Topic :: Internet :: WWW/HTTP :: Indexing/Search
23
+ Classifier: Topic :: Multimedia :: Graphics
24
+ Classifier: Typing :: Typed
25
+ Requires-Python: >=3.10
26
+ Requires-Dist: requests>=2.28
27
+ Provides-Extra: dev
28
+ Requires-Dist: build; extra == 'dev'
29
+ Requires-Dist: pytest>=7; extra == 'dev'
30
+ Requires-Dist: twine; extra == 'dev'
31
+ Description-Content-Type: text/markdown
32
+
33
+ # google-images-api by cognifyapi
34
+
35
+ A small Python client for the [CognifyAPI Google Images API](https://cognifyapi.com/google-images).
36
+ Search Google Images and get structured JSON back: image URLs, plus width, height and MIME type with JSON results.
37
+
38
+ **[Get an API key (free trial)](https://studio.cognifyapi.com/)**
39
+
40
+ ## Install
41
+
42
+ ```bash
43
+ pip install google-images-api
44
+ ```
45
+
46
+ Requires Python 3.10 or newer.
47
+
48
+ ## Quickstart
49
+
50
+ ```python
51
+ from google_images_api import GoogleImagesAPI
52
+
53
+ client = GoogleImagesAPI(api_key="YOUR_COGNIFY_API_KEY")
54
+ result = client.search("electric cars", count=10)
55
+
56
+ for image in result:
57
+ print(image.url)
58
+ ```
59
+
60
+ You can also set the key once in your environment and omit `api_key`:
61
+
62
+ ```bash
63
+ export COGNIFY_API_KEY="YOUR_COGNIFY_API_KEY"
64
+ ```
65
+
66
+ ## Usage
67
+
68
+ ### Image metadata
69
+
70
+ ```python
71
+ result = client.search("SpaceX", count=5, image_info=True)
72
+
73
+ for image in result:
74
+ print(image.url, image.width, image.height, image.type, image.mime)
75
+ ```
76
+
77
+ Without `image_info=True`, only `image.url` is filled in.
78
+
79
+ ### Just the URLs
80
+
81
+ ```python
82
+ urls = client.search("tesla", count=20).urls
83
+ ```
84
+
85
+ ### Download images
86
+
87
+ ```python
88
+ for image in client.search("northern lights", count=3):
89
+ path = client.download(image, directory="images")
90
+ print("saved", path)
91
+ ```
92
+
93
+ ### Raw JSON
94
+
95
+ ```python
96
+ result.raw # the full API response as a dict
97
+ result.status # "success"
98
+ ```
99
+
100
+ ### Use as a context manager
101
+
102
+ ```python
103
+ with GoogleImagesAPI() as client:
104
+ print(client.search("sunset").urls)
105
+ ```
106
+
107
+ ### Error handling
108
+
109
+ ```python
110
+ from google_images_api import AuthenticationError, RateLimitError, APIError, GoogleImagesAPIError
111
+
112
+ try:
113
+ client.search("cats")
114
+ except AuthenticationError:
115
+ ... # bad or missing API key
116
+ except RateLimitError:
117
+ ... # too many requests or quota used up
118
+ except APIError as exc:
119
+ print(exc.status_code, exc)
120
+ except GoogleImagesAPIError:
121
+ ... # network problem or any other library error
122
+ ```
123
+
124
+ ## Command line
125
+
126
+ ```bash
127
+ google-images-api "electric cars" -n 10 # print image URLs
128
+ google-images-api "SpaceX" -n 5 --info # with width, height and MIME type
129
+ google-images-api "tesla" -n 5 --download ./images # save the files
130
+ google-images-api "tesla" --json # raw JSON
131
+ ```
132
+
133
+ ## API reference
134
+
135
+ `GoogleImagesAPI(api_key=None, base_url="https://api.cognifyapi.com", timeout=30.0)`
136
+
137
+ `client.search(query, count=None, image_info=False) -> SearchResult`
138
+
139
+ | Parameter | Required | Description |
140
+ | ------------ | -------- | -------------------------------------------------------- |
141
+ | `query` | yes | Search keyword, for example `"SpaceX"`. |
142
+ | `count` | no | Number of results (API default: 100). |
143
+ | `image_info` | no | Also return width, height, type and MIME type. |
144
+
145
+ Example API response:
146
+
147
+ ```json
148
+ {
149
+ "status": "success",
150
+ "query": "SpaceX",
151
+ "results": 2,
152
+ "images": [
153
+ { "url": "https://example.com/image.jpg", "width": 1920, "height": 1080, "type": "jpg", "mime": "image/jpg" }
154
+ ]
155
+ }
156
+ ```
157
+
158
+ ## Links
159
+
160
+ - [API documentation](https://cognifyapi.com/docs/google-images-docs)
161
+ - [Google Images API](https://cognifyapi.com/google-images)
162
+ - [CognifyAPI](https://cognifyapi.com/)
163
+ - [Report an issue](https://github.com/cognifyapi/google-images-api/issues)
164
+
165
+ ## License
166
+
167
+ MIT. See [LICENSE](LICENSE).
@@ -0,0 +1,135 @@
1
+ # google-images-api by cognifyapi
2
+
3
+ A small Python client for the [CognifyAPI Google Images API](https://cognifyapi.com/google-images).
4
+ Search Google Images and get structured JSON back: image URLs, plus width, height and MIME type with JSON results.
5
+
6
+ **[Get an API key (free trial)](https://studio.cognifyapi.com/)**
7
+
8
+ ## Install
9
+
10
+ ```bash
11
+ pip install google-images-api
12
+ ```
13
+
14
+ Requires Python 3.10 or newer.
15
+
16
+ ## Quickstart
17
+
18
+ ```python
19
+ from google_images_api import GoogleImagesAPI
20
+
21
+ client = GoogleImagesAPI(api_key="YOUR_COGNIFY_API_KEY")
22
+ result = client.search("electric cars", count=10)
23
+
24
+ for image in result:
25
+ print(image.url)
26
+ ```
27
+
28
+ You can also set the key once in your environment and omit `api_key`:
29
+
30
+ ```bash
31
+ export COGNIFY_API_KEY="YOUR_COGNIFY_API_KEY"
32
+ ```
33
+
34
+ ## Usage
35
+
36
+ ### Image metadata
37
+
38
+ ```python
39
+ result = client.search("SpaceX", count=5, image_info=True)
40
+
41
+ for image in result:
42
+ print(image.url, image.width, image.height, image.type, image.mime)
43
+ ```
44
+
45
+ Without `image_info=True`, only `image.url` is filled in.
46
+
47
+ ### Just the URLs
48
+
49
+ ```python
50
+ urls = client.search("tesla", count=20).urls
51
+ ```
52
+
53
+ ### Download images
54
+
55
+ ```python
56
+ for image in client.search("northern lights", count=3):
57
+ path = client.download(image, directory="images")
58
+ print("saved", path)
59
+ ```
60
+
61
+ ### Raw JSON
62
+
63
+ ```python
64
+ result.raw # the full API response as a dict
65
+ result.status # "success"
66
+ ```
67
+
68
+ ### Use as a context manager
69
+
70
+ ```python
71
+ with GoogleImagesAPI() as client:
72
+ print(client.search("sunset").urls)
73
+ ```
74
+
75
+ ### Error handling
76
+
77
+ ```python
78
+ from google_images_api import AuthenticationError, RateLimitError, APIError, GoogleImagesAPIError
79
+
80
+ try:
81
+ client.search("cats")
82
+ except AuthenticationError:
83
+ ... # bad or missing API key
84
+ except RateLimitError:
85
+ ... # too many requests or quota used up
86
+ except APIError as exc:
87
+ print(exc.status_code, exc)
88
+ except GoogleImagesAPIError:
89
+ ... # network problem or any other library error
90
+ ```
91
+
92
+ ## Command line
93
+
94
+ ```bash
95
+ google-images-api "electric cars" -n 10 # print image URLs
96
+ google-images-api "SpaceX" -n 5 --info # with width, height and MIME type
97
+ google-images-api "tesla" -n 5 --download ./images # save the files
98
+ google-images-api "tesla" --json # raw JSON
99
+ ```
100
+
101
+ ## API reference
102
+
103
+ `GoogleImagesAPI(api_key=None, base_url="https://api.cognifyapi.com", timeout=30.0)`
104
+
105
+ `client.search(query, count=None, image_info=False) -> SearchResult`
106
+
107
+ | Parameter | Required | Description |
108
+ | ------------ | -------- | -------------------------------------------------------- |
109
+ | `query` | yes | Search keyword, for example `"SpaceX"`. |
110
+ | `count` | no | Number of results (API default: 100). |
111
+ | `image_info` | no | Also return width, height, type and MIME type. |
112
+
113
+ Example API response:
114
+
115
+ ```json
116
+ {
117
+ "status": "success",
118
+ "query": "SpaceX",
119
+ "results": 2,
120
+ "images": [
121
+ { "url": "https://example.com/image.jpg", "width": 1920, "height": 1080, "type": "jpg", "mime": "image/jpg" }
122
+ ]
123
+ }
124
+ ```
125
+
126
+ ## Links
127
+
128
+ - [API documentation](https://cognifyapi.com/docs/google-images-docs)
129
+ - [Google Images API](https://cognifyapi.com/google-images)
130
+ - [CognifyAPI](https://cognifyapi.com/)
131
+ - [Report an issue](https://github.com/cognifyapi/google-images-api/issues)
132
+
133
+ ## License
134
+
135
+ MIT. See [LICENSE](LICENSE).
@@ -0,0 +1,58 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.18"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "google-images-api"
7
+ dynamic = ["version"]
8
+ description = "Python client for the CognifyAPI Google Images API: search Google Images and get image URLs, sizes and MIME types as JSON."
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = "MIT"
12
+ license-files = ["LICENSE"]
13
+ authors = [{ name = "CognifyAPI", email = "support@cognifyapi.com" }]
14
+ keywords = [
15
+ "google images api",
16
+ "google image search",
17
+ "image search api",
18
+ "image scraper",
19
+ "web scraping",
20
+ "serp api",
21
+ "cognifyapi",
22
+ ]
23
+ classifiers = [
24
+ "Development Status :: 4 - Beta",
25
+ "Intended Audience :: Developers",
26
+ "Operating System :: OS Independent",
27
+ "Programming Language :: Python :: 3",
28
+ "Programming Language :: Python :: 3 :: Only",
29
+ "Programming Language :: Python :: 3.10",
30
+ "Programming Language :: Python :: 3.11",
31
+ "Programming Language :: Python :: 3.12",
32
+ "Programming Language :: Python :: 3.13",
33
+ "Topic :: Internet :: WWW/HTTP :: Indexing/Search",
34
+ "Topic :: Multimedia :: Graphics",
35
+ "Typing :: Typed",
36
+ ]
37
+ dependencies = ["requests>=2.28"]
38
+
39
+ [project.optional-dependencies]
40
+ dev = ["pytest>=7", "build", "twine"]
41
+
42
+ [project.scripts]
43
+ google-images-api = "google_images_api.cli:main"
44
+
45
+ [project.urls]
46
+ Homepage = "https://cognifyapi.com/google-images"
47
+ Documentation = "https://cognifyapi.com/docs/google-images-docs"
48
+ Source = "https://github.com/cognifyapi/google-images-api"
49
+ Issues = "https://github.com/cognifyapi/google-images-api/issues"
50
+
51
+ [tool.hatch.version]
52
+ path = "src/google_images_api/__init__.py"
53
+
54
+ [tool.hatch.build.targets.wheel]
55
+ packages = ["src/google_images_api"]
56
+
57
+ [tool.pytest.ini_options]
58
+ testpaths = ["tests"]
@@ -0,0 +1,22 @@
1
+ """Python client for the CognifyAPI Google Images API."""
2
+
3
+ from .client import GoogleImagesAPI, Image, SearchResult
4
+ from .exceptions import (
5
+ APIError,
6
+ AuthenticationError,
7
+ GoogleImagesAPIError,
8
+ RateLimitError,
9
+ )
10
+
11
+ __version__ = "0.1.0"
12
+
13
+ __all__ = [
14
+ "GoogleImagesAPI",
15
+ "Image",
16
+ "SearchResult",
17
+ "GoogleImagesAPIError",
18
+ "APIError",
19
+ "AuthenticationError",
20
+ "RateLimitError",
21
+ "__version__",
22
+ ]
@@ -0,0 +1,60 @@
1
+ """Command line interface: ``google-images-api "electric cars" -n 10``."""
2
+
3
+ import argparse
4
+ import json
5
+ import sys
6
+ from typing import List, Optional
7
+
8
+ from . import __version__
9
+ from .client import GoogleImagesAPI
10
+ from .exceptions import GoogleImagesAPIError
11
+
12
+
13
+ def build_parser() -> argparse.ArgumentParser:
14
+ parser = argparse.ArgumentParser(
15
+ prog="google-images-api",
16
+ description="Search Google Images through the CognifyAPI.",
17
+ )
18
+ parser.add_argument("query", help="search keyword")
19
+ parser.add_argument("-n", "--count", type=int, help="number of results")
20
+ parser.add_argument(
21
+ "-i", "--info", action="store_true", help="include width, height and MIME type"
22
+ )
23
+ parser.add_argument(
24
+ "-d", "--download", metavar="DIR", help="download the images into DIR"
25
+ )
26
+ parser.add_argument("--json", action="store_true", help="print the raw JSON response")
27
+ parser.add_argument("--api-key", help="API key (default: $COGNIFY_API_KEY)")
28
+ parser.add_argument("--version", action="version", version=__version__)
29
+ return parser
30
+
31
+
32
+ def main(argv: Optional[List[str]] = None) -> int:
33
+ args = build_parser().parse_args(argv)
34
+ try:
35
+ with GoogleImagesAPI(api_key=args.api_key) as client:
36
+ result = client.search(args.query, count=args.count, image_info=args.info)
37
+ if args.json:
38
+ print(json.dumps(result.raw, indent=2))
39
+ else:
40
+ for image in result:
41
+ extra = (
42
+ f" {image.width}x{image.height} {image.mime}"
43
+ if image.width and image.height
44
+ else ""
45
+ )
46
+ print(f"{image.url}{extra}")
47
+ if args.download:
48
+ for image in result:
49
+ try:
50
+ print("saved", client.download(image, args.download), file=sys.stderr)
51
+ except GoogleImagesAPIError as exc:
52
+ print(f"skipped: {exc}", file=sys.stderr)
53
+ except (GoogleImagesAPIError, ValueError) as exc:
54
+ print(f"error: {exc}", file=sys.stderr)
55
+ return 1
56
+ return 0
57
+
58
+
59
+ if __name__ == "__main__":
60
+ sys.exit(main())
@@ -0,0 +1,218 @@
1
+ """HTTP client for the CognifyAPI Google Images endpoint."""
2
+
3
+ import os
4
+ import posixpath
5
+ from dataclasses import dataclass, field
6
+ from typing import Any, Dict, Iterator, List, Optional, Union
7
+ from urllib.parse import urlparse
8
+
9
+ import requests
10
+
11
+ from .exceptions import (
12
+ APIError,
13
+ AuthenticationError,
14
+ GoogleImagesAPIError,
15
+ RateLimitError,
16
+ )
17
+
18
+ DEFAULT_BASE_URL = "https://api.cognifyapi.com"
19
+ API_KEY_ENV_VAR = "COGNIFY_API_KEY"
20
+ _EXTENSIONS = {"jpeg": "jpg"}
21
+
22
+
23
+ @dataclass
24
+ class Image:
25
+ """A single image result.
26
+
27
+ ``width``, ``height``, ``type`` and ``mime`` are only filled in when the
28
+ search was made with ``image_info=True``.
29
+ """
30
+
31
+ url: str
32
+ width: Optional[int] = None
33
+ height: Optional[int] = None
34
+ type: Optional[str] = None
35
+ mime: Optional[str] = None
36
+
37
+ @classmethod
38
+ def from_api(cls, item: Any) -> "Image":
39
+ # Without imageInfo the API may return plain URL strings.
40
+ if isinstance(item, str):
41
+ return cls(url=item)
42
+ if isinstance(item, dict) and isinstance(item.get("url"), str):
43
+ return cls(
44
+ url=item["url"],
45
+ width=item.get("width"),
46
+ height=item.get("height"),
47
+ type=item.get("type"),
48
+ mime=item.get("mime"),
49
+ )
50
+ raise APIError("Unexpected image entry in API response.", payload=item)
51
+
52
+
53
+ @dataclass
54
+ class SearchResult:
55
+ """The parsed response of a search."""
56
+
57
+ query: str
58
+ images: List[Image] = field(default_factory=list)
59
+ status: Optional[str] = None
60
+ raw: Dict[str, Any] = field(default_factory=dict, repr=False)
61
+
62
+ def __iter__(self) -> Iterator[Image]:
63
+ return iter(self.images)
64
+
65
+ def __len__(self) -> int:
66
+ return len(self.images)
67
+
68
+ @property
69
+ def urls(self) -> List[str]:
70
+ return [image.url for image in self.images]
71
+
72
+
73
+ class GoogleImagesAPI:
74
+ """Client for ``GET /google-images``.
75
+
76
+ >>> client = GoogleImagesAPI(api_key="YOUR_COGNIFY_API_KEY")
77
+ >>> result = client.search("electric cars", count=10, image_info=True)
78
+ >>> result.urls[:1]
79
+
80
+ If ``api_key`` is omitted, the ``COGNIFY_API_KEY`` environment variable is used.
81
+ """
82
+
83
+ def __init__(
84
+ self,
85
+ api_key: Optional[str] = None,
86
+ base_url: str = DEFAULT_BASE_URL,
87
+ timeout: float = 30.0,
88
+ session: Optional[requests.Session] = None,
89
+ ) -> None:
90
+ api_key = api_key or os.environ.get(API_KEY_ENV_VAR)
91
+ if not api_key:
92
+ raise AuthenticationError(
93
+ "No API key. Pass api_key=... or set the "
94
+ f"{API_KEY_ENV_VAR} environment variable."
95
+ )
96
+ self.base_url = base_url.rstrip("/")
97
+ self.timeout = timeout
98
+ self._session = session or requests.Session()
99
+ self._session.headers.update({"x-cognifyapi-key": api_key})
100
+
101
+ def __enter__(self) -> "GoogleImagesAPI":
102
+ return self
103
+
104
+ def __exit__(self, *exc_info: Any) -> None:
105
+ self.close()
106
+
107
+ def close(self) -> None:
108
+ self._session.close()
109
+
110
+ def search(
111
+ self,
112
+ query: str,
113
+ count: Optional[int] = None,
114
+ image_info: bool = False,
115
+ ) -> SearchResult:
116
+ """Search Google Images.
117
+
118
+ :param query: Search keyword, for example ``"SpaceX"``.
119
+ :param count: Number of results. The API default is 100.
120
+ :param image_info: Also return width, height, type and MIME type.
121
+ """
122
+ if not query or not query.strip():
123
+ raise ValueError("query must be a non-empty string.")
124
+ if count is not None and count < 1:
125
+ raise ValueError("count must be a positive integer.")
126
+
127
+ params: Dict[str, Any] = {"query": query}
128
+ if count is not None:
129
+ params["count"] = count
130
+ if image_info:
131
+ params["imageInfo"] = "true"
132
+
133
+ data = self._get("/google-images", params)
134
+
135
+ images = data.get("images")
136
+ if not isinstance(images, list):
137
+ raise APIError(
138
+ "The API response did not contain an images array.",
139
+ payload=data,
140
+ )
141
+ return SearchResult(
142
+ query=data.get("query", query),
143
+ images=[Image.from_api(item) for item in images],
144
+ status=data.get("status"),
145
+ raw=data,
146
+ )
147
+
148
+ def download(
149
+ self,
150
+ image: Union[Image, str],
151
+ directory: str = ".",
152
+ filename: Optional[str] = None,
153
+ ) -> str:
154
+ """Download one image to ``directory`` and return the file path."""
155
+ url = image.url if isinstance(image, Image) else image
156
+ os.makedirs(directory, exist_ok=True)
157
+ if filename is None:
158
+ filename = posixpath.basename(urlparse(url).path) or "image"
159
+ if "." not in filename:
160
+ ext = _EXTENSIONS.get(
161
+ (image.type or "").lower(), (image.type or "jpg").lower()
162
+ ) if isinstance(image, Image) else "jpg"
163
+ filename = f"{filename}.{ext}"
164
+ path = os.path.join(directory, os.path.basename(filename))
165
+ try:
166
+ # Plain request: image hosts must not receive the API key header.
167
+ response = requests.get(url, timeout=self.timeout, stream=True)
168
+ response.raise_for_status()
169
+ with open(path, "wb") as handle:
170
+ for chunk in response.iter_content(chunk_size=65536):
171
+ handle.write(chunk)
172
+ except requests.RequestException as exc:
173
+ raise GoogleImagesAPIError(f"Could not download {url}: {exc}") from exc
174
+ return path
175
+
176
+ def _get(self, path: str, params: Dict[str, Any]) -> Dict[str, Any]:
177
+ try:
178
+ response = self._session.get(
179
+ f"{self.base_url}{path}", params=params, timeout=self.timeout
180
+ )
181
+ except requests.RequestException as exc:
182
+ raise GoogleImagesAPIError(f"Request failed: {exc}") from exc
183
+
184
+ try:
185
+ payload = response.json()
186
+ except ValueError:
187
+ payload = None
188
+
189
+ if response.status_code in (401, 403):
190
+ raise AuthenticationError(
191
+ _message(payload, "Invalid or missing API key."),
192
+ response.status_code,
193
+ payload,
194
+ )
195
+ if response.status_code == 429:
196
+ raise RateLimitError(
197
+ _message(payload, "Rate limit or quota exceeded."),
198
+ response.status_code,
199
+ payload,
200
+ )
201
+ if not response.ok:
202
+ raise APIError(
203
+ _message(payload, f"API returned HTTP {response.status_code}."),
204
+ response.status_code,
205
+ payload,
206
+ )
207
+ if not isinstance(payload, dict):
208
+ raise APIError("API returned a non-JSON response.", response.status_code)
209
+ return payload
210
+
211
+
212
+ def _message(payload: Any, default: str) -> str:
213
+ if isinstance(payload, dict):
214
+ for key in ("message", "error"):
215
+ value = payload.get(key)
216
+ if isinstance(value, str) and value:
217
+ return value
218
+ return default
@@ -0,0 +1,29 @@
1
+ """Exceptions raised by google_images_api."""
2
+
3
+ from typing import Any, Optional
4
+
5
+
6
+ class GoogleImagesAPIError(Exception):
7
+ """Base class for all errors raised by this library."""
8
+
9
+
10
+ class APIError(GoogleImagesAPIError):
11
+ """The API returned an error response or an unexpected payload."""
12
+
13
+ def __init__(
14
+ self,
15
+ message: str,
16
+ status_code: Optional[int] = None,
17
+ payload: Optional[Any] = None,
18
+ ) -> None:
19
+ super().__init__(message)
20
+ self.status_code = status_code
21
+ self.payload = payload
22
+
23
+
24
+ class AuthenticationError(APIError):
25
+ """The API key is missing, invalid or not allowed (HTTP 401/403)."""
26
+
27
+
28
+ class RateLimitError(APIError):
29
+ """Too many requests or quota exceeded (HTTP 429)."""
File without changes
@@ -0,0 +1,33 @@
1
+ import json
2
+ from unittest import mock
3
+
4
+ from google_images_api import cli
5
+ from google_images_api.client import Image, SearchResult
6
+
7
+
8
+ def test_cli_prints_urls(capsys, monkeypatch):
9
+ monkeypatch.setenv("COGNIFY_API_KEY", "key")
10
+ result = SearchResult(
11
+ query="x",
12
+ images=[Image(url="https://e.com/a.jpg", width=10, height=20, mime="image/jpg")],
13
+ raw={"images": []},
14
+ )
15
+ with mock.patch("google_images_api.cli.GoogleImagesAPI") as cls:
16
+ cls.return_value.__enter__.return_value.search.return_value = result
17
+ assert cli.main(["x", "-n", "1", "-i"]) == 0
18
+ assert "https://e.com/a.jpg 10x20 image/jpg" in capsys.readouterr().out
19
+
20
+
21
+ def test_cli_json(capsys, monkeypatch):
22
+ monkeypatch.setenv("COGNIFY_API_KEY", "key")
23
+ result = SearchResult(query="x", images=[], raw={"status": "success"})
24
+ with mock.patch("google_images_api.cli.GoogleImagesAPI") as cls:
25
+ cls.return_value.__enter__.return_value.search.return_value = result
26
+ assert cli.main(["x", "--json"]) == 0
27
+ assert json.loads(capsys.readouterr().out) == {"status": "success"}
28
+
29
+
30
+ def test_cli_missing_key(capsys, monkeypatch):
31
+ monkeypatch.delenv("COGNIFY_API_KEY", raising=False)
32
+ assert cli.main(["x"]) == 1
33
+ assert "No API key" in capsys.readouterr().err
@@ -0,0 +1,112 @@
1
+ from unittest import mock
2
+
3
+ import pytest
4
+
5
+ from google_images_api import (
6
+ APIError,
7
+ AuthenticationError,
8
+ GoogleImagesAPI,
9
+ RateLimitError,
10
+ )
11
+
12
+
13
+ def fake_response(status=200, payload=None, json_error=False):
14
+ response = mock.Mock()
15
+ response.status_code = status
16
+ response.ok = status < 400
17
+ if json_error:
18
+ response.json.side_effect = ValueError("no json")
19
+ else:
20
+ response.json.return_value = payload
21
+ return response
22
+
23
+
24
+ @pytest.fixture
25
+ def session():
26
+ s = mock.Mock()
27
+ s.headers = {}
28
+ return s
29
+
30
+
31
+ def make_client(session):
32
+ return GoogleImagesAPI(api_key="key", session=session)
33
+
34
+
35
+ def test_requires_api_key(monkeypatch):
36
+ monkeypatch.delenv("COGNIFY_API_KEY", raising=False)
37
+ with pytest.raises(AuthenticationError):
38
+ GoogleImagesAPI()
39
+
40
+
41
+ def test_api_key_from_env(monkeypatch, session):
42
+ monkeypatch.setenv("COGNIFY_API_KEY", "envkey")
43
+ GoogleImagesAPI(session=session)
44
+ assert session.headers == {"x-cognifyapi-key": "envkey"}
45
+
46
+
47
+ def test_search_with_image_info(session):
48
+ session.get.return_value = fake_response(
49
+ payload={
50
+ "status": "success",
51
+ "query": "SpaceX",
52
+ "results": 1,
53
+ "images": [
54
+ {
55
+ "url": "https://e.com/a.jpg",
56
+ "width": 1920,
57
+ "height": 1080,
58
+ "type": "jpg",
59
+ "mime": "image/jpg",
60
+ }
61
+ ],
62
+ }
63
+ )
64
+ result = make_client(session).search("SpaceX", count=1, image_info=True)
65
+
66
+ _, kwargs = session.get.call_args
67
+ assert session.get.call_args[0][0] == "https://api.cognifyapi.com/google-images"
68
+ assert kwargs["params"] == {"query": "SpaceX", "count": 1, "imageInfo": "true"}
69
+ assert len(result) == 1
70
+ assert result.urls == ["https://e.com/a.jpg"]
71
+ assert result.images[0].width == 1920
72
+ assert result.images[0].mime == "image/jpg"
73
+
74
+
75
+ def test_search_without_image_info_accepts_strings_and_objects(session):
76
+ session.get.return_value = fake_response(
77
+ payload={"images": ["https://e.com/a.jpg", {"url": "https://e.com/b.jpg"}]}
78
+ )
79
+ result = make_client(session).search("tesla")
80
+ assert result.urls == ["https://e.com/a.jpg", "https://e.com/b.jpg"]
81
+ assert result.images[1].width is None
82
+ assert session.get.call_args[1]["params"] == {"query": "tesla"}
83
+
84
+
85
+ @pytest.mark.parametrize(
86
+ "status, exc", [(401, AuthenticationError), (403, AuthenticationError),
87
+ (429, RateLimitError), (500, APIError)]
88
+ )
89
+ def test_http_errors(session, status, exc):
90
+ session.get.return_value = fake_response(status, {"message": "nope"})
91
+ with pytest.raises(exc) as info:
92
+ make_client(session).search("x")
93
+ assert info.value.status_code == status
94
+ assert str(info.value) == "nope"
95
+
96
+
97
+ def test_non_json_response(session):
98
+ session.get.return_value = fake_response(200, json_error=True)
99
+ with pytest.raises(APIError):
100
+ make_client(session).search("x")
101
+
102
+
103
+ def test_missing_images_array(session):
104
+ session.get.return_value = fake_response(payload={"status": "success"})
105
+ with pytest.raises(APIError):
106
+ make_client(session).search("x")
107
+
108
+
109
+ @pytest.mark.parametrize("query, count", [("", None), (" ", None), ("x", 0)])
110
+ def test_validation(session, query, count):
111
+ with pytest.raises(ValueError):
112
+ make_client(session).search(query, count=count)