Metadata-Version: 2.5
Name: flipzi
Version: 0.2.0
Summary: Official Python client for the Flipzi Data API: trading card prices, eBay sold comps, Cardmarket conditions, price history and market movers for Pokémon, Magic, Yu-Gi-Oh!, One Piece, Lorcana and more.
Project-URL: Homepage, https://flipzi.io/docs/
Project-URL: Documentation, https://flipzi.io/docs/
Project-URL: Repository, https://gitlab.com/flipzi/sdk
Project-URL: Issues, https://gitlab.com/flipzi/sdk/-/issues
Project-URL: Changelog, https://gitlab.com/flipzi/sdk/-/blob/main/python/CHANGELOG.md
Author-email: Flipzi <hello@flipzi.io>
License-Expression: MIT
License-File: LICENSE
Keywords: api client,card prices,cardmarket,ebay,flipzi,lorcana,mtg,one piece,pokemon,pokemon tcg,sdk,sold prices,tcg,trading cards,yugioh
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Software Development :: Libraries
Classifier: Typing :: Typed
Requires-Python: >=3.9
Requires-Dist: httpx<1,>=0.23
Provides-Extra: dev
Requires-Dist: build>=1; extra == 'dev'
Requires-Dist: mypy>=1.5; extra == 'dev'
Requires-Dist: pytest>=7; extra == 'dev'
Requires-Dist: pyyaml>=6; extra == 'dev'
Requires-Dist: twine>=5; extra == 'dev'
Description-Content-Type: text/markdown

# flipzi

