Skip to main content

pyatv-http

An HTTP interface for controlling Apple TVs, built on top of pyatv.

Please refer to the API documentation for the full, up-to-date list of endpoints and schemas.

Features

  • GET /<name>/power-state — reads the current power state without changing it.
  • PUT /<name>/power-state (body {"power_state": "on"} or {"power_state": "off"}) — checks the Apple TV's current power state and only sends a command if it differs from the desired state. POST is also accepted as an identical alias, for clients/platforms that can't issue PUT requests.
  • GET /devices — lists the devices available in the config file. Public, no token required.
  • GET /health — unauthenticated liveness check, for load balancers/uptime monitors.
  • GET /status / GET /stats — optional, opt-in public status page (HTML) and matching JSON endpoint showing recent command activity and success/error counts. See Status page.
  • Every other request (reading/setting power state) requires a bearer token, configured as a list of accepted tokens in the config file.
  • Config-driven: one TOML file lists the port to listen on, accepted API tokens, the paired devices, and optional status-page settings.
  • Pairing stays out-of-band, via pyatv's own atvremote CLI; a pyatv-http gen-config helper turns a paired device's stored credentials into a config snippet.

Setup

1. Find your Apple TV

uvx --from pyatv atvremote scan

This lists every Apple TV on the network along with its identifiers, IP address, and which protocols it supports (AirPlay, Companion, etc).

2. Pair with atvremote

Power control uses the Companion protocol, and pyatv-http talks to the device over AirPlay for the initial handshake, so pair both:

uvx --from pyatv atvremote --id <device-identifier> pair --protocol airplay
uvx --from pyatv atvremote --id <device-identifier> pair --protocol companion

Follow the on-screen PIN prompt for each. Credentials are stored in pyatv's storage file (default ~/.pyatv.conf).

3. Generate a config entry

uv run pyatv-http gen-config \
  --identifier <device-identifier> \
  --address <device-ip-or-hostname> \
  --key living_room

<device-identifier> and <device-ip-or-hostname> come from the scan output in step 1; --key is whatever short name you want to use in URLs (--name sets the human-readable display name too, defaulting to --key).

This prints a [devices.living_room] TOML block built from the stored pairing. Paste it into your config file (see below). If the identifier doesn't match any paired device, the command lists the identifiers it does have on file.

4. Write the config file

port = 8080

[auth]
tokens = ["a-long-random-token"]

[status]
enabled = true
history_size = 100

[devices.living_room]
name = "Living Room"
identifier = "AA:BB:CC:DD:EE:FF"
address = "10.0.0.5"

[devices.living_room.protocols.airplay]
identifier = "AA:BB:CC:DD:EE:FF"
credentials = "..."

[devices.living_room.protocols.companion]
identifier = "11:22:33:44:55:66"
credentials = "..."
  • port — port the HTTP server listens on. Optional, defaults to 8080.
  • [auth].tokens — required, non-empty list of bearer tokens accepted on every request (see API below). Generate one with e.g. python3 -c "import secrets; print(secrets.token_urlsafe(32))".
  • The [devices.<key>] table key (living_room above) is the URL path segment used in requests, e.g. PUT /living_room/power-state.
  • identifier — the device's main pyatv identifier (from atvremote scan).
  • address — the Apple TV's IP address or hostname; used to connect directly instead of relying on mDNS discovery at request time.
  • [devices.<key>.protocols.<protocol>] — one block per paired protocol, exactly as generated by gen-config. Supported protocol names: airplay, companion, dmap, mrp, raop.
  • [status] — optional, entirely off by default. enabled turns on the public /status and /stats endpoints (see Status page); history_size caps how many recent commands are kept in memory (default 100).

5. Run the server

uv run pyatv-http serve --config config.toml

--config is optional; if omitted, it defaults to $XDG_CONFIG_HOME/pyatv-http/config.toml, falling back to ~/.config/pyatv-http/config.toml when $XDG_CONFIG_HOME isn't set.

By default the server binds 0.0.0.0; pass --host to bind a specific interface.

API

Every request must include one of the configured tokens as a bearer token:

TOKEN=a-long-random-token

curl -X PUT http://localhost:8080/living_room/power-state \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"power_state": "on"}'

curl -X PUT http://localhost:8080/living_room/power-state \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"power_state": "off"}'

# POST is also accepted, identical to PUT, for clients that can only
# issue GET/POST requests:
curl -X POST http://localhost:8080/living_room/power-state \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"power_state": "on"}'

curl http://localhost:8080/living_room/power-state \
  -H "Authorization: Bearer $TOKEN"

curl http://localhost:8080/devices

curl http://localhost:8080/health

# Fallback for clients that can't set an Authorization header (see
# "Limited HTTP clients" below): access_token in the query string for GET,
# access_token as a JSON body field for POST. Not available for PUT.
curl "http://localhost:8080/living_room/power-state?access_token=$TOKEN"

curl -X POST http://localhost:8080/living_room/power-state \
  -H "Content-Type: application/json" \
  -d '{"power_state": "on", "access_token": "'"$TOKEN"'"}'

GET/PUT/POST /<name>/power-state all return a JSON body: {"device": "living_room", "power_state": "on"}.

