google-images-api 0.1.0__py3-none-any.whl

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,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,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,10 @@
1
+ google_images_api/__init__.py,sha256=edvtWr4flzfgoaTB8yylqVB8oicy1oazLGufP8zdBG0,435
2
+ google_images_api/cli.py,sha256=odANU-iQj2qZL9v9ijfkQGv2pLXsS0GcmH9nylAJ0co,2222
3
+ google_images_api/client.py,sha256=koNsiPxbiDRxobSp6IrKlhJE-wITcTK05SmrTDIU6nM,7128
4
+ google_images_api/exceptions.py,sha256=V11X8YtVssupD4fXVb00mIaDD31GQbZLx1CDA04jQ9I,752
5
+ google_images_api/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
+ google_images_api-0.1.0.dist-info/METADATA,sha256=bItp131jWNganS_bxn2jnSUEppeP_Uqnqzd6QS9vlAg,4887
7
+ google_images_api-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
8
+ google_images_api-0.1.0.dist-info/entry_points.txt,sha256=K1YvMvbewt6yOPAPnvB_51Qlz-lQuPf798rVb07Ad9Y,65
9
+ google_images_api-0.1.0.dist-info/licenses/LICENSE,sha256=55aAxAn81ncyNPxe0IqQQ0F8E62Sk_iQNJTPtYOwn6g,1067
10
+ google_images_api-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ google-images-api = google_images_api.cli:main
@@ -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.