# humblebundle.py — machine-readable summary

> Unofficial Python client for humblebundle.com. Typed, immutable results.
> Audience: LLM agents and code generators. Human docs: README.md.

## Install

```
pip install humblebundle.py   # Python >= 3.10, requires "requests"
```

## Import surface

```python
import humblebundle
from humblebundle import (
    HumbleBundleClient, AsyncHumbleBundleClient,
    Bundle, BundleItem, ChoiceGame, HumbleChoice, Tier, Money, ProductCollection,
    Category, StoreSort,
    Store, StoreSearch, StoreProduct, StoreProductDetail, StoreSection,
    StorePromotion, StoreDistribution, StoreEdition, StoreLink, CriticReview,
    HumbleBundleError, FetchError, RateLimitError, PageDataError,
    BundleNotFoundError, StoreProductNotFoundError, AgeVerificationError,
    AuthenticationError,
    configure_logging, silence, describe_models,
    bundles, bundle, items, choices,            # module-level convenience functions
    store, store_product, store_search,
)
```

`humblebundle.__version__` is the installed version.

## Canonical usage

```python
from humblebundle import HumbleBundleClient

client = HumbleBundleClient()        # or HumbleBundleClient(timeout=10, retries=2)
bundles = client.bundles("games")    # ProductCollection[Bundle], keyed by product key
bundle  = client.bundle("survival-fittest")   # Bundle with .tiers populated
items   = client.items("survival-fittest")    # ProductCollection[BundleItem]
choice  = client.choices()                    # HumbleChoice (Mapping[str, ChoiceGame])

store   = client.store()                      # Store (Mapping[str, StoreProduct])
game    = client.store_product("cult-of-the-lamb")   # StoreProductDetail
results = client.store_search("witcher", page=1, per_page=25,
                              sort="top-discounts", genres=["rpg"])
```

All calls are synchronous. Wrap with
`AsyncHumbleBundleClient` for `asyncio`. All raise subclasses of
`HumbleBundleError`; no function returns `None` on failure.

## Signatures

```python
HumbleBundleClient(
    *, timeout: float = 30.0, retries: int = 3, user_agent: str | None = None,
    session: requests.Session | None = None, source: HtmlSource | None = None,
    base_url: str = "https://www.humblebundle.com",
    age_gate_birthdate: str | None = "1990-01-01",
    store_search_action: str | None = None,
)

client.bundles(categories: Category | str | Iterable[Category | str] | None = None)
    -> ProductCollection[Bundle]
client.bundle(slug_or_url: str) -> Bundle
client.items(bundle_or_slug: Bundle | str) -> ProductCollection[BundleItem]
client.choices(month: str | None = None, year: int | None = None) -> HumbleChoice
client.store(path_or_url: str = "store") -> Store
client.store_product(slug_or_url: str, *, birthdate: str | None = None) -> StoreProductDetail
client.store_search(
    query: str = "", *, page: int = 1, per_page: int = 25,
    sort: StoreSort | str | None = None,
    genres: Iterable[str] | str | None = None,
    platforms: Iterable[str] | str | None = None,
    delivery_methods: Iterable[str] | str | None = None,
) -> StoreSearch
client.login(username, password, *, authy_token=None, recaptcha_challenge=None,
             recaptcha_response=None) -> None
client.close() -> None          # also via `with HumbleBundleClient() as client:`
```

`categories`: `"games"` (default), `"books"`, `"software"`, `"bundles"`,
`"all"`. Unknown values raise `ValueError`.

`slug_or_url`: `"survival-fittest"`, `"/games/survival-fittest"`,
`"books/some-bundle"`, or a full URL.

`store(path_or_url)`: `"store"` (landing page), `"store/page/summer-sale"`,
`"store/promo/<slug>"`, a bare product slug, or a full URL. An empty path
raises `ValueError`; a page with no product data raises `PageDataError`.

`store_product(slug_or_url, birthdate=...)`: age-restricted products are
unlocked automatically with `age_gate_birthdate` (default `"1990-01-01"`);
pass `birthdate="YYYY-MM-DD"` per call, or construct the client with
`age_gate_birthdate=None` to raise `AgeVerificationError` instead.

