> ## Documentation Index
> Fetch the complete documentation index at: https://docs.hotkey.so/llms.txt
> Use this file to discover all available pages before exploring further.

# Python

> The official client for the HTTP API, sync and async, for Python 3.10 and later. Typed objects, retries, idempotency keys, paging and webhook signatures.

> [!NOTE]
>
> The Python client isn't on PyPI yet. Until it is, use the [TypeScript client](https://docs.hotkey.so/sdk/typescript.md) or the [HTTP API](https://docs.hotkey.so/api.md) directly. Once it is, `pip install hotkey-sdk`.

Its one dependency is httpx. The package is imported as `hotkey`.

```python theme={null}
from hotkey import Hotkey

hotkey = Hotkey()  # reads HOTKEY_KEY
```

`Hotkey("hk_live_…", base_url=...)` takes the key and host instead. `base_url` is `https://console.hotkey.so` by default, and `HOTKEY_BASE_URL` sets it too. `with Hotkey() as hotkey:` closes its connections at the end.

Objects come back as plain dicts, typed as `TypedDict`s in `hotkey.types` (`Browser`, `Ask`, `Event` …), so `browser["id"]` works and your type checker knows the fields.

## One browser per end user

```python theme={null}
# Made the first time, the same browser every time after.
browser = hotkey.browsers.get_or_create(
    external_id="user_829", name="Acme for Ada (829)", metadata={"plan": "pro"}, time_zone="Europe/Paris",
)

# A key for this user's agent: on MCP and /v1 it reaches this browser alone.
agent_key = hotkey.agent_keys.create(name="Agent for user_829", browser=browser["id"])

# The first sign-in. Send ask["link"] to the user.
ask = hotkey.asks.create(
    browser=browser["id"],
    url="https://www.linkedin.com/login",
    reason="Sign in to LinkedIn so we can post for you",
    return_url="https://app.acme.com/connected?user=829",
)

ended = hotkey.asks.wait(ask["id"])  # or the ask.done webhook
print(ended["status"])  # done, cancelled, expired or tab_closed
```

`get_or_create` makes the browser, or, when one already has that `external_id` (409 `browser_exists`), returns that one. The same steps with webhooks are in the package's `examples/per_end_user.py`, and on [One browser per end user](https://docs.hotkey.so/per-end-user.md).

## Async

`AsyncHotkey` has the same methods, awaited. A list method returns a pager: `await` it for one page, or `async for` over it for every item.

```python theme={null}
from hotkey import AsyncHotkey

async with AsyncHotkey() as hotkey:
    browser = await hotkey.browsers.get_or_create(external_id="user_829")
    async for b in hotkey.browsers.list(q="plan:pro"):
        print(b["external_id"])
```

## What the client does for you

* **Idempotency keys.** Every `POST` and `PATCH` carries an `Idempotency-Key`. The client makes one per call and sends the same key with each retry of that call, so a retry never makes a second browser or ask. Pass `idempotency_key="browser-user_829"` to choose it.
* **Retries.** A 429 or 503 (`rate_limited`, `browsers_busy`, `server_busy`, `restarting`) means nothing ran: the client waits its `Retry-After` and sends it again. So does 409 `idempotency_key_in_use`. A lost connection, a timeout, or a 500, 502 or 504 is tried again with backoff only when that is safe: a `GET`, or a write with its key. `max_retries` is 3; a `Retry-After` longer than `max_retry_wait` (60 s) is raised instead of waited out. The wrong-key lockout (429 `too_many_attempts`) is never retried.
* **Timeouts.** Each try gives up after `timeout`, 90 s by default, since a wake may wait 20 s for a place.
* **Paging.** Iterating over a list goes through every page; `.data` is the page itself.

```python theme={null}
hotkey = Hotkey(max_retries=5, on_response=lambda r: print(r.method, r.path, r.status, r.request_id, r.retry_in_s))
```

`on_response` is called after every try, retries included, for logs and metrics.

## Errors

