Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 61 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,61 @@ result = client.create_image_batch(

`create_image_batch` accepts HTML/CSS and URL requests; use `create_templated_image_batch` for templates. Empty `html` or `url` values in variations are omitted so they can inherit from `default_options`. An empty variation list returns a successful empty result without sending an HTTP request. Options unsupported by the batch API, such as `dedupe_duration_s`, are not serialized. See the [batch API documentation](https://docs.htmlcsstoimage.com/getting-started/using-the-api/#batch-image-creation).

## Recordings

Use `create_recording` with `CreateHtmlCssRecordingRequest` or `CreateUrlRecordingRequest` to record HTML/CSS or a public webpage as MP4, WebM, or GIF:

```python
from html_css_to_image import (
CreateHtmlCssRecordingRequest,
CreateUrlRecordingRequest,
RecordingOutputOptions,
RecordingSimpleScrollAction,
)

result = client.create_recording(CreateUrlRecordingRequest(
url="https://example.com",
duration_ms=10000,
viewport_width=1280,
viewport_height=720,
actions=[RecordingSimpleScrollAction()],
output=RecordingOutputOptions(format="mp4"),
))
if result.success:
print(result.recording_url) # Embed or request directly; it waits until the recording is ready.
else:
print(result.error)

animation = client.create_recording(CreateHtmlCssRecordingRequest(
html="<h1>Hello</h1>",
css="@keyframes fade { from { opacity: 0; } to { opacity: 1; } } h1 { animation: fade 2s; }",
duration_ms=3000,
duration_mode="fixed",
output=RecordingOutputOptions(format="gif", scale=0.5),
))
```

Both request types share browser settings, triggers, ordered actions, and output options. Actions and triggers are typed dataclasses, such as `RecordingClickAction(selector="#start")` and `RecordingElementVisibleTrigger(selector="#ready")`. For JavaScript actions, `if_error=None` fails on a script error; `if_error=[]` ignores errors. Empty branch lists are preserved in JSON.

```python
deleted = client.delete_recording("recording-id")
batch_deleted = client.delete_recording_batch(["first-id", "second-id"])
```

Deletion returns a success response when accepted. `delete_recording_batch` accepts a list or tuple of strings; an empty list returns a successful result without sending an HTTP request. All recording methods return the existing `ApiErrorResponse` on API errors and propagate HTTPX transport failures.

Optional settings use the API defaults. Recordings have no audio. Creation returns an ID, status URL, and recording URL. The `recording_url` can be embedded or requested directly; the request waits until the recording is ready, so checking status is optional.

```python
status = client.fetch_recording_status("recording-id")
if status.success:
print(status.status)
```

`fetch_recording_status` makes one request. HTTP 200 and 202 both return status information; `ready`, `failed`, and `cancelled` are terminal states. An error can describe an earlier, retryable attempt. A successful status fetch can report a failed recording. A status the client does not recognize, such as one added in a newer API version, is reported as `unknown`.

See the [recording guide](https://docs.htmlcsstoimage.com/getting-started/recordings/), [actions reference](https://docs.htmlcsstoimage.com/parameters/actions/), and [trigger reference](https://docs.htmlcsstoimage.com/parameters/trigger/) for the timeline, output options, and examples.

## Signed URLs

The signed URL helpers perform no network request. They create the exact query string, sign it with HMAC-SHA256 using the API key, and return a URL that can be shared without exposing that key.
Expand Down Expand Up @@ -187,7 +242,7 @@ single = client.delete_image("image-id")
batch = client.delete_image_batch(["image-id-1", "image-id-2"])
```

Every successful `2xx` response maps to `DeleteImageSuccessResponse`. API errors use `ApiErrorResponse`, while network failures remain HTTPX exceptions.
Every successful `2xx` response maps to `DeleteImageSuccessResponse`. `delete_image_batch` accepts a list or tuple of strings; an empty list returns a successful result without sending an HTTP request. API errors use `ApiErrorResponse`, while network failures remain HTTPX exceptions.

## HTTP configuration

Expand Down Expand Up @@ -245,11 +300,15 @@ else:
| `create_image_batch(variations, default_options=None)` | `CreateImageBatchResponse` | Sends `POST /v1/image/batch`, unless the list is empty. |
| `create_templated_image_batch(variations, default_options=None)` | `CreateImageBatchResponse` | Sends `POST /v1/image/batch/templated`, unless the list is empty. |
| `delete_image(image_id)` | `DeleteImageResponse` | Sends `DELETE /v1/image/{id}`. |
| `delete_image_batch(image_ids)` | `DeleteImageResponse` | Sends `DELETE /v1/image/batch`. |
| `delete_image_batch(image_ids)` | `DeleteImageResponse` | Sends `DELETE /v1/image/batch`, unless the list is empty. |
| `image_url(image_id, render_options=None)` | `str` | Builds an existing-image URL locally. |
| `generate_templated_image_url(request, render_options=None)` | `str` | Builds and signs a template URL from a request locally. |
| `generate_templated_image_url_from_values(...)` | `str` | Builds and signs a template URL from separate values locally. |
| `generate_create_and_render_url(...)` | `str` | Builds and signs a URL screenshot locally. |
| `create_recording(request)` | `CreateRecordingResponse` | Sends `POST /v1/recording`. |
| `fetch_recording_status(recording_id)` | `RecordingStatusResponse` | Sends `GET /v1/recordings/{id}/status`. |
| `delete_recording(recording_id)` | `DeleteRecordingResponse` | Sends `DELETE /v1/recordings/{id}`. |
| `delete_recording_batch(recording_ids)` | `DeleteRecordingResponse` | Sends `DELETE /v1/recordings/batch`, unless the list is empty. |
| `close()` | `None` | Closes only an SDK-owned HTTP client. |

The package exports typed request, response, PDF, and render/crop models from `html_css_to_image`. Public classes, constructor parameters, attributes, and methods include docstrings for IDE help and generated API documentation.
Expand Down
4 changes: 2 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ build-backend = "hatchling.build"

[project]
name = "html-css-to-image"
version = "0.4.0"
version = "1.0.0"
description = "Official Python client for the HTML/CSS to Image API"
readme = "README.md"
requires-python = ">=3.10"
Expand All @@ -14,7 +14,7 @@ authors = [
]
keywords = ["html-to-image", "screenshot", "hcti", "htmlcsstoimage"]
classifiers = [
"Development Status :: 3 - Alpha",
"Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 3",
Expand Down
72 changes: 72 additions & 0 deletions src/html_css_to_image/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,80 @@
TemplatedBatchImageOptions,
ValidationError,
)
from .recordings import (
BaseCreateRecordingRequest,
CoordinatesScrollTarget,
CreateHtmlCssRecordingRequest,
CreateRecordingRequest,
CreateRecordingResponse,
CreateRecordingSuccessResponse,
CreateUrlRecordingRequest,
DeleteRecordingResponse,
DeleteRecordingSuccessResponse,
PositionScrollTarget,
RecordingAction,
RecordingClickAction,
RecordingDurationMode,
RecordingElementVisibleTrigger,
RecordingError,
RecordingErrorAction,
RecordingExecuteJavaScriptAction,
RecordingFormat,
RecordingFunctionCallTrigger,
RecordingImmediateTrigger,
RecordingLocateSelectorAction,
RecordingMouseButton,
RecordingOutputOptions,
RecordingScrollAction,
RecordingSimpleScrollAction,
RecordingStallAction,
RecordingStatus,
RecordingStatusResponse,
RecordingStatusSuccessResponse,
RecordingTrigger,
ScrollEasing,
ScrollPosition,
ScrollStep,
ScrollTarget,
SelectorScrollTarget,
)

__all__ = [
"BaseCreateRecordingRequest",
"CoordinatesScrollTarget",
"CreateHtmlCssRecordingRequest",
"CreateRecordingRequest",
"CreateRecordingResponse",
"CreateRecordingSuccessResponse",
"CreateUrlRecordingRequest",
"DeleteRecordingResponse",
"DeleteRecordingSuccessResponse",
"PositionScrollTarget",
"RecordingAction",
"RecordingClickAction",
"RecordingDurationMode",
"RecordingElementVisibleTrigger",
"RecordingError",
"RecordingErrorAction",
"RecordingExecuteJavaScriptAction",
"RecordingFormat",
"RecordingFunctionCallTrigger",
"RecordingImmediateTrigger",
"RecordingLocateSelectorAction",
"RecordingMouseButton",
"RecordingOutputOptions",
"RecordingScrollAction",
"RecordingSimpleScrollAction",
"RecordingStallAction",
"RecordingStatus",
"RecordingStatusResponse",
"RecordingStatusSuccessResponse",
"RecordingTrigger",
"ScrollEasing",
"ScrollPosition",
"ScrollStep",
"ScrollTarget",
"SelectorScrollTarget",
"ApiErrorResponse",
"BaseCreateImageRequest",
"BatchCreateImageRequest",
Expand Down
101 changes: 75 additions & 26 deletions src/html_css_to_image/_request_mapper.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
from __future__ import annotations

from collections.abc import Mapping
from dataclasses import fields, is_dataclass
from enum import Enum
from typing import Any

from .models import (
Expand All @@ -18,11 +20,56 @@
RequestOverride,
TemplatedBatchImageOptions,
)
from .recordings import (
CreateHtmlCssRecordingRequest,
CreateRecordingRequest,
CreateUrlRecordingRequest,
)


class RequestMapper:
"""Serialize typed request models for HCTI API operations."""

@classmethod
def map_recording(cls, request: CreateRecordingRequest) -> dict[str, Any]:
"""Serialize a recording without adding defaults or validating API options."""
if not isinstance(
request, (CreateHtmlCssRecordingRequest, CreateUrlRecordingRequest)
):
raise TypeError(f"Unsupported request type: {type(request).__name__}")
payload: dict[str, Any] = cls._recording_value(request)
if isinstance(request, CreateHtmlCssRecordingRequest):
payload.pop("google_fonts", None)
fonts = cls._map_google_fonts(request.google_fonts)
if fonts is not None:
payload["google_fonts"] = fonts
return payload

@classmethod
def _recording_value(cls, value: Any) -> Any:
if isinstance(value, Enum):
return value.value
if is_dataclass(value) and not isinstance(value, type):
return {
item.name: cls._recording_value(getattr(value, item.name))
for item in fields(value)
if getattr(value, item.name) is not None
}
if isinstance(value, Mapping):
return {key: cls._recording_value(item) for key, item in value.items()}
if isinstance(value, (list, tuple)):
return [cls._recording_value(item) for item in value]
return value

@staticmethod
def _map_google_fonts(font_names: list[str] | tuple[str, ...] | None) -> str | None:
fonts: list[str] = []
for font in font_names or ():
processed = font.strip().replace(" ", "+")
if processed and processed not in fonts:
fonts.append(processed)
return "|".join(fonts) if fonts else None

@classmethod
def map_request(
cls,
Expand Down Expand Up @@ -61,19 +108,23 @@ def map_batch_request(

@classmethod
def map_templated_batch_options(
cls, request: TemplatedBatchImageOptions,
cls,
request: TemplatedBatchImageOptions,
) -> dict[str, Any]:
if not isinstance(request, TemplatedBatchImageOptions):
raise TypeError("Template batches require TemplatedBatchImageOptions")
return cls.without_none({
"template_id": request.template_id,
"template_version": request.template_version,
"template_values": (
dict(request.template_values)
if request.template_values is not None else None
),
"format": request.format,
})
return cls.without_none(
{
"template_id": request.template_id,
"template_version": request.template_version,
"template_values": (
dict(request.template_values)
if request.template_values is not None
else None
),
"format": request.format,
}
)

@classmethod
def common_payload(
Expand Down Expand Up @@ -135,14 +186,9 @@ def _map_html_request(
payload["html"] = request.html or None if in_batch else request.html
payload["css"] = request.css

if request.google_fonts:
fonts: list[str] = []
for font in request.google_fonts:
processed = font.strip().replace(" ", "+")
if processed and processed not in fonts:
fonts.append(processed)
if fonts:
payload["google_fonts"] = "|".join(fonts)
fonts = cls._map_google_fonts(request.google_fonts)
if fonts is not None:
payload["google_fonts"] = fonts

return cls.without_none(payload)

Expand Down Expand Up @@ -183,14 +229,17 @@ def _map_url_request(
@staticmethod
def _map_request_overrides(rules: list[RequestOverride]) -> list[dict[str, Any]]:
return [
RequestMapper.without_none({
"action": rule.action.value,
"url": rule.url,
"resource_types": (
[resource_type.value for resource_type in rule.resource_types]
if rule.resource_types is not None else None
),
})
RequestMapper.without_none(
{
"action": rule.action.value,
"url": rule.url,
"resource_types": (
[resource_type.value for resource_type in rule.resource_types]
if rule.resource_types is not None
else None
),
}
)
for rule in rules
]

Expand Down
Loading
Loading