`store_search(...)`: `page >= 1`, `1 <= per_page <= 100`, otherwise
`ValueError`. `sort` accepts `"relevance"` (default), `"top-discounts"`,
`"alphabetical"`, `"newest"` and aliases such as `"discounts"`, `"a-z"`,
`"new"`. Filters are sent as Algolia `refinementList` entries (`genres`,
`platforms`, `delivery_methods`). An empty `query` browses the whole store.
The Next.js server-action id used by the search endpoint changes with every
deployment; it is discovered from the site's JavaScript chunks on first use,
cached per client, and can be overridden with `store_search_action=...`.

## Return types — field reference

`ProductCollection[P]` is an immutable `Mapping[str, P]`:
`len()`, `[key]`, iteration over keys, `.values()`, `.items()`,
`dict(collection)`, `.first`, `.titles` (`{key: title}`), `.search(text)`,
`.to_dict(include_raw=False)`.

### `Bundle` (subclass of `Product`)

| field | type |
| --- | --- |
| `key` | `str` (stable product key) |
| `name` | `str` (alias of `key`) |
| `title` | `str \| None` |
| `url`, `product_url` | `str \| None` (absolute) |
| `slug`, `category`, `product_type` | `str \| None` |
| `description`, `headline` | `str \| None` |
| `bundle_types` | `tuple[str, ...]` |
| `logo_image_url`, `thumbnail`, `title_image_url` | `str \| None` |
| `items_count` | `int \| None` |
| `included_item_titles` (alias `highlights`) | `tuple[str, ...]` |
| `price`, `base_price`, `retail_value` | `Money \| None` |
| `on_sale` | `bool \| None` |
| `platforms`, `delivery_methods` | `tuple[str, ...]` |
| `start_date`, `end_date` | `datetime \| None` (UTC-aware) |
| `num_sold` (alias `bundles_sold`) | `int \| None` |
| `tiers` | `tuple[Tier, ...]` (empty unless loaded via `client.bundle`) |
| `raw` | `Mapping` source payload |

Methods/properties: `items() -> ProductCollection[BundleItem]`,
`supports(platform) -> bool`, `is_expired -> bool | None`,
`currency -> str | None`, `stepin()` (deprecated alias of `items()`),
`to_dict(include_raw=False)`, `keys()`, `get(name, default)`.

### `BundleItem`

`key`, `title`, `description`, `image`, `thumbnail`, `msrp: Money|None`,
`developers: tuple[str,...]`, `publishers: tuple[str,...]`,
`delivery_methods`, `platforms`, `item_content_type`, `media: tuple[str,...]`,
`carousel`, `tpkd_skus`, `tier_key`, `tier_sku`, `currency`, `raw`.

### `Tier`

`key`, `name`, `price: Money|None`, `items: tuple[BundleItem,...]`, `raw`.

### `ChoiceGame`

`key`, `title`, `description`, `thumbnail`, `price: Money|None`,
`developers`, `genres`, `delivery_methods`, `platforms`, `media`,
`product_url`, `parent_url`, `product_type`, `end_date`, `on_sale`,
`currency`, `raw`.

### `HumbleChoice` (a `Mapping[str, ChoiceGame]`)

`month: str|None`, `year: int|None`, `url: str|None`,
`games: Mapping[str, ChoiceGame]`, `raw`.
`to_dict(include_raw=False)` returns
`{"month", "year", "url", "games": {key: ChoiceGame dict}}`.

### `Money`

`amount: float|None`, `currency: str|None`; `float(money)`, `str(money)`
(`"19.50 USD"`), `bool(money)`, `to_dict() -> {"amount", "currency"}`,
`Money.from_payload(anything)`.

### `Store` (a `Mapping[str, StoreProduct]`)

`url: str|None`, `sections: tuple[StoreSection, ...]`, `promotions:
tuple[StorePromotion, ...]`, `products: ProductCollection[StoreProduct]`,
`raw`. Methods/properties: `.first`, `.titles`, `.section(name)` (matches the
section key, its title, or the hyphenated title; returns `StoreSection|None`),
`to_dict(include_raw=False)` →
`{"url", "sections": [...], "promotions": [...], "products": {key: ...}}`.

