# Python library (/docs/python)

## Install

Needs Python 3.11 or newer.

```sh
pip install bowmark-web bowmark-web-stubs
```

The second package adds types and autocomplete. It is optional.

Create a key on the [keys page](https://bowmark.ai/dashboard/keys) and set it in your
environment. Every call reads it.

```sh
export BOWMARK_API_KEY=bmk_...
```

## Call one function

`bowmark` reaches every function in the library by its path. Each
[site page](/sites) lists a site's functions with their arguments and return types.
Arguments are passed as a dict, the same shape the site page shows.

```python
import asyncio
from bowmark_web import bowmark

async def main() -> None:
    found = await bowmark.providers.steam.searchGames({"query": "portal"})
    appid = found["results"][0]["appid"]
    details = await bowmark.providers.steam.getGameDetails({"appid": appid})
    print(details["game"]["name"], details["game"]["price"])

asyncio.run(main())
```

Function names keep their original spelling (`searchGames`, not `search_games`), so a name
on a site page works as written.

## Several calls in one session

Two `bowmark` calls get two separate sessions. When a flow has a second step that depends on
the first (a cart, a sign-in), use `session()` so every call shares one.

```python
from bowmark_web import session

async with session() as bm:
    found = await bm.providers.gymshark.search({"query": "hoodie"})
    await bm.providers.gymshark.addToCart({"variantId": found["products"][0]["variantId"]})
    cart = await bm.providers.gymshark.getCart()
```

The session closes when the `async with` block ends.

## Run a script

`run()` sends a whole JavaScript script and returns the [response envelope](/docs/responses)
instead of raising. Use it for `read.page` and `browser_agent`, which work only inside a script.

```python
from bowmark_web import run

envelope = await run('return await bowmark.read.page("https://example.com")')
if not envelope["ok"]:
    raise RuntimeError(envelope["error"] or "run failed")
print(envelope["result"]["title"])
```

## Sites that need a sign-in

A call to a signed-in function pauses until the person signs in. It raises
`BowmarkNeedsUserError` with a link. Open it, sign in, and call again: the session is still
open. See [Signed-in sites](/docs/signed-in-sites).

```python
from bowmark_web import BowmarkError, BowmarkNeedsUserError

try:
    friends = await bm.providers.steam.viewFriends({})
except BowmarkNeedsUserError as paused:
    print("Sign in:", paused.handoff["url"])
except BowmarkError as err:
    print(err.code, err)
```

## Errors

| Error                                     | When                                    | What to do                               |
| ----------------------------------------- | --------------------------------------- | ---------------------------------------- |
| `BowmarkNeedsUserError`                   | A call is waiting for a sign-in         | Open `handoff["url"]`, then call again   |
| `BowmarkError`, `code="no_api_key"`       | No key was found                        | Set `BOWMARK_API_KEY` or pass `api_key=` |
| `BowmarkError`, `code="bad_argument"`     | An argument does not match the function | Fix it; the message names the field      |
| `BowmarkError`, `code="unknown_function"` | The function is not in this version     | Check the name, or upgrade the package   |
| `BowmarkError`, any other `code`          | The call failed                         | Branch on `code`; `str(err)` explains it |

## Options

Every entry point takes `api_key=`, `base_url=`, `headers=`, `timeout=` and `on_log=`.
Without `api_key` it reads `BOWMARK_API_KEY` at call time.

Not using Python? Use the [Node library](/docs/node) or the [HTTP API](/docs/http-api).
