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.1

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.1
File Size Uploaded Provenance Actions
hatch_rest_api-1.42.1.tar.gz 98.7 kB Without provenance Details for hatch_rest_api-1.42.1.tar.gz

Built distribution (wheel)

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

Total release size: 170.4 kB

Release files / hatch_rest_api-1.42.1.tar.gz

Download URL hatch_rest_api-1.42.1.tar.gz
Size 98.7 kB
Tags Source
SHA-256 checksum
How to use checksums
5eb6be88f6dd98395a28748e8c148f16996d69c1f948ccf819c49b9fcace1758
BLAKE2b-256 checksum
How to use checksums
fb0a8f51acc66258df68e731935bfdaef79616122f922c798b142012cb9dabde
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.1-py3-none-any.whl

Download URL hatch_rest_api-1.42.1-py3-none-any.whl
Size 71.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
1821dc79e1405fe90b8dc0e8a6394f4b1cf87274f40de2ac0972ae45b51eaba2
BLAKE2b-256 checksum
How to use checksums
00cb85ecfb4eeea89303b168c9651d3bf8aa61c40b89207c99bb4c58ae892e0e
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.1

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.1 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