### `StoreSection`

`key: str` (slugified title), `title: str|None`, `layout: str|None`,
`card_count: int|None`, `products: tuple[StoreProduct, ...]`, `raw`.
`to_dict()` → `{"key", "title", "layout", "card_count", "products": [...]}`.

### `StoreProduct` (subclass of `Product`)

| field | type |
| --- | --- |
| `key`, `title`, `slug` | `str` / `str \| None` |
| `url`, `product_url` | `str \| None` (absolute) |
| `category`, `product_type`, `thumbnail`, `title_image_url`, `tag` | `str \| None` |
| `platforms`, `delivery_methods` | `tuple[str, ...]` |
| `price`, `base_price` | `Money \| None` |
| `on_sale` | `bool \| None` |
| `valid_until` | `datetime \| None` |
| `sku` | `str \| None` |
| `choice_discount_eligible` | `bool \| None` |
| `choice_discount_percent` | `int \| None` |
| `items_count` | `int \| None` |

Properties: `currency -> str|None`, `discount_percent -> int|None`
(whole percent off `base_price`).

### `StoreProductDetail` (subclass of `StoreProduct`)

Adds: `description`, `description_text` (HTML-stripped), `developers`,
`publishers`, `genres`, `operating_systems`, `media: tuple[str, ...]` (image and
YouTube URLs), `carousel`, `distributions: tuple[StoreDistribution, ...]`,
`editions: tuple[StoreEdition, ...]`, `critic_reviews: tuple[CriticReview, ...]`,
`links: tuple[StoreLink, ...]`, `dlc: bool|None`, `dlc_base_game`,
`release_tag`, `released_at`, `release_end`, `esrb_rating`, `esrb_descriptors`,
`pegi_rating`, `pegi_descriptors`, `minimum_age: int|None`,
`system_requirements`, `system_requirements_text`, `vr_system_requirements`,
`legal_disclaimer`, `purchase_limit: int|None`, `available: bool|None`,
`region_blocked`, `out_of_keys`, `low_on_keys`, `requires_steam_linking`.
Prices come from the page's separate price block, matched on the product SKU.

### `StoreDistribution`

`key`, `sku`, `platforms: tuple[str,...]`, `via`, `operating_systems`,
`inventory_state`, `region_blocked: bool|None`, `default: bool|None`.

### `StoreEdition`

`key`, `name`, `sku`, `price: Money|None`, `base_price: Money|None`,
`available: bool|None`, `raw`.

### `StoreLink`

`title: str|None`, `url: str|None`.

### `CriticReview`

`source`, `score`, `reviewer`, `text`, `url` (all `str|None`).

### `StorePromotion` (subclass of `Product`)

`key`, `title`, `url`, `slug`, `page_type`, `image`, `thumbnail`, `raw`.

### `StoreSearch` (a `Mapping[str, StoreProduct]`)

`query: str`, `page: int`, `pages: int`, `total: int`, `per_page: int`,
`sort: str|None`, `refinements: Mapping[str, tuple[str, ...]]`,
`facets: Mapping[str, Mapping[str, int]]`, `products: ProductCollection`,
`url: str|None`, `raw`. Methods/properties: `.first`, `.titles`, `.has_next`,
`.has_previous`, `.next_page()`, `.previous_page()` (both raise `ValueError` at
the edge), `to_dict(include_raw=False)` → `{"query", "page", "pages", "total",
"per_page", "sort", "refinements", "facets", "products"}`.

### `StoreSort` (a `str` enum)

`RELEVANCE = "relevance"`, `TOP_DISCOUNTS = "top-discounts"`,
`ALPHABETICAL = "alphabetical"`, `NEWEST = "newest"`;
`StoreSort.coerce(value)` accepts those values plus aliases (`"discounts"`,
`"a-z"`, `"new"`, ...) and `None`; `.request_value` is the string sent to the
site (`""` for relevance, which is omitted from the request).

## JSON

`product.to_dict()` is JSON-serialisable: `Money` → `{"amount", "currency"}`,
`datetime` → ISO-8601 string, tuples → lists, nested models → dicts.
`to_dict(include_raw=True)` adds the untouched payload.
`humblebundle.describe_models()` returns the full schema as a dict; on the CLI,
`humblebundle schema` prints it as JSON.

