Skip to main content

GitHub Release GitHub Activity License

Project Maintenance BuyMeCoffee

An async Python client for Hatch sleep devices: the Rest and Restore families. It logs in to the Hatch cloud API over HTTP (aiohttp), then talks to each device through its AWS IoT device shadow over MQTT (awsiotsdk). It follows Home Assistant's guide to API libraries and is the library behind the ha_hatch integration.

Much of the protocol knowledge is ported from homebridge-hatch-baby-rest.

Supported Devices

get_rest_devices() returns one object per device on the account, picked by the device's Hatch product:

Device product Class Highlights
Rest Mini restMini RestMini sound track and volume
Rest+ restPlus RestPlus sound, volume, power, light color
Rest 2nd gen / Rest+ 2nd gen riot, riotPlus RestIot sound, light, clock, toddler lock, favorites
Rest Baby restBaby RestBaby sound, light, clock, toddler lock, favorites
Restore (1st gen, original) restore Restore routines, light, sound, clock, alarms; see docs/restore.md
Restore (1st gen) restoreIot RestoreIot light, clock, favorites, alarms
Restore (V4) restoreV4 RestoreV4 same as RestoreV5
Restore 3 restoreV5 RestoreV5 light, sound, clock schedule and tap-to-show, favorites, alarms

RestDevice is the union of these classes. An unrecognised product falls back to RestMini.

Installation

pip install hatch-rest-api

Requires Python 3.14.

Basic Usage

import asyncio

from aiohttp import ClientSession

from hatch_rest_api import RestIot, get_rest_devices


async def main() -> None:
    async with ClientSession() as session:
        api, mqtt_connection, devices, expiration = await get_rest_devices(
            email="you@example.com",
            password="your-password",
            client_session=session,
        )
        try:
            for device in devices:
                print(repr(device))  # <RestIot device_name='Nursery' thing_name='...'>
                print(device.as_dict())  # the device's current state as a dict

                # Called after every state update reported by the device.
                device.register_callback(lambda: print("updated"))

                if isinstance(device, RestIot):
                    # Device commands block on the MQTT publish, so run them in a thread.
                    await asyncio.to_thread(device.set_volume, 30)
        finally:
            for device in devices:
                await asyncio.to_thread(device.unsubscribe)
            await asyncio.to_thread(lambda: mqtt_connection.disconnect().result())


asyncio.run(main())

get_rest_devices() returns:

  • api: the Hatch HTTP client, for favorites, routines and alarm requests.
  • mqtt_connection: the shared AWS IoT connection. Disconnect it when you are done.
  • devices: one RestDevice per supported device.
  • expiration: when the AWS credentials expire, as a Unix timestamp. Call get_rest_devices() again before then to get a fresh connection and new device objects.

Reading state

Each device mirrors its AWS IoT shadow. State such as is_on, volume, audio_track, is_light_on or is_clock_on (which fields exist depends on the class) updates as the device reports changes. register_callback() runs a callback after each update, and remove_callback() removes it. as_dict() returns the whole state as a dict, which is useful for diagnostics; str(device) prints the same.

Sending commands

Commands such as set_volume(), set_color(), set_audio_track(), set_clock() and set_favorite() publish a desired-state update to the device's shadow. They are synchronous and wait up to 10 seconds for MQTT to acknowledge the publish, so in async code run them with asyncio.to_thread() or your framework's executor. The new state arrives back through the shadow and triggers your callbacks.

Alarm methods, such as refresh_alarms() and set_alarm_enabled(), go through the Hatch HTTP API and are async.

Errors

The library's own errors subclass BaseError:

Error Raised when
AuthError Hatch reports the session is invalid (error code 1001). Log in again.
RateError Hatch answers HTTP 429. Back off before retrying. Hatch.content() retries with exponential backoff on its own; other calls raise straight away.
DeviceSyncError A device does not confirm a change it had to apply over MQTT (original Restore alarms).
BaseError The account has no supported devices.

Other failures from the Hatch HTTP API, such as an error response or a body that isn't JSON, raise aiohttp.ClientError. MQTT failures raise the AWS IoT SDK's own exceptions.

Development

scripts/setup   # creates .venv with Python 3.14 and installs prek hooks
scripts/lint    # prek (ruff, codespell, actionlint, file checks) and mypy --strict
scripts/test    # pytest with coverage

The test suite needs no network access. See AGENTS.md for the codebase layout and conventions, and RELEASE.md for how releases are cut from Conventional Commit messages.

Live Smoke Test

The live smoke test connects to a real Hatch account, discovers its devices, connects them to AWS IoT, prints their shadow state, listens for real-time shadow updates, and sends one sample control update to the first device.

scripts/live_smoke_test

Use it only when you want to exercise the live Hatch APIs. The sample control update writes the first device's current volume back to it, so the setting is unchanged but the control path and shadow update are exercised. The script then waits 5 minutes so MQTT messages can be observed.

To run non-interactively, put credentials in a local env file and pass it with --credentials-file. Supported keys are HATCH_EMAIL/HATCH_PASSWORD (see scripts/hatch_rest_api.env.example); TOML and JSON files with email/password keys also work, as do HATCH_EMAIL/HATCH_PASSWORD environment variables.

scripts/live_smoke_test --credentials-file scripts/hatch_rest_api.env --output-file /private/tmp/hatch_rest_api.txt --read-only

Other options:

  • --output-file writes a full transcript (stdout, stderr, and logs) for later API debugging or fixture updates.
  • --read-only skips the sample control update while still loading devices and listening for MQTT messages.

Metadata

Release files for hatch-rest-api 1.42.3

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for hatch-rest-api 1.42.3
File Size Uploaded Provenance Actions
hatch_rest_api-1.42.3.tar.gz 101.2 kB Without provenance Details for hatch_rest_api-1.42.3.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for hatch-rest-api 1.42.3
File Interpreter ABI Platform Actions
hatch_rest_api-1.42.3-py3-none-any.whl Python 3 none any Details for hatch_rest_api-1.42.3-py3-none-any.whl

Total release size: 169.8 kB

Release files / hatch_rest_api-1.42.3.tar.gz

Download URL hatch_rest_api-1.42.3.tar.gz
Size 101.2 kB
Tags Source
SHA-256 checksum
How to use checksums
fb6a48de8f47c4b54257b5bcd6d8471402832777ad9db6c217c27c277ff3b754
BLAKE2b-256 checksum
How to use checksums
047d5d7895514691b6b9f35a8d8f446ba37bf225b2f12874af415459e7183c5b
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.16

Release files / hatch_rest_api-1.42.3-py3-none-any.whl

Download URL hatch_rest_api-1.42.3-py3-none-any.whl
Size 68.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
973e71c166b36d1e334d46287dc9b91dcc99cd35b5026fcc6e19196a263b6ab1
BLAKE2b-256 checksum
How to use checksums
b3530c3f6b5083dbed09d08673171f1334349da31952ca0eb019d18c10c55c4f
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.16

Security for hatch-rest-api 1.42.3

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

1.42.3 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page