Every error answer is raised as a subclass of `HotkeyError` chosen by status, with the fields of [the error body](https://docs.hotkey.so/api.md#errors): `InvalidRequestError` (400, 405), `AuthenticationError` (401), `PlanLimitError` (402), `PermissionDeniedError` (403), `NotFoundError` (404), `ConflictError` (409), `RateLimitError` (429), `UpstreamError` (502), `BusyError` (503), `InternalServerError` (other 5xx), and `APIConnectionError` when no answer came (`code` is `connection_failed` or `timeout`).

```python theme={null}
from hotkey import ConflictError

try:
    hotkey.asks.cancel(ask_id)
except ConflictError as e:
    if e.code != "ask_resolved":  # it ended already
        raise
```

Each has `status`, `type`, `code`, `param`, `request_id`, `retry_after` and `body`, the whole error object with the fields some codes add (`browser` on `browser_exists`, `limit` on `browsers_busy`). Branch on `code`.

## Lists

```python theme={null}
page = hotkey.browsers.list(q="plan:pro", limit=50)
page.data, page.has_more, page.next_cursor
next_page = page.next_page()

for b in hotkey.browsers.list(metadata={"plan": "pro"}, state="awake"):
    print(b["external_id"])
```

[Events](https://docs.hotkey.so/api.md#events) go oldest first. `events.follow()` reads the log as it grows, from now or after an event id you kept:

```python theme={null}
for event in hotkey.events.follow(type="ask.*", after=last_seen_id):
    last_seen_id = event["id"]
```

## Updates

Arguments left at `None` are not sent. Inside `metadata`, `None` removes that key, as the API's `null` does. To clear a field itself, pass `CLEAR`:

```python theme={null}
from hotkey import CLEAR

hotkey.browsers.update(browser_id, metadata={"plan": None, "region": "eu"}, time_zone=CLEAR)
```

## Webhooks

Pass the raw body, before any JSON parsing, the `Hotkey-Signature` header and the endpoint's secret:

```python theme={null}
from flask import Flask, request
from hotkey import WebhookSignatureError, construct_event

app = Flask(__name__)

@app.post("/hotkey")
def hotkey_webhook():
    try:
        event = construct_event(request.get_data(), request.headers.get("Hotkey-Signature"), WEBHOOK_SECRET)
    except WebhookSignatureError:
        return "", 400  # missing, wrong or older than 5 minutes
    if event["type"] == "ask.done":
        queue_connected(event["browser"]["external_id"], event["data"]["ask"])  # answer first, work after
    return "", 200
```

`verify_signature` answers True or False instead. `sign_payload(body, secret)` makes a header for your receiver's own tests. The same functions are on the client as `hotkey.webhooks`.

## Every method

| Method | Route |
| - | - |
| `account.get()` | `GET /v1/account` |
| `workspace.get()`, `workspace.update(phone_alerts=)` | `GET`, `PATCH /v1/workspace` |
| `browsers.create(...)`, `get_or_create(external_id=, ...)` | `POST /v1/browsers` |
| `browsers.list(external_id=, q=, metadata=, state=, limit=, starting_after=)`, `find_by_external_id(id)` | `GET /v1/browsers` |
| `browsers.get(id)`, `update(id, ...)`, `delete(id)` | `GET`, `PATCH`, `DELETE /v1/browsers/{id}` |
| `browsers.wake(id)`, `sleep(id)` | `POST /v1/browsers/{id}/wake`, `/sleep` |
| `browsers.tabs(id)`, `asks(id)`, `downloads(id)` | `GET /v1/browsers/{id}/tabs`, `/asks`, `/downloads` |
| `browsers.set_onepassword(id, token=...)`, `get_onepassword(id)`, `delete_onepassword(id)` | `PUT`, `GET`, `DELETE /v1/browsers/{id}/onepassword` |
| `asks.create(browser=, reason=, url=, tab=, timeout_minutes=, return_url=)`, `list(browser=, status=)`, `get(id)` | `POST`, `GET /v1/asks` |
| `asks.cancel(id, note=)`, `new_link(id)`, `wait(id)` | `POST /v1/asks/{id}/cancel`, `/link` |
| `downloads.list(browser)`, `get(id)`, `content(id)`, `delete(id)` | `/v1/downloads/{id}`, `/content` |
| `events.list(browser=, type=)`, `follow()` | `GET /v1/events` |
| `agent_keys.create(name=, browser=)`, `list(browser=)`, `get(id)`, `delete(id)` | `/v1/agent_keys` |
| `webhook_endpoints.create(url=, events=, description=, browser=)`, `list()`, `get(id)`, `update(id, ...)`, `delete(id)` | `/v1/webhook_endpoints` |

`hotkey.request(method, path, query=..., body=...)` calls any other route with the same retries and errors.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.