## CLI

```
humblebundle bundles [CATEGORY ...] [--json] [--fields a,b] [--limit N] [--raw]
humblebundle bundle SLUG [--items] [same output options]
humblebundle items SLUG [same output options]
humblebundle choices [--month M] [--year Y] [same output options]
humblebundle store [PATH] [-s/--section NAME] [same output options]
humblebundle store-product SLUG [--birthdate YYYY-MM-DD] [same output options]
humblebundle store-search [QUERY] [--page N] [--per-page N] [--sort ORDER]
                          [--genre NAME] [--platform NAME] [--delivery NAME]
                          [same output options]
humblebundle schema [--indent N]
humblebundle --version | -v/--verbose | --timeout SECONDS
```

`--json` prints `{product_key: {...}}` (or the `HumbleChoice`/`Store`/
`StoreSearch` dict, which keeps page metadata). `--fields` projects the product
records. Without `--json`, a table is printed. Exit codes: `0` success, `1`
library error (message on stderr), `2` bad usage. `python -m humblebundle` is
equivalent.

## Errors

| exception | meaning |
| --- | --- |
| `HumbleBundleError` | base class for everything below |
| `FetchError` | connection error, timeout, or HTTP status ≥ 400 (`status_code`, `url`) |
| `RateLimitError` | HTTP 429 persisted after retries (`status_code`, `url`) |
| `PageDataError` | page fetched but expected data missing (site changed) |
| `BundleNotFoundError` | bundle page exposed no bundle detail data |
| `StoreProductNotFoundError` | store product page exposed no product data |
| `AgeVerificationError` | store product is age-gated and no birthdate was usable |
| `AuthenticationError` | login rejected / captcha or 2FA required |

Retries (default 3) apply to connection errors and HTTP 429/500/502/503/504 with
exponential backoff and `Retry-After` support.

## Guidance for agents

1. Prefer `client.items(bundle)` over `client.items(slug)` when you already have
   a `Bundle` from `client.bundle(...)` — it reuses the parsed tiers and makes no
   second request.
2. Never assume `price` is a float. Use `price.amount` and `price.currency`.
3. Call `to_dict()` before JSON-encoding models; models are not dicts.
4. Treat `PageDataError` as "upstream layout changed", not as a user error.
5. Reuse a single `HumbleBundleClient` for multiple calls; creating one per call
   discards the connection pool and increases the chance of rate limiting.
6. Public data only — no login is required for `bundles`, `bundle`, `items`,
   `choices`, `store`, `store_product` or `store_search`.
7. Run `humblebundle schema` to refresh field knowledge instead of guessing.
8. `Store`/`StoreSearch` are mappings but also carry page metadata; iterate
   `.products` (or the mapping) for products and read `.sections`, `.facets`,
   `.total` for context.
9. `client.store_search("")` browses the whole store; use `sort=` and the
   `genres`/`platforms`/`delivery_methods` filters instead of post-filtering.
10. Age-gated store products are handled automatically (a plain
    `age_gate_verified_birthdate` cookie); set
    `age_gate_birthdate=None` to opt out and receive `AgeVerificationError`.

## Source layout

```
humblebundle/
  __init__.py    public exports, version, NullHandler
  client.py      HumbleBundleClient, AsyncHumbleBundleClient
  models.py      Bundle, BundleItem, ChoiceGame, Tier, Money, HumbleChoice,
                 Store, StoreSearch, StoreProduct, StoreProductDetail,
                 StoreSort, describe_models
  get.py         module-level helpers on a per-thread default client
  cli.py         argparse CLI (also `python -m humblebundle`)
  logger.py      configure_logging / silence / get_logger
  exceptions.py  error hierarchy
  _http.py       transport: GET via requests, server-action POST via http.client
  _parser.py     locate feed/tiers/products/store blocks in page data
  _rsc.py        Next.js React Server Components payload reader
  _values.py     URL/date/list/HTML normalisation helpers
  py.typed       PEP 561 marker
tests/           hermetic pytest suite (no network)
```