The official Python client for the [Flipzi Data API](https://flipzi.io/docs/): trading
card prices, eBay sold prices across 8 marketplaces, Cardmarket offers by condition,
price history, PSA population and market movers. It covers Pokémon (English, Japanese and
Chinese), Magic, Yu-Gi-Oh!, One Piece, Lorcana, Riftbound, Dragon Ball, Digimon, Gundam,
Star Wars: Unlimited, Flesh and Blood and more.

- Sync and async clients (`Flipzi`, `AsyncFlipzi`), built on `httpx`.
- Fully typed: responses are `TypedDict`s generated from the API's OpenAPI spec, and the package ships `py.typed`.
- Retries on 429 and 5xx with backoff, and honours `Retry-After`.
- Generators for paged endpoints, and bulk helpers that split requests to your plan's cap.
- Python 3.9+.

```sh
pip install flipzi
```

## First price in three lines

```python
from flipzi import Flipzi
flipzi = Flipzi(api_key="fz_live_...")
print(flipzi.price("0908653a-ce24-4d7e-811e-78c2935bd822")["data"]["prices"][0]["price_formatted"])
```

Get a free key (no card needed) at [flipzi.io/account/register?product=data](https://flipzi.io/account/register?product=data).
If you leave out `api_key`, the client reads `FLIPZI_API_KEY` from the environment.

Don't have a card id? Search for one:

```python
card = flipzi.search("charizard ex", game="pokemon")["data"][0]
card["id"], card["name"], card["set"]["name"], card["number"]
```

Async works the same way:

```python
import asyncio
from flipzi import AsyncFlipzi

async def main():
    async with AsyncFlipzi() as flipzi:
        res = await flipzi.price("0908653a-ce24-4d7e-811e-78c2935bd822")
        print(res["data"]["prices"][0]["price_formatted"])

asyncio.run(main())
```

## Methods

Every endpoint has one method. Each returns the API's JSON body as a dict, typed with a
`TypedDict` from `flipzi.models`.

| Method | Endpoint |
|---|---|
| `health()` | `GET /v1/meta/health` (no key needed) |
| `usage()` | `GET /v1/meta/usage` (free; still answers when you are over quota) |
| `games()` | `GET /v1/catalog/games` |
| `sets(game)` / `iter_sets(game)` | `GET /v1/catalog/sets` |
| `set_cards(set_id)` / `iter_set_cards(set_id)` | `GET /v1/catalog/sets/{set_id}/cards` |
| `set_analytics(set_id, game=)` | `GET /v1/catalog/sets/{set_id}/analytics` |
| `search(q, game=, ...)` / `iter_search(...)` | `GET /v1/cards/search` |
| `card(card_id)` | `GET /v1/cards/{card_id}` |
| `lookup(pokemontcg_id)` | `GET /v1/cards/lookup` |
| `price(card_id, grade=, currency=)` | `GET /v1/cards/{card_id}/price` |
| `history(card_id, period=)` | `GET /v1/cards/{card_id}/history` |
| `sold(card_id, ...)` | `GET /v1/cards/{card_id}/sold` |
| `marketplaces(card_id, marketplace=, ...)` | `GET /v1/cards/{card_id}/marketplaces` |
| `sales(card_id, ...)` / `iter_sales(card_id, ...)` | `GET /v1/cards/{card_id}/sales` |
| `printings(card_id)` | `GET /v1/cards/{card_id}/printings` |
| `analytics(card_id, grade=)` | `GET /v1/cards/{card_id}/analytics` |
| `cardmarket(card_id, language=, seller_country=)` | `GET /v1/cards/{card_id}/cardmarket` |
| `cardmarket_history(card_id, days=)` | `GET /v1/cards/{card_id}/cardmarket/history` |
| `population(card_id)` | `GET /v1/cards/{card_id}/population` |
| `updates(since)` / `iter_updates(since)` | `GET /v1/cards/updates` |
| `movers(game, window=, direction=)` | `GET /v1/market/movers` |
| `sealed_comparisons(game=, set=)` | `GET /v1/sealed/comparisons` |
| `sealed_comparison(slug)` | `GET /v1/sealed/comparisons/{slug}` |
| `sealed_cardmarket(sealed_id, seller_country=)` | `GET /v1/sealed/{sealed_id}/cardmarket` |
| `bulk_prices(ids, grade=, currency=)` | `POST /v1/cards/bulk` |
| `bulk_analytics(ids, ...)` | `POST /v1/cards/bulk/analytics` |
| `bulk_cardmarket(ids, language=, seller_country=)` | `POST /v1/cards/bulk/cardmarket` |
| `request(method, path, params, json)` | anything else |

Keyword arguments are the API's own parameter names (`page_size`, `grade`, `marketplace`),
so the [API reference](https://flipzi.io/docs/) applies word for word. Which plan each
endpoint needs, and what it costs in units, is listed there.

## Enums

```python
from flipzi import Marketplace, Condition, Currency, Game, Finish, Period, grade

flipzi.sold(card_id, marketplace=Marketplace.EBAY_DE, condition=Condition.NEAR_MINT)
flipzi.price(card_id, grade=grade("PSA", 10), currency=Currency.USD)  # grade "PSA_10"
```

Each enum is a `str` Enum, so `Marketplace.EBAY_DE == "ebay_de"`, and plain strings work
everywhere. Each also has a `Literal` alias (`MarketplaceLiteral` and so on) in
`flipzi.enums`. Grades are open-ended strings (`RAW`, `PSA_10`, `BGS_9.5`): build one with
`grade()`.

## Pagination

```python
for s in flipzi.iter_sets("pokemon"):
    print(s["set_id"], s["name"])

# Every price that changed in the last hour, following the cursor.
from datetime import datetime, timedelta, timezone
since = (datetime.now(timezone.utc) - timedelta(hours=1)).strftime("%Y-%m-%dT%H:%M:%SZ")
for change in flipzi.iter_updates(since):
    print(change["card_id"], change["grade"], change["price_cents"])
```

Async: `async for s in flipzi.iter_sets("pokemon")`. Pass `max_items=n` to stop early.
Every page is one request and is billed as one.

## Bulk

```python
res = flipzi.bulk_prices(ids, grade="RAW", currency="eur")  # any number of ids
res["data"]       # one row per card found
res["not_found"]  # ids with no card
```

Ids are de-duplicated, then sent in chunks of your plan's bulk cap (basic 25, pro 100,
ultra 500 ids a request). The first call learns the cap from the API: an over-cap request
is refused before it is billed, and the refusal names the cap. To skip that probe, pass
`chunk_size=100`. The chunk responses are merged into one.

## Errors

Every failure raises one exception, `FlipziError`:

```python
from flipzi import FlipziError

try:
    flipzi.sold(card_id)
except FlipziError as e:
    e.status      # 403
    e.code        # "PLAN_FEATURE_LOCKED"
    e.message     # "Your plan does not include 'sold_comps'. ..."
    e.details     # {"required_feature": ..., "your_plan": ..., "upgrade_url": ..., "next_step": ...}
    e.request_id  # quote it to support@flipzi.io
    e.next_step   # details["next_step"]
```

It is built from the API's error body, `{"error": {code, message, details, request_id}}`.
When no response arrives at all, `status` is `0` and `code` is `NETWORK_ERROR` or `TIMEOUT`.

## Retries

The client retries 429, 500, 502, 503 and 504 responses, and network errors, twice by
default. It waits `Retry-After` when the API sends one, and otherwise backs off
exponentially with jitter (0.5 s, 1 s, 2 s and so on, capped at 8 s).

- `QUOTA_EXCEEDED` is never retried: the monthly quota does not come back until the 1st.
- A `Retry-After` longer than `max_retry_after` (60 s) raises instead of sleeping.
- Refused requests are not billed.

```python
Flipzi(max_retries=5, max_retry_after=120, timeout=10.0)
flipzi.request("GET", "/v1/catalog/games", max_retries=0)  # per call
```

## Quota and rate limits

Metered responses carry your remaining units and requests in headers. The client parses them:

```python
flipzi.price(card_id)
m = flipzi.last_response
m.quota_remaining, m.quota_limit, m.quota_period   # 249876, 250000, "2026-10"
m.rate_limit_remaining, m.rate_limit_reset, m.request_id
```

`quota_remaining` is the count when the request arrived, before its own cost. With
concurrent calls, use the hook instead, which sees every response:
`Flipzi(on_response=lambda m: print(m.quota_remaining))`. `flipzi.usage()` gives the same
numbers, per key, at no cost.

## Options

| Option | Default | |
|---|---|---|
| `api_key` | `$FLIPZI_API_KEY` | Sent as `X-API-Key`. |
| `base_url` | `https://data.flipzi.io` | API origin. |
| `max_retries` | `2` | Retries after 429, 5xx or a network error. |
| `max_retry_after` | `60` | Longest `Retry-After` (seconds) to sleep through. |
| `timeout` | `30.0` | Seconds, per attempt. |
| `on_response` | | Called with a `ResponseMeta` after every response. |
| `http_client` | | Your own `httpx.Client` / `httpx.AsyncClient` (proxies, transports). |
| `tag_client` | `True` | Sends `X-Flipzi-Client: sdk-python/<version>` (SDK name and version only). |

Use the client as a context manager, or call `close()` (`await aclose()` for async), to
release connections.

## Examples

- [`examples/price_my_collection.py`](examples/price_my_collection.py): values a list of
  cards with quantities and grades, using bulk requests.
- [`examples/ebay_de_vs_uk.py`](examples/ebay_de_vs_uk.py): eBay Germany and UK sold
  prices for one card, side by side, per grade and language.

```sh
FLIPZI_API_KEY=fz_live_... python examples/ebay_de_vs_uk.py
```

## Development

```sh
python -m venv .venv && .venv/bin/pip install -e ".[dev]"
.venv/bin/python scripts/generate.py   # regenerate src/flipzi/models.py from ../spec/openapi.yaml
.venv/bin/python scripts/unasync.py    # regenerate the sync client from the async one
.venv/bin/pytest                       # tests against a local mock server
FLIPZI_API_KEY=fz_live_... .venv/bin/pytest tests/test_live.py   # also hits the real API (~6 units)
```

The mock server replays real responses recorded into the repo's `fixtures/` (see
`fixtures/README.md`).

## Licence

MIT. See [LICENSE](LICENSE).