GET /devices returns the devices available in the config file:

[{"device": "living_room", "name": "Living Room"}]

GET /devices and GET /health require no token.

Status Meaning
200 Command sent (or no-op, if the device was already in that state)
401 Missing or invalid bearer token
404 No device configured under that name
504 Device could not be found/reached on the network
502 pyatv raised an error while connecting or sending the command

Status page

Set [status] enabled = true in the config file (see Write the config file) to turn on two extra, unauthenticated endpoints for checking on the service at a glance:

  • GET /status — an HTML page listing the configured devices, per-device and total success/error command counts, and the most recent commands (time, device, command, result, detail).

  • GET /stats — the same data as JSON, for scripts or monitoring:

    {
      "totals": { "living_room": { "success": 12, "error": 1 } },
      "global_totals": { "success": 12, "error": 1 },
      "recent": [
        {
          "timestamp": "2026-07-26T15:00:00+00:00",
          "device": "living_room",
          "command": "set_power_state",
          "ok": true,
          "detail": "on"
        }
      ]
    }
    

Both are 404 when [status].enabled is left at its default (false). History is kept in memory only (up to history_size entries) and resets on restart — there's no persistence across process restarts.

Interactive API docs

FastAPI auto-generates interactive documentation for the running server:

  • GET /docs — Swagger UI (use the "Authorize" button to set your bearer token, then try requests directly from the browser).
  • GET /redoc — ReDoc view of the same schema.
  • GET /openapi.json — the raw OpenAPI schema.

These three routes are not themselves behind the bearer-token check.

A static, always-up-to-date copy of the same schema (rendered with Redoc) is published on every release to hugoh.github.io/pyatv-http — handy for browsing the API without a server running.

Limited HTTP clients (e.g. Hubitat Rule Machine)

A lot of home-automation "rule engine" style integrations — Hubitat's Rule Machine is the one that prompted this — can only fire GET and POST requests, and can't attach a custom Authorization header to them. Two things in this API exist specifically to accommodate that:

  1. POST is a full alias for PUT on /<name>/power-state. State changes normally belong on PUT (it's idempotent and semantically correct — "set this resource to this value"), but any client that can only do GET/POST can use POST with the exact same body and get identical behavior.

  2. The bearer token can be passed in-band instead of as a header, as a fallback that's only checked when no valid Authorization header is present. This follows RFC 6750 (OAuth 2.0 Bearer Token Usage) sections 2.2 and 2.3, which define access_token as the parameter name for exactly this case:

    • GET requests: ?access_token=... query parameter.
    • POST requests: "access_token" field in the JSON body, alongside power_state.

    This fallback is deliberately not available on PUT — PUT stays the strict, header-only, "do it the correct way" method. If your client can set a custom header, prefer PUT with an Authorization header; the fallback exists only for clients that genuinely can't.

Security note: a token in a URL or a JSON body is more likely to end up somewhere you don't want it — server access logs, browser history, an intermediate proxy's logs — than one in an Authorization header. Only rely on this fallback when pyatv-http is reachable exclusively on a trusted local network (the normal setup for a Hubitat hub talking to a LAN service, not something exposed to the internet), and consider using a token dedicated to that integration so it can be rotated on its own if it ever leaks.

Notes

  • Each request opens a fresh connection to the Apple TV, checks its current power state, and only sends the power command if it differs from the desired state — there's no persistent connection or background polling.
  • Pairing is entirely out-of-band via atvremote; this project never performs the pairing handshake itself.

Development

uv sync
uv run pytest   # or: mise run test
hk check --all

Metadata

Release files for pyatv-http 0.4.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 pyatv-http 0.4.1
File Size Uploaded Provenance Actions
pyatv_http-0.4.1.tar.gz 111.4 kB With provenance Details for pyatv_http-0.4.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for pyatv-http 0.4.1
File Interpreter ABI Platform Actions
pyatv_http-0.4.1-py3-none-any.whl Python 3 none any Details for pyatv_http-0.4.1-py3-none-any.whl

Total release size: 127.6 kB

Release files / pyatv_http-0.4.1.tar.gz

Download URL pyatv_http-0.4.1.tar.gz
Size 111.4 kB
Tags Source
SHA-256 checksum
How to use checksums
01e3acd028d340f08b6e084af35145936f696c973d8e35cebde67f0ce680aa94
BLAKE2b-256 checksum
How to use checksums
b90f231a2e3512201707eeea59127cb0234d7573372207ffebe54a1490c42c9d
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.13.13

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.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Jul 26, 2026.

Transparency log

Release files / pyatv_http-0.4.1-py3-none-any.whl

Download URL pyatv_http-0.4.1-py3-none-any.whl
Size 16.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
b6fca826c28572da4581aba1d2cf95872152c9b9890c719e37bd5c23e521176f
BLAKE2b-256 checksum
How to use checksums
57cc2da5c45a0a27960aa9b17bd6aaa9232be02d34deecbc2c493daaf27e42de
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.13.13

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.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Jul 26, 2026.

Transparency log

Security for pyatv-http 0.4.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.

Full provenance

All 2 files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for pyatv_http-0.4.1.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Jul 26, 2026.

Transparency log

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.

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