calotype 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,7 @@
1
+ node_modules/
2
+ dist/
3
+ *.tgz
4
+ *.tsbuildinfo
5
+ .venv/
6
+ *.egg-info/
7
+ __pycache__/
calotype-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Dostal Technology LLC
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,154 @@
1
+ Metadata-Version: 2.5
2
+ Name: calotype
3
+ Version: 0.1.0
4
+ Summary: Python client for Calotype, a hosted screenshot API: send a URL, get the page back as an image.
5
+ Project-URL: Homepage, https://calotype.dev
6
+ Project-URL: Documentation, https://calotype.dev/docs
7
+ Project-URL: Repository, https://github.com/skewbald-labs/calotype
8
+ Project-URL: Issues, https://github.com/skewbald-labs/calotype/issues
9
+ Author-email: "Skewbald, an AI agent" <skewbald@agentmail.to>
10
+ License-Expression: MIT
11
+ License-File: LICENSE
12
+ Keywords: ai-agent,calotype,screenshot,screenshot-api,website-screenshot
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: Topic :: Internet :: WWW/HTTP
19
+ Classifier: Typing :: Typed
20
+ Requires-Python: >=3.9
21
+ Description-Content-Type: text/markdown
22
+
23
+ # calotype
24
+
25
+ Python client for [Calotype](https://calotype.dev), a hosted screenshot API: send a URL, get the page back as a PNG, JPEG or WebP.
26
+
27
+ Calotype and this client are built and run by **Skewbald, an AI agent**. It wrote this code, runs the service and answers support at skewbald@agentmail.to. A person backs the project; Dostal Technology LLC is the seller.
28
+
29
+ ```sh
30
+ pip install calotype
31
+ ```
32
+
33
+ Python 3.9 or newer. No dependencies: the client uses the standard library.
34
+
35
+ ## Use
36
+
37
+ ```python
38
+ from calotype import Calotype
39
+
40
+ client = Calotype("cal_...") # or set CALOTYPE_API_KEY and call Calotype()
41
+
42
+ image = client.screenshot("https://example.com") # bytes: a 1280x800 PNG
43
+ open("example.png", "wb").write(image)
44
+
45
+ image = client.screenshot(
46
+ "https://calotype.dev/pricing",
47
+ format="webp",
48
+ full_page=True,
49
+ dark_mode=True,
50
+ block_ads=True,
51
+ )
52
+ ```
53
+
54
+ ### A free key
55
+
56
+ 100 screenshots a month, with no account and no email. The key is shown once; Calotype stores only its hash.
57
+
58
+ ```python
59
+ new = Calotype().create_key() # sends {"ref": "pypi"}, a tag that says the key came from this package
60
+ print(new.plan, new.monthly_quota) # free 100
61
+ client = Calotype(new.key) # keep new.key somewhere safe
62
+ ```
63
+
64
+ `create_key(ref=None)` sends no tag. `create_key(email="you@example.com")` adds an address for quota notices at 80% and 100%.
65
+
66
+ ### Usage
67
+
68
+ ```python
69
+ usage = client.usage()
70
+ print(usage.used, usage.limit, usage.remaining, usage.resets_at)
71
+ ```
72
+
73
+ ### More than the bytes
74
+
75
+ `capture()` takes the same arguments as `screenshot()` and returns a `Screenshot`: `image`, `content_type`, `used` and `limit` (the key's count after this capture), `target_status` (the page's own HTTP status), `truncated` and `duration_ms`.
76
+
77
+ ## Parameters
78
+
79
+ All optional and keyword-only. One left out is not sent, so the API's default applies. Full reference: [calotype.dev/docs](https://calotype.dev/docs).
80
+
81
+ | Parameter | Type | API default | Meaning |
82
+ |---|---|---|---|
83
+ | `width` | int, 100 to 3840 | 1280 | Viewport width in CSS pixels. |
84
+ | `height` | int, 100 to 2160 | 800 | Viewport height in CSS pixels. |
85
+ | `full_page` | bool | `False` | Capture the whole scrolling page (up to 20,000 px tall). |
86
+ | `format` | `"png"`, `"jpeg"`, `"webp"` | `"png"` | Image format. |
87
+ | `quality` | int, 1 to 100 | 80 | For jpeg and webp only. |
88
+ | `device_scale_factor` | float, 1 to 3 | 1 | Pixel density. |
89
+ | `delay_ms` | int, 0 to 10000 | 0 | Wait after the page loads. |
90
+ | `wait_until` | `"load"`, `"domcontentloaded"`, `"networkidle"`, `"commit"` | `"load"` | When the page counts as loaded. |
91
+ | `block_ads` | bool | `False` | Block requests to common ad and tracking domains. |
92
+ | `dark_mode` | bool | `False` | Ask the page for its dark colour scheme. |
93
+
94
+ ## Errors
95
+
96
+ Every error is a `CalotypeError` with `.code` (the API's stable error code), `.status` (the HTTP status) and `.message`. Failed captures are not counted against the quota.
97
+
98
+ | Class | Codes | Meaning |
99
+ |---|---|---|
100
+ | `AuthenticationError` | `missing_key`, `invalid_key` | No key, or one that is wrong or revoked. |
101
+ | `InvalidRequestError` | `invalid_parameters`, `invalid_url`, `invalid_scheme`, `invalid_json`, `invalid_email` | The request was not valid. `.details` lists the bad fields. |
102
+ | `BlockedTargetError` | `blocked_target` | The address is private, local or otherwise refused. |
103
+ | `CaptureFailedError` | `dns_error`, `target_unreachable`, `page_too_large`, `timeout` | The page could not be captured. |
104
+ | `QuotaExceededError` | `quota_exceeded` | The month's screenshots are used up. `.plan`, `.limit`, `.used`, `.resets_at`. |
105
+ | `RateLimitError` | `rate_limited` | Too many keys created recently. `.retry_after` seconds. |
106
+ | `ServerBusyError` | `busy` | All renderers are busy. `.retry_after` seconds. |
107
+ | `PermissionDeniedError` | `plan_unavailable`, `self_serve_disabled` | The server refused the action. |
108
+ | `ServerError` | `internal_error`, other 5xx | The service failed. |
109
+ | `APIConnectionError` | none | The API could not be reached or did not answer in time. |
110
+
111
+ ```python
112
+ from calotype import BlockedTargetError, QuotaExceededError
113
+
114
+ try:
115
+ image = client.screenshot("http://localhost:3000")
116
+ except BlockedTargetError as e:
117
+ print(e) # blocked_target: ...
118
+ except QuotaExceededError as e:
119
+ print(e.resets_at)
120
+ ```
121
+
122
+ ## Options
123
+
124
+ ```python
125
+ Calotype(api_key, base_url="https://calotype.dev", timeout=90.0, transport=None)
126
+ ```
127
+
128
+ - `base_url`: set it if you run your own Calotype.
129
+ - `timeout`: seconds per request.
130
+ - `transport`: a function `(calotype.Request) -> calotype.Response`, to use another HTTP library or a fake in tests. The default uses `urllib.request`, which honours the usual proxy environment variables.
131
+
132
+ The client is synchronous. In async code, run it in a thread: `await asyncio.to_thread(client.screenshot, url)`.
133
+
134
+ ## What it sends
135
+
136
+ Only the calls you make: `POST /v1/screenshot`, `POST /v1/keys`, `GET /v1/usage`, each with `User-Agent: calotype-python/<version>`, and your key on the two that need it. Privacy notice: [calotype.dev/privacy](https://calotype.dev/privacy).
137
+
138
+ ## MCP
139
+
140
+ This package has no MCP server. For agents, use the hosted one at `https://calotype.dev/mcp`, or the local `calotype-mcp` server for Node.js: [calotype.dev/agents](https://calotype.dev/agents).
141
+
142
+ ## Develop
143
+
144
+ The source is in [`clients/python`](https://github.com/skewbald-labs/calotype/tree/main/clients/python) of the Calotype repository, next to the service itself. The service's own Python package is also named `calotype`, so run these from `clients/python`, never from the repository root:
145
+
146
+ ```sh
147
+ uv run pytest # no network: the HTTP layer is faked
148
+ CALOTYPE_LIVE=1 uv run pytest # adds one keyless call to calotype.dev; creates no key
149
+ uv build
150
+ ```
151
+
152
+ ## License
153
+
154
+ MIT. See `LICENSE`.
@@ -0,0 +1,132 @@
1
+ # calotype
2
+
3
+ Python client for [Calotype](https://calotype.dev), a hosted screenshot API: send a URL, get the page back as a PNG, JPEG or WebP.
4
+
5
+ Calotype and this client are built and run by **Skewbald, an AI agent**. It wrote this code, runs the service and answers support at skewbald@agentmail.to. A person backs the project; Dostal Technology LLC is the seller.
6
+
7
+ ```sh
8
+ pip install calotype
9
+ ```
10
+
11
+ Python 3.9 or newer. No dependencies: the client uses the standard library.
12
+
13
+ ## Use
14
+
15
+ ```python
16
+ from calotype import Calotype
17
+
18
+ client = Calotype("cal_...") # or set CALOTYPE_API_KEY and call Calotype()
19
+
20
+ image = client.screenshot("https://example.com") # bytes: a 1280x800 PNG
21
+ open("example.png", "wb").write(image)
22
+
23
+ image = client.screenshot(
24
+ "https://calotype.dev/pricing",
25
+ format="webp",
26
+ full_page=True,
27
+ dark_mode=True,
28
+ block_ads=True,
29
+ )
30
+ ```
31
+
32
+ ### A free key
33
+
34
+ 100 screenshots a month, with no account and no email. The key is shown once; Calotype stores only its hash.
35
+
36
+ ```python
37
+ new = Calotype().create_key() # sends {"ref": "pypi"}, a tag that says the key came from this package
38
+ print(new.plan, new.monthly_quota) # free 100
39
+ client = Calotype(new.key) # keep new.key somewhere safe
40
+ ```
41
+
42
+ `create_key(ref=None)` sends no tag. `create_key(email="you@example.com")` adds an address for quota notices at 80% and 100%.
43
+
44
+ ### Usage
45
+
46
+ ```python
47
+ usage = client.usage()
48
+ print(usage.used, usage.limit, usage.remaining, usage.resets_at)
49
+ ```
50
+
51
+ ### More than the bytes
52
+
53
+ `capture()` takes the same arguments as `screenshot()` and returns a `Screenshot`: `image`, `content_type`, `used` and `limit` (the key's count after this capture), `target_status` (the page's own HTTP status), `truncated` and `duration_ms`.
54
+
55
+ ## Parameters
56
+
57
+ All optional and keyword-only. One left out is not sent, so the API's default applies. Full reference: [calotype.dev/docs](https://calotype.dev/docs).
58
+
59
+ | Parameter | Type | API default | Meaning |
60
+ |---|---|---|---|
61
+ | `width` | int, 100 to 3840 | 1280 | Viewport width in CSS pixels. |
62
+ | `height` | int, 100 to 2160 | 800 | Viewport height in CSS pixels. |
63
+ | `full_page` | bool | `False` | Capture the whole scrolling page (up to 20,000 px tall). |
64
+ | `format` | `"png"`, `"jpeg"`, `"webp"` | `"png"` | Image format. |
65
+ | `quality` | int, 1 to 100 | 80 | For jpeg and webp only. |
66
+ | `device_scale_factor` | float, 1 to 3 | 1 | Pixel density. |
67
+ | `delay_ms` | int, 0 to 10000 | 0 | Wait after the page loads. |
68
+ | `wait_until` | `"load"`, `"domcontentloaded"`, `"networkidle"`, `"commit"` | `"load"` | When the page counts as loaded. |
69
+ | `block_ads` | bool | `False` | Block requests to common ad and tracking domains. |
70
+ | `dark_mode` | bool | `False` | Ask the page for its dark colour scheme. |
71
+
72
+ ## Errors
73
+
74
+ Every error is a `CalotypeError` with `.code` (the API's stable error code), `.status` (the HTTP status) and `.message`. Failed captures are not counted against the quota.
75
+
76
+ | Class | Codes | Meaning |
77
+ |---|---|---|
78
+ | `AuthenticationError` | `missing_key`, `invalid_key` | No key, or one that is wrong or revoked. |
79
+ | `InvalidRequestError` | `invalid_parameters`, `invalid_url`, `invalid_scheme`, `invalid_json`, `invalid_email` | The request was not valid. `.details` lists the bad fields. |
80
+ | `BlockedTargetError` | `blocked_target` | The address is private, local or otherwise refused. |
81
+ | `CaptureFailedError` | `dns_error`, `target_unreachable`, `page_too_large`, `timeout` | The page could not be captured. |
82
+ | `QuotaExceededError` | `quota_exceeded` | The month's screenshots are used up. `.plan`, `.limit`, `.used`, `.resets_at`. |
83
+ | `RateLimitError` | `rate_limited` | Too many keys created recently. `.retry_after` seconds. |
84
+ | `ServerBusyError` | `busy` | All renderers are busy. `.retry_after` seconds. |
85
+ | `PermissionDeniedError` | `plan_unavailable`, `self_serve_disabled` | The server refused the action. |
86
+ | `ServerError` | `internal_error`, other 5xx | The service failed. |
87
+ | `APIConnectionError` | none | The API could not be reached or did not answer in time. |
88
+
89
+ ```python
90
+ from calotype import BlockedTargetError, QuotaExceededError
91
+
92
+ try:
93
+ image = client.screenshot("http://localhost:3000")
94
+ except BlockedTargetError as e:
95
+ print(e) # blocked_target: ...
96
+ except QuotaExceededError as e:
97
+ print(e.resets_at)
98
+ ```
99
+
100
+ ## Options
101
+
102
+ ```python
103
+ Calotype(api_key, base_url="https://calotype.dev", timeout=90.0, transport=None)
104
+ ```
105
+
106
+ - `base_url`: set it if you run your own Calotype.
107
+ - `timeout`: seconds per request.
108
+ - `transport`: a function `(calotype.Request) -> calotype.Response`, to use another HTTP library or a fake in tests. The default uses `urllib.request`, which honours the usual proxy environment variables.
109
+
110
+ The client is synchronous. In async code, run it in a thread: `await asyncio.to_thread(client.screenshot, url)`.
111
+
112
+ ## What it sends
113
+
114
+ Only the calls you make: `POST /v1/screenshot`, `POST /v1/keys`, `GET /v1/usage`, each with `User-Agent: calotype-python/<version>`, and your key on the two that need it. Privacy notice: [calotype.dev/privacy](https://calotype.dev/privacy).
115
+
116
+ ## MCP
117
+
118
+ This package has no MCP server. For agents, use the hosted one at `https://calotype.dev/mcp`, or the local `calotype-mcp` server for Node.js: [calotype.dev/agents](https://calotype.dev/agents).
119
+
120
+ ## Develop
121
+
122
+ The source is in [`clients/python`](https://github.com/skewbald-labs/calotype/tree/main/clients/python) of the Calotype repository, next to the service itself. The service's own Python package is also named `calotype`, so run these from `clients/python`, never from the repository root:
123
+
124
+ ```sh
125
+ uv run pytest # no network: the HTTP layer is faked
126
+ CALOTYPE_LIVE=1 uv run pytest # adds one keyless call to calotype.dev; creates no key
127
+ uv build
128
+ ```
129
+
130
+ ## License
131
+
132
+ MIT. See `LICENSE`.
@@ -0,0 +1,48 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.25"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "calotype"
7
+ dynamic = ["version"]
8
+ description = "Python client for Calotype, a hosted screenshot API: send a URL, get the page back as an image."
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ license-files = ["LICENSE"]
12
+ requires-python = ">=3.9"
13
+ authors = [{ name = "Skewbald, an AI agent", email = "skewbald@agentmail.to" }]
14
+ keywords = ["screenshot", "screenshot-api", "calotype", "website-screenshot", "ai-agent"]
15
+ classifiers = [
16
+ "Development Status :: 4 - Beta",
17
+ "Intended Audience :: Developers",
18
+ "Operating System :: OS Independent",
19
+ "Programming Language :: Python :: 3",
20
+ "Programming Language :: Python :: 3 :: Only",
21
+ "Topic :: Internet :: WWW/HTTP",
22
+ "Typing :: Typed",
23
+ ]
24
+ # No dependencies: the client uses the standard library's urllib.
25
+ dependencies = []
26
+
27
+ [project.urls]
28
+ Homepage = "https://calotype.dev"
29
+ Documentation = "https://calotype.dev/docs"
30
+ Repository = "https://github.com/skewbald-labs/calotype"
31
+ Issues = "https://github.com/skewbald-labs/calotype/issues"
32
+
33
+ [dependency-groups]
34
+ dev = ["pytest>=8"]
35
+
36
+ [tool.hatch.version]
37
+ path = "src/calotype/_version.py"
38
+
39
+ [tool.hatch.build.targets.wheel]
40
+ packages = ["src/calotype"]
41
+
42
+ [tool.hatch.build.targets.sdist]
43
+ include = ["src", "tests", "README.md", "LICENSE", "pyproject.toml"]
44
+
45
+ [tool.pytest.ini_options]
46
+ testpaths = ["tests"]
47
+ pythonpath = ["tests"]
48
+ addopts = "-p no:cacheprovider --import-mode=importlib"
@@ -0,0 +1,56 @@
1
+ """Python client for Calotype, a hosted screenshot API (https://calotype.dev).
2
+
3
+ from calotype import Calotype
4
+
5
+ image = Calotype("cal_...").screenshot("https://example.com", format="webp")
6
+
7
+ Calotype and this client are built and run by Skewbald, an AI agent.
8
+ """
9
+
10
+ from ._client import (
11
+ DEFAULT_BASE_URL,
12
+ Calotype,
13
+ NewKey,
14
+ Request,
15
+ Response,
16
+ Screenshot,
17
+ Transport,
18
+ Usage,
19
+ )
20
+ from ._version import __version__
21
+ from .errors import (
22
+ APIConnectionError,
23
+ AuthenticationError,
24
+ BlockedTargetError,
25
+ CalotypeError,
26
+ CaptureFailedError,
27
+ InvalidRequestError,
28
+ PermissionDeniedError,
29
+ QuotaExceededError,
30
+ RateLimitError,
31
+ ServerBusyError,
32
+ ServerError,
33
+ )
34
+
35
+ __all__ = [
36
+ "APIConnectionError",
37
+ "AuthenticationError",
38
+ "BlockedTargetError",
39
+ "Calotype",
40
+ "CalotypeError",
41
+ "CaptureFailedError",
42
+ "DEFAULT_BASE_URL",
43
+ "InvalidRequestError",
44
+ "NewKey",
45
+ "PermissionDeniedError",
46
+ "QuotaExceededError",
47
+ "RateLimitError",
48
+ "Request",
49
+ "Response",
50
+ "Screenshot",
51
+ "ServerBusyError",
52
+ "ServerError",
53
+ "Transport",
54
+ "Usage",
55
+ "__version__",
56
+ ]
@@ -0,0 +1,293 @@
1
+ """The client: three calls over the Calotype HTTP API, with the standard library only."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import socket
8
+ import urllib.error
9
+ import urllib.request
10
+ from dataclasses import dataclass, field
11
+ from typing import Any, Callable, Literal, Mapping
12
+ from urllib.parse import urlsplit
13
+
14
+ from ._version import __version__
15
+ from .errors import APIConnectionError, AuthenticationError, CalotypeError, error_for
16
+
17
+ DEFAULT_BASE_URL = "https://calotype.dev"
18
+ USER_AGENT = f"calotype-python/{__version__}"
19
+
20
+ Format = Literal["png", "jpeg", "webp"]
21
+ WaitUntil = Literal["load", "domcontentloaded", "networkidle", "commit"]
22
+
23
+
24
+ @dataclass(frozen=True)
25
+ class Request:
26
+ """One HTTP request, as handed to the transport."""
27
+
28
+ method: str
29
+ url: str
30
+ headers: Mapping[str, str]
31
+ body: bytes | None
32
+ timeout: float
33
+
34
+
35
+ @dataclass(frozen=True)
36
+ class Response:
37
+ """One HTTP answer, as the transport returns it. Header names are lower case."""
38
+
39
+ status: int
40
+ headers: Mapping[str, str]
41
+ body: bytes
42
+
43
+
44
+ #: Sends a request and returns the answer, whatever its status. Raises
45
+ #: ``APIConnectionError`` when there is no answer. Pass your own to
46
+ #: ``Calotype(transport=...)`` to use another HTTP library, or a fake in tests.
47
+ Transport = Callable[[Request], Response]
48
+
49
+
50
+ def urllib_transport(request: Request) -> Response:
51
+ """The default transport: ``urllib.request`` from the standard library."""
52
+ req = urllib.request.Request(request.url, data=request.body, method=request.method, headers=dict(request.headers))
53
+ try:
54
+ try:
55
+ with urllib.request.urlopen(req, timeout=request.timeout) as resp:
56
+ return Response(resp.status, {k.lower(): v for k, v in resp.headers.items()}, resp.read())
57
+ except urllib.error.HTTPError as e: # an answer with an error status
58
+ try:
59
+ return Response(e.code, {k.lower(): v for k, v in e.headers.items()}, e.read())
60
+ finally:
61
+ e.close()
62
+ except (urllib.error.URLError, socket.timeout, TimeoutError, ConnectionError, OSError) as e:
63
+ reason = getattr(e, "reason", e)
64
+ raise APIConnectionError(f"Could not reach the Calotype API ({type(reason).__name__}).") from e
65
+
66
+
67
+ @dataclass(frozen=True)
68
+ class Screenshot:
69
+ """A captured page: the image and what the API said about it."""
70
+
71
+ image: bytes = field(repr=False)
72
+ content_type: str
73
+ #: Screenshots the key has used this month, and its monthly limit.
74
+ used: int | None
75
+ limit: int | None
76
+ #: The page's own HTTP status, when the API reported one.
77
+ target_status: int | None
78
+ #: True if the page passed the download limit and the image shows what had loaded by then.
79
+ truncated: bool
80
+ duration_ms: int | None
81
+
82
+
83
+ @dataclass(frozen=True)
84
+ class NewKey:
85
+ """A key from ``create_key``. ``key`` is shown this once; Calotype keeps only its hash."""
86
+
87
+ key: str = field(repr=False)
88
+ plan: str
89
+ monthly_quota: int
90
+ message: str = ""
91
+
92
+
93
+ @dataclass(frozen=True)
94
+ class Usage:
95
+ """A key's count for the current month."""
96
+
97
+ plan: str
98
+ month: str
99
+ used: int
100
+ limit: int
101
+ resets_at: str
102
+ #: Not secret: names this key to support without sending the key.
103
+ key_ref: str
104
+ #: The masked address quota notices go to, if the key has one.
105
+ email: str | None = None
106
+ notices: bool = False
107
+
108
+ @property
109
+ def remaining(self) -> int:
110
+ return max(0, self.limit - self.used)
111
+
112
+
113
+ def _int(value: str | None) -> int | None:
114
+ try:
115
+ return int(value) # type: ignore[arg-type]
116
+ except (TypeError, ValueError):
117
+ return None
118
+
119
+
120
+ class Calotype:
121
+ """A client for the Calotype API.
122
+
123
+ ``api_key`` defaults to the ``CALOTYPE_API_KEY`` environment variable.
124
+ ``create_key`` needs no key. ``timeout`` is in seconds, per request.
125
+ """
126
+
127
+ def __init__(
128
+ self,
129
+ api_key: str | None = None,
130
+ *,
131
+ base_url: str = DEFAULT_BASE_URL,
132
+ timeout: float = 90.0,
133
+ transport: Transport | None = None,
134
+ ) -> None:
135
+ self.api_key = (api_key if api_key is not None else os.environ.get("CALOTYPE_API_KEY", "")).strip()
136
+ self.base_url = base_url.rstrip("/")
137
+ if urlsplit(self.base_url).scheme not in ("http", "https"):
138
+ raise ValueError("base_url must start with http:// or https://")
139
+ self.timeout = timeout
140
+ self._transport = transport or urllib_transport
141
+
142
+ def __repr__(self) -> str: # never the key
143
+ return f"Calotype(base_url={self.base_url!r}, api_key={'set' if self.api_key else 'not set'})"
144
+
145
+ # --- the three calls ------------------------------------------------------------------
146
+
147
+ def screenshot(
148
+ self,
149
+ url: str,
150
+ *,
151
+ width: int | None = None,
152
+ height: int | None = None,
153
+ full_page: bool | None = None,
154
+ format: Format | None = None,
155
+ quality: int | None = None,
156
+ device_scale_factor: float | None = None,
157
+ delay_ms: int | None = None,
158
+ wait_until: WaitUntil | None = None,
159
+ block_ads: bool | None = None,
160
+ dark_mode: bool | None = None,
161
+ ) -> bytes:
162
+ """Capture ``url`` and return the image bytes.
163
+
164
+ Parameters left as ``None`` are not sent, so the API's defaults apply:
165
+ a 1280 by 800 PNG of the viewport. Reference: https://calotype.dev/docs
166
+ """
167
+ return self.capture(
168
+ url,
169
+ width=width,
170
+ height=height,
171
+ full_page=full_page,
172
+ format=format,
173
+ quality=quality,
174
+ device_scale_factor=device_scale_factor,
175
+ delay_ms=delay_ms,
176
+ wait_until=wait_until,
177
+ block_ads=block_ads,
178
+ dark_mode=dark_mode,
179
+ ).image
180
+
181
+ def capture(
182
+ self,
183
+ url: str,
184
+ *,
185
+ width: int | None = None,
186
+ height: int | None = None,
187
+ full_page: bool | None = None,
188
+ format: Format | None = None,
189
+ quality: int | None = None,
190
+ device_scale_factor: float | None = None,
191
+ delay_ms: int | None = None,
192
+ wait_until: WaitUntil | None = None,
193
+ block_ads: bool | None = None,
194
+ dark_mode: bool | None = None,
195
+ ) -> Screenshot:
196
+ """Like ``screenshot``, but also returns the usage count and the page's status."""
197
+ params = {
198
+ "url": url,
199
+ "width": width,
200
+ "height": height,
201
+ "full_page": full_page,
202
+ "format": format,
203
+ "quality": quality,
204
+ "device_scale_factor": device_scale_factor,
205
+ "delay_ms": delay_ms,
206
+ "wait_until": wait_until,
207
+ "block_ads": block_ads,
208
+ "dark_mode": dark_mode,
209
+ }
210
+ resp = self._send("POST", "/v1/screenshot", {k: v for k, v in params.items() if v is not None}, auth=True)
211
+ used, _, limit = resp.headers.get("x-calotype-usage", "").partition("/")
212
+ return Screenshot(
213
+ image=resp.body,
214
+ content_type=resp.headers.get("content-type", "").split(";")[0].strip(),
215
+ used=_int(used),
216
+ limit=_int(limit),
217
+ target_status=_int(resp.headers.get("x-calotype-target-status")),
218
+ truncated=bool(resp.headers.get("x-calotype-truncated")),
219
+ duration_ms=_int(resp.headers.get("x-calotype-duration-ms")),
220
+ )
221
+
222
+ def create_key(self, ref: str | None = "pypi", *, email: str | None = None) -> NewKey:
223
+ """Create a free key. Needs no key and no account.
224
+
225
+ ``ref`` is a short tag that tells Calotype where the key came from;
226
+ pass ``None`` to send none. ``email`` is optional and used only for
227
+ quota notices. The new key is returned, not stored on this client:
228
+ ``Calotype(new.key)`` makes a client that uses it.
229
+ """
230
+ body: dict[str, Any] = {}
231
+ if ref:
232
+ body["ref"] = ref
233
+ if email:
234
+ body["email"] = email
235
+ resp = self._send("POST", "/v1/keys", body, auth=False)
236
+ data = self._json(resp)
237
+ if not isinstance(data.get("key"), str):
238
+ raise CalotypeError("The API's answer held no key.", status=resp.status)
239
+ return NewKey(
240
+ key=data["key"],
241
+ plan=data.get("plan", ""),
242
+ monthly_quota=data.get("monthly_quota", 0),
243
+ message=data.get("message", ""),
244
+ )
245
+
246
+ def usage(self) -> Usage:
247
+ """This key's count for the current month."""
248
+ data = self._json(self._send("GET", "/v1/usage", None, auth=True))
249
+ return Usage(
250
+ plan=data.get("plan", ""),
251
+ month=data.get("month", ""),
252
+ used=data.get("used", 0),
253
+ limit=data.get("limit", 0),
254
+ resets_at=data.get("resets_at", ""),
255
+ key_ref=data.get("key_ref", ""),
256
+ email=data.get("email"),
257
+ notices=bool(data.get("notices", False)),
258
+ )
259
+
260
+ # --- HTTP -----------------------------------------------------------------------------
261
+
262
+ def _send(self, method: str, path: str, body: Mapping[str, Any] | None, *, auth: bool) -> Response:
263
+ headers = {"User-Agent": USER_AGENT, "Accept": "*/*"}
264
+ if auth:
265
+ if not self.api_key:
266
+ raise AuthenticationError(
267
+ "No API key. Pass one to Calotype(...) or set CALOTYPE_API_KEY. "
268
+ "Calotype().create_key() makes a free one.",
269
+ code="missing_key",
270
+ )
271
+ headers["Authorization"] = f"Bearer {self.api_key}"
272
+ data = None
273
+ if body is not None:
274
+ data = json.dumps(body).encode()
275
+ headers["Content-Type"] = "application/json"
276
+ resp = self._transport(Request(method, self.base_url + path, headers, data, self.timeout))
277
+ if not 200 <= resp.status < 300:
278
+ try:
279
+ error = json.loads(resp.body).get("error")
280
+ except Exception:
281
+ error = None
282
+ raise error_for(resp.status, error, resp.headers)
283
+ return resp
284
+
285
+ @staticmethod
286
+ def _json(resp: Response) -> dict[str, Any]:
287
+ try:
288
+ data = json.loads(resp.body)
289
+ except ValueError:
290
+ data = None
291
+ if not isinstance(data, dict):
292
+ raise CalotypeError("The API answered with something that is not a JSON object.", status=resp.status)
293
+ return data
@@ -0,0 +1 @@
1
+ __version__ = "0.1.0"
@@ -0,0 +1,154 @@
1
+ """Errors the client raises, one class per kind of API error code.
2
+
3
+ Every API error answers ``{"error": {"code": ..., "message": ...}}``. The code
4
+ is stable; ``error_for`` picks the class from it, then from the HTTP status.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from typing import Any, Mapping
10
+
11
+
12
+ class CalotypeError(Exception):
13
+ """Any error from the client. The base of every class below.
14
+
15
+ ``code`` is the API's stable error code (``""`` when the answer had none),
16
+ ``status`` the HTTP status (``None`` when there was no answer), and
17
+ ``body`` the parsed ``error`` object with any extra fields.
18
+ """
19
+
20
+ def __init__(
21
+ self,
22
+ message: str,
23
+ *,
24
+ code: str = "",
25
+ status: int | None = None,
26
+ body: Mapping[str, Any] | None = None,
27
+ headers: Mapping[str, str] | None = None,
28
+ ) -> None:
29
+ super().__init__(message)
30
+ self.message = message
31
+ self.code = code
32
+ self.status = status
33
+ self.body: Mapping[str, Any] = body or {}
34
+ self.headers: Mapping[str, str] = headers or {}
35
+
36
+ def __str__(self) -> str:
37
+ return f"{self.code}: {self.message}" if self.code else self.message
38
+
39
+ @property
40
+ def retry_after(self) -> float | None:
41
+ """Seconds the server asked the caller to wait, if it said."""
42
+ value = self.body.get("retry_after_s", self.headers.get("retry-after"))
43
+ try:
44
+ return float(value) # type: ignore[arg-type]
45
+ except (TypeError, ValueError):
46
+ return None
47
+
48
+
49
+ class APIConnectionError(CalotypeError):
50
+ """The API could not be reached, or did not answer in time. Nothing was counted."""
51
+
52
+
53
+ class AuthenticationError(CalotypeError):
54
+ """No key, or a key that is wrong or revoked (``missing_key``, ``invalid_key``)."""
55
+
56
+
57
+ class PermissionDeniedError(CalotypeError):
58
+ """The server refused the action (``plan_unavailable``, ``self_serve_disabled``)."""
59
+
60
+
61
+ class InvalidRequestError(CalotypeError):
62
+ """The request was not valid (``invalid_parameters``, ``invalid_url``,
63
+ ``invalid_scheme``, ``invalid_json``, ``invalid_email``)."""
64
+
65
+ @property
66
+ def details(self) -> list[dict[str, str]]:
67
+ """For ``invalid_parameters``: one ``{"field": ..., "message": ...}`` per bad field."""
68
+ details = self.body.get("details")
69
+ return list(details) if isinstance(details, list) else []
70
+
71
+ def __str__(self) -> str:
72
+ text = super().__str__()
73
+ if self.details:
74
+ text += " " + "; ".join(f"{d.get('field')}: {d.get('message')}" for d in self.details)
75
+ return text
76
+
77
+
78
+ class BlockedTargetError(CalotypeError):
79
+ """The address is private, local or otherwise not allowed (``blocked_target``)."""
80
+
81
+
82
+ class CaptureFailedError(CalotypeError):
83
+ """The page could not be captured (``dns_error``, ``target_unreachable``,
84
+ ``page_too_large``, ``timeout``). It was not counted against the quota."""
85
+
86
+
87
+ class QuotaExceededError(CalotypeError):
88
+ """The key has used its screenshots for the month (``quota_exceeded``)."""
89
+
90
+ @property
91
+ def plan(self) -> str | None:
92
+ return self.body.get("plan")
93
+
94
+ @property
95
+ def limit(self) -> int | None:
96
+ return self.body.get("limit")
97
+
98
+ @property
99
+ def used(self) -> int | None:
100
+ return self.body.get("used")
101
+
102
+ @property
103
+ def resets_at(self) -> str | None:
104
+ """When the count resets, as an ISO 8601 UTC time."""
105
+ return self.body.get("resets_at")
106
+
107
+
108
+ class RateLimitError(CalotypeError):
109
+ """Too many keys were created recently (``rate_limited``). See ``retry_after``."""
110
+
111
+
112
+ class ServerBusyError(CalotypeError):
113
+ """All renderers are busy (``busy``). Retry after ``retry_after`` seconds."""
114
+
115
+
116
+ class ServerError(CalotypeError):
117
+ """The service failed (``internal_error``, or any other 5xx answer)."""
118
+
119
+
120
+ _BY_CODE: dict[str, type[CalotypeError]] = {
121
+ "missing_key": AuthenticationError,
122
+ "invalid_key": AuthenticationError,
123
+ "plan_unavailable": PermissionDeniedError,
124
+ "self_serve_disabled": PermissionDeniedError,
125
+ "invalid_parameters": InvalidRequestError,
126
+ "invalid_url": InvalidRequestError,
127
+ "invalid_scheme": InvalidRequestError,
128
+ "invalid_json": InvalidRequestError,
129
+ "invalid_email": InvalidRequestError,
130
+ "blocked_target": BlockedTargetError,
131
+ "dns_error": CaptureFailedError,
132
+ "target_unreachable": CaptureFailedError,
133
+ "page_too_large": CaptureFailedError,
134
+ "timeout": CaptureFailedError,
135
+ "quota_exceeded": QuotaExceededError,
136
+ "rate_limited": RateLimitError,
137
+ "busy": ServerBusyError,
138
+ "internal_error": ServerError,
139
+ }
140
+
141
+ _BY_STATUS: dict[int, type[CalotypeError]] = {
142
+ 400: InvalidRequestError,
143
+ 401: AuthenticationError,
144
+ 403: PermissionDeniedError,
145
+ }
146
+
147
+
148
+ def error_for(status: int, error: Mapping[str, Any] | None, headers: Mapping[str, str]) -> CalotypeError:
149
+ """The exception for an answer that is not a success."""
150
+ error = error if isinstance(error, Mapping) else {}
151
+ code = error.get("code") if isinstance(error.get("code"), str) else ""
152
+ message = error.get("message") if isinstance(error.get("message"), str) else f"HTTP {status}"
153
+ cls = _BY_CODE.get(code) or _BY_STATUS.get(status) or (ServerError if status >= 500 else CalotypeError)
154
+ return cls(message, code=code, status=status, body=error, headers=headers)
File without changes
@@ -0,0 +1,22 @@
1
+ """A guard against testing the wrong ``calotype``.
2
+
3
+ The service in this repository is also a package named ``calotype`` (at the
4
+ repository root). These tests are for the client in ``clients/python/src``;
5
+ if the import resolves anywhere else, stop before a single test runs.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from pathlib import Path
11
+
12
+ import pytest
13
+
14
+ import calotype
15
+
16
+ _SRC = Path(__file__).resolve().parents[1] / "src" / "calotype"
17
+ _FOUND = Path(calotype.__file__).resolve().parent
18
+ if not hasattr(calotype, "Calotype") or (_FOUND != _SRC and "site-packages" not in _FOUND.parts):
19
+ raise pytest.UsageError(
20
+ f"'import calotype' found {_FOUND}, not the client in {_SRC}. "
21
+ "Run the tests from clients/python with the client installed: uv run pytest"
22
+ )
@@ -0,0 +1,38 @@
1
+ """Fakes for the HTTP layer, so the tests need no network."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from typing import Any
7
+
8
+ from calotype import Request, Response
9
+
10
+
11
+ class FakeTransport:
12
+ """Records each request and answers from a queue."""
13
+
14
+ def __init__(self, *answers: Response | Exception) -> None:
15
+ self.answers = list(answers)
16
+ self.requests: list[Request] = []
17
+
18
+ def __call__(self, request: Request) -> Response:
19
+ self.requests.append(request)
20
+ answer = self.answers.pop(0)
21
+ if isinstance(answer, Exception):
22
+ raise answer
23
+ return answer
24
+
25
+ @property
26
+ def last(self) -> Request:
27
+ return self.requests[-1]
28
+
29
+ def last_json(self) -> Any:
30
+ return json.loads(self.last.body or b"null")
31
+
32
+
33
+ def json_response(status: int, data: Any, headers: dict[str, str] | None = None) -> Response:
34
+ return Response(status, {"content-type": "application/json", **(headers or {})}, json.dumps(data).encode())
35
+
36
+
37
+ def error_response(status: int, code: str, message: str, headers: dict[str, str] | None = None, **extra: Any) -> Response:
38
+ return json_response(status, {"error": {"code": code, "message": message, **extra}}, headers)
@@ -0,0 +1,169 @@
1
+ from __future__ import annotations
2
+
3
+ import pytest
4
+
5
+ import calotype
6
+ from calotype import Calotype, NewKey, Response, Screenshot, Usage
7
+
8
+ from fakes import FakeTransport, json_response
9
+
10
+ PNG = b"\x89PNG\r\n\x1a\n fake image bytes"
11
+
12
+
13
+ def image_response(**headers: str) -> Response:
14
+ return Response(200, {"content-type": "image/png", **headers}, PNG)
15
+
16
+
17
+ def test_screenshot_returns_the_image_bytes_and_sends_only_what_was_asked():
18
+ transport = FakeTransport(image_response())
19
+ client = Calotype("cal_test", transport=transport)
20
+
21
+ assert client.screenshot("https://example.com") == PNG
22
+
23
+ request = transport.last
24
+ assert request.method == "POST"
25
+ assert request.url == "https://calotype.dev/v1/screenshot"
26
+ assert request.headers["Authorization"] == "Bearer cal_test"
27
+ assert request.headers["Content-Type"] == "application/json"
28
+ assert request.headers["User-Agent"] == f"calotype-python/{calotype.__version__}"
29
+ assert request.timeout == 90.0
30
+ # Nothing but the URL: the API's own defaults apply.
31
+ assert transport.last_json() == {"url": "https://example.com"}
32
+
33
+
34
+ def test_screenshot_passes_every_parameter_through():
35
+ transport = FakeTransport(image_response())
36
+ Calotype("cal_test", transport=transport).screenshot(
37
+ "https://example.com",
38
+ width=390,
39
+ height=844,
40
+ full_page=True,
41
+ format="webp",
42
+ quality=70,
43
+ device_scale_factor=2.0,
44
+ delay_ms=500,
45
+ wait_until="networkidle",
46
+ block_ads=True,
47
+ dark_mode=False,
48
+ )
49
+ assert transport.last_json() == {
50
+ "url": "https://example.com",
51
+ "width": 390,
52
+ "height": 844,
53
+ "full_page": True,
54
+ "format": "webp",
55
+ "quality": 70,
56
+ "device_scale_factor": 2.0,
57
+ "delay_ms": 500,
58
+ "wait_until": "networkidle",
59
+ "block_ads": True,
60
+ "dark_mode": False, # False is a value, not "unset"
61
+ }
62
+
63
+
64
+ def test_capture_reads_the_usage_and_page_headers():
65
+ transport = FakeTransport(
66
+ image_response(
67
+ **{
68
+ "content-type": "image/webp; charset=binary",
69
+ "x-calotype-usage": "42/100",
70
+ "x-calotype-duration-ms": "1830",
71
+ "x-calotype-target-status": "404",
72
+ "x-calotype-truncated": "1",
73
+ }
74
+ ),
75
+ image_response(),
76
+ )
77
+ client = Calotype("cal_test", transport=transport)
78
+
79
+ shot = client.capture("https://example.com/missing", format="webp")
80
+ assert shot == Screenshot(
81
+ image=PNG, content_type="image/webp", used=42, limit=100, target_status=404, truncated=True, duration_ms=1830
82
+ )
83
+
84
+ bare = client.capture("https://example.com")
85
+ assert (bare.used, bare.limit, bare.target_status, bare.truncated, bare.duration_ms) == (None, None, None, False, None)
86
+ assert "fake image" not in repr(bare)
87
+
88
+
89
+ def test_create_key_needs_no_key_and_tags_the_source():
90
+ answer = {"key": "cal_new", "plan": "free", "monthly_quota": 100, "message": "This is the only time the key is shown."}
91
+ transport = FakeTransport(json_response(201, answer), json_response(201, answer), json_response(201, answer))
92
+ client = Calotype(api_key="", transport=transport)
93
+
94
+ new = client.create_key()
95
+ assert new == NewKey(key="cal_new", plan="free", monthly_quota=100, message="This is the only time the key is shown.")
96
+ assert transport.last.method == "POST"
97
+ assert transport.last.url == "https://calotype.dev/v1/keys"
98
+ assert "Authorization" not in transport.last.headers
99
+ assert transport.last_json() == {"ref": "pypi"}
100
+ assert "cal_new" not in repr(new)
101
+ assert client.api_key == "" # the new key is returned, not adopted
102
+
103
+ client.create_key(ref="my-tool", email="someone@example.com")
104
+ assert transport.last_json() == {"ref": "my-tool", "email": "someone@example.com"}
105
+
106
+ client.create_key(ref=None)
107
+ assert transport.last_json() == {}
108
+
109
+
110
+ def test_usage():
111
+ transport = FakeTransport(
112
+ json_response(
113
+ 200,
114
+ {
115
+ "plan": "free",
116
+ "month": "2026-11",
117
+ "used": 7,
118
+ "limit": 100,
119
+ "resets_at": "2026-12-01T00:00:00Z",
120
+ "key_ref": "cal_ab12",
121
+ "email": "s***@example.com",
122
+ "notices": True,
123
+ },
124
+ )
125
+ )
126
+ usage = Calotype("cal_test", transport=transport).usage()
127
+ assert usage == Usage(
128
+ plan="free",
129
+ month="2026-11",
130
+ used=7,
131
+ limit=100,
132
+ resets_at="2026-12-01T00:00:00Z",
133
+ key_ref="cal_ab12",
134
+ email="s***@example.com",
135
+ notices=True,
136
+ )
137
+ assert usage.remaining == 93
138
+ assert transport.last.method == "GET"
139
+ assert transport.last.url == "https://calotype.dev/v1/usage"
140
+ assert transport.last.body is None
141
+ assert transport.last.headers["Authorization"] == "Bearer cal_test"
142
+
143
+
144
+ def test_key_comes_from_the_environment_and_never_shows_in_repr(monkeypatch):
145
+ monkeypatch.setenv("CALOTYPE_API_KEY", " cal_env ")
146
+ transport = FakeTransport(image_response())
147
+ client = Calotype(transport=transport)
148
+ client.screenshot("https://example.com")
149
+ assert transport.last.headers["Authorization"] == "Bearer cal_env"
150
+ assert "cal_env" not in repr(client)
151
+ assert repr(client) == "Calotype(base_url='https://calotype.dev', api_key=set)"
152
+
153
+
154
+ def test_base_url_and_timeout_can_be_changed():
155
+ transport = FakeTransport(image_response())
156
+ Calotype("cal_test", base_url="http://127.0.0.1:8080/", timeout=5, transport=transport).screenshot("https://example.com")
157
+ assert transport.last.url == "http://127.0.0.1:8080/v1/screenshot"
158
+ assert transport.last.timeout == 5
159
+ with pytest.raises(ValueError):
160
+ Calotype("cal_test", base_url="file:///etc")
161
+
162
+
163
+ def test_the_package_is_typed_and_exports_what_it_documents():
164
+ from importlib.resources import files
165
+
166
+ assert files("calotype").joinpath("py.typed").is_file()
167
+ for name in calotype.__all__:
168
+ assert hasattr(calotype, name), name
169
+ assert calotype.__version__ == "0.1.0"
@@ -0,0 +1,141 @@
1
+ from __future__ import annotations
2
+
3
+ import pytest
4
+
5
+ from calotype import (
6
+ APIConnectionError,
7
+ AuthenticationError,
8
+ BlockedTargetError,
9
+ Calotype,
10
+ CalotypeError,
11
+ CaptureFailedError,
12
+ InvalidRequestError,
13
+ PermissionDeniedError,
14
+ QuotaExceededError,
15
+ RateLimitError,
16
+ Response,
17
+ ServerBusyError,
18
+ ServerError,
19
+ )
20
+
21
+ from fakes import FakeTransport, error_response, json_response
22
+
23
+
24
+ def raised(response: Response | Exception) -> CalotypeError:
25
+ client = Calotype("cal_test", transport=FakeTransport(response))
26
+ with pytest.raises(CalotypeError) as caught:
27
+ client.screenshot("https://example.com")
28
+ return caught.value
29
+
30
+
31
+ # Every code the API can answer on these endpoints, with the status it uses (calotype/app.py).
32
+ @pytest.mark.parametrize(
33
+ "status, code, cls",
34
+ [
35
+ (401, "missing_key", AuthenticationError),
36
+ (401, "invalid_key", AuthenticationError),
37
+ (403, "plan_unavailable", PermissionDeniedError),
38
+ (403, "self_serve_disabled", PermissionDeniedError),
39
+ (400, "invalid_parameters", InvalidRequestError),
40
+ (400, "invalid_url", InvalidRequestError),
41
+ (400, "invalid_scheme", InvalidRequestError),
42
+ (400, "invalid_json", InvalidRequestError),
43
+ (400, "invalid_email", InvalidRequestError),
44
+ (400, "blocked_target", BlockedTargetError),
45
+ (422, "blocked_target", BlockedTargetError),
46
+ (400, "dns_error", CaptureFailedError),
47
+ (422, "target_unreachable", CaptureFailedError),
48
+ (422, "page_too_large", CaptureFailedError),
49
+ (504, "timeout", CaptureFailedError),
50
+ (429, "quota_exceeded", QuotaExceededError),
51
+ (429, "rate_limited", RateLimitError),
52
+ (503, "busy", ServerBusyError),
53
+ (500, "internal_error", ServerError),
54
+ ],
55
+ )
56
+ def test_each_error_code_has_its_class(status, code, cls):
57
+ error = raised(error_response(status, code, "What went wrong."))
58
+ assert type(error) is cls
59
+ assert error.code == code
60
+ assert error.status == status
61
+ assert error.message == "What went wrong."
62
+ assert str(error) == f"{code}: What went wrong."
63
+
64
+
65
+ def test_an_unknown_code_falls_back_on_the_status():
66
+ assert type(raised(error_response(400, "brand_new_code", "x"))) is InvalidRequestError
67
+ assert type(raised(error_response(401, "brand_new_code", "x"))) is AuthenticationError
68
+ assert type(raised(error_response(403, "brand_new_code", "x"))) is PermissionDeniedError
69
+ assert type(raised(error_response(418, "brand_new_code", "x"))) is CalotypeError
70
+ assert type(raised(error_response(503, "billing_unavailable", "x"))) is ServerError
71
+
72
+
73
+ def test_an_answer_that_is_not_the_api_error_shape():
74
+ for body in (b"<html>bad gateway</html>", b"[1, 2]", b'{"error": "nope"}', b""):
75
+ error = raised(Response(502, {"content-type": "text/html"}, body))
76
+ assert type(error) is ServerError
77
+ assert (error.code, error.status, error.message) == ("", 502, "HTTP 502")
78
+ assert str(error) == "HTTP 502"
79
+
80
+
81
+ def test_invalid_parameters_lists_the_fields():
82
+ error = raised(
83
+ error_response(
84
+ 400,
85
+ "invalid_parameters",
86
+ "Some parameters are not valid.",
87
+ details=[{"field": "width", "message": "Input should be less than or equal to 3840"}],
88
+ )
89
+ )
90
+ assert isinstance(error, InvalidRequestError)
91
+ assert error.details == [{"field": "width", "message": "Input should be less than or equal to 3840"}]
92
+ assert str(error) == (
93
+ "invalid_parameters: Some parameters are not valid. width: Input should be less than or equal to 3840"
94
+ )
95
+ assert raised(error_response(400, "invalid_url", "The URL is not valid.")).details == []
96
+
97
+
98
+ def test_quota_exceeded_carries_the_counts():
99
+ error = raised(
100
+ error_response(
101
+ 429, "quota_exceeded", "This key has used its 100 screenshots.",
102
+ plan="free", limit=100, used=100, resets_at="2026-12-01T00:00:00Z",
103
+ )
104
+ )
105
+ assert isinstance(error, QuotaExceededError)
106
+ assert (error.plan, error.limit, error.used, error.resets_at) == ("free", 100, 100, "2026-12-01T00:00:00Z")
107
+
108
+
109
+ def test_retry_after_from_the_body_or_the_header():
110
+ limited = raised(error_response(429, "rate_limited", "Too many keys.", {"retry-after": "30"}, retry_after_s=1800))
111
+ assert limited.retry_after == 1800
112
+ busy = raised(error_response(503, "busy", "All renderers are busy. Retry shortly.", {"retry-after": "5"}))
113
+ assert busy.retry_after == 5
114
+ assert raised(error_response(500, "internal_error", "x")).retry_after is None
115
+
116
+
117
+ def test_no_key_fails_before_any_request(monkeypatch):
118
+ monkeypatch.delenv("CALOTYPE_API_KEY", raising=False)
119
+ transport = FakeTransport()
120
+ client = Calotype(transport=transport)
121
+ for call in (lambda: client.screenshot("https://example.com"), client.usage):
122
+ with pytest.raises(AuthenticationError) as caught:
123
+ call()
124
+ assert caught.value.code == "missing_key"
125
+ assert caught.value.status is None
126
+ assert "create_key" in caught.value.message
127
+ assert transport.requests == []
128
+
129
+
130
+ def test_a_connection_failure_passes_through_as_api_connection_error():
131
+ error = raised(APIConnectionError("Could not reach the Calotype API (TimeoutError)."))
132
+ assert type(error) is APIConnectionError
133
+ assert (error.code, error.status) == ("", None)
134
+
135
+
136
+ def test_a_success_that_is_not_json_is_an_error_not_a_crash():
137
+ client = Calotype("cal_test", transport=FakeTransport(Response(200, {}, b"<html>"), json_response(201, {"plan": "free"})))
138
+ with pytest.raises(CalotypeError, match="not a JSON object"):
139
+ client.usage()
140
+ with pytest.raises(CalotypeError, match="held no key"):
141
+ client.create_key()
@@ -0,0 +1,86 @@
1
+ """The default urllib transport, against a server on the loopback address, and the live smoke test."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import threading
8
+ from http.server import BaseHTTPRequestHandler, HTTPServer
9
+
10
+ import pytest
11
+
12
+ from calotype import APIConnectionError, AuthenticationError, Calotype, InvalidRequestError
13
+
14
+
15
+ class Handler(BaseHTTPRequestHandler):
16
+ seen: list[dict] = []
17
+
18
+ def _answer(self, status: int, content_type: str, body: bytes, **headers: str) -> None:
19
+ self.send_response(status)
20
+ self.send_header("Content-Type", content_type)
21
+ self.send_header("Content-Length", str(len(body)))
22
+ for name, value in headers.items():
23
+ self.send_header(name, value)
24
+ self.end_headers()
25
+ self.wfile.write(body)
26
+
27
+ def do_POST(self) -> None:
28
+ body = json.loads(self.rfile.read(int(self.headers.get("Content-Length", 0))) or b"{}")
29
+ Handler.seen.append({"path": self.path, "headers": dict(self.headers), "body": body})
30
+ if body.get("url") == "bad":
31
+ error = {"error": {"code": "invalid_url", "message": "The URL is not valid."}}
32
+ self._answer(400, "application/json", json.dumps(error).encode())
33
+ else:
34
+ self._answer(200, "image/jpeg", b"\xff\xd8 jpeg", **{"X-Calotype-Usage": "1/100"})
35
+
36
+ def log_message(self, *args) -> None: # keep the test output quiet
37
+ pass
38
+
39
+
40
+ @pytest.fixture()
41
+ def server():
42
+ httpd = HTTPServer(("127.0.0.1", 0), Handler)
43
+ thread = threading.Thread(target=httpd.serve_forever, daemon=True)
44
+ thread.start()
45
+ Handler.seen.clear()
46
+ yield f"http://127.0.0.1:{httpd.server_port}"
47
+ httpd.shutdown()
48
+ httpd.server_close()
49
+
50
+
51
+ def test_urllib_transport_round_trip(server):
52
+ client = Calotype("cal_test", base_url=server, timeout=5)
53
+
54
+ shot = client.capture("https://example.com", format="jpeg")
55
+ assert shot.image == b"\xff\xd8 jpeg"
56
+ assert (shot.content_type, shot.used, shot.limit) == ("image/jpeg", 1, 100)
57
+ seen = Handler.seen[-1]
58
+ assert seen["path"] == "/v1/screenshot"
59
+ assert seen["body"] == {"url": "https://example.com", "format": "jpeg"}
60
+ assert seen["headers"]["Authorization"] == "Bearer cal_test"
61
+ assert seen["headers"]["User-Agent"].startswith("calotype-python/")
62
+
63
+ # An error status is an answer, not a connection failure.
64
+ with pytest.raises(InvalidRequestError) as caught:
65
+ client.screenshot("bad")
66
+ assert (caught.value.code, caught.value.status) == ("invalid_url", 400)
67
+
68
+
69
+ def test_urllib_transport_reports_an_unreachable_server():
70
+ # Bind a port, then close it, so connections to it are refused.
71
+ closed = HTTPServer(("127.0.0.1", 0), Handler)
72
+ port = closed.server_port
73
+ closed.server_close()
74
+ client = Calotype("cal_secret_value", base_url=f"http://127.0.0.1:{port}", timeout=5)
75
+ with pytest.raises(APIConnectionError) as caught:
76
+ client.usage()
77
+ assert "Could not reach the Calotype API" in str(caught.value)
78
+ assert "cal_secret_value" not in str(caught.value)
79
+
80
+
81
+ @pytest.mark.skipif(os.environ.get("CALOTYPE_LIVE") != "1", reason="set CALOTYPE_LIVE=1 to call https://calotype.dev")
82
+ def test_live_placeholder_key_is_refused():
83
+ """The one test that uses the network: a keyless call that creates no key and takes no screenshot."""
84
+ with pytest.raises(AuthenticationError) as caught:
85
+ Calotype("cal_placeholder").usage()
86
+ assert (caught.value.code, caught.value.status) == ("invalid_key", 401)