Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 16 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
# PyPriceCharting API Client ![](https://github.com/ahcodedev/pypricecharting/actions/workflows/python.yml/badge.svg?branch=main)
# PyPriceCharting API Client

[![CI](https://github.com/ahcodedev/pypricecharting/actions/workflows/python.yml/badge.svg?branch=main)](https://github.com/ahcodedev/pypricecharting/actions/workflows/python.yml)
[![Docs](https://github.com/ahcodedev/pypricecharting/actions/workflows/docs.yml/badge.svg?branch=main)](https://github.com/ahcodedev/pypricecharting/actions/workflows/docs.yml)
[![Security](https://github.com/ahcodedev/pypricecharting/actions/workflows/security.yml/badge.svg?branch=main)](https://github.com/ahcodedev/pypricecharting/actions/workflows/security.yml)
[![gitleaks](https://img.shields.io/badge/protected%20by-gitleaks-blue)](https://github.com/gitleaks/gitleaks)
[![uv](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/uv/main/assets/badge/v0.json)](https://github.com/astral-sh/uv)
[![Ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json)](https://github.com/astral-sh/ruff)
![Python](https://img.shields.io/badge/python-3.15-blue)
[![License: MIT](https://img.shields.io/badge/license-MIT-green)](LICENSE)

PriceCharting API Client written in Python

Expand Down Expand Up @@ -65,19 +72,23 @@ See [RELEASE.md](RELEASE.md) for how releases and release labels work.

## Usage

The client is under development. `PriceCharting` and `AsyncPriceCharting` can be created and used
as context managers, but their API methods are not implemented yet.
The client is under development. `product` is implemented on both clients; the other API methods
are not implemented yet.

```python
from pypricecharting import AsyncPriceCharting, PriceCharting

with PriceCharting("<40-character API token>") as client:
...
game = client.product(id="6910")
print(game.product_name, game.cib_price) # prices are in pennies

async with AsyncPriceCharting("<40-character API token>") as client:
...
game = await client.product(q="earthbound")
```

If the token is omitted, it is read from the `PRICECHARTING_TOKEN` environment variable. See the
docs site for errors and client options.

## Supporting Files

Project contains an OpenAPI spec and a Bruno project for easy testing and mocking
Expand Down
3 changes: 3 additions & 0 deletions docs/api/errors.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Errors

::: pypricecharting.error
74 changes: 72 additions & 2 deletions docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ Python client for the [PriceCharting API](https://www.pricecharting.com/api-docu
The package provides a synchronous client, `PriceCharting`, and an asynchronous client,
`AsyncPriceCharting`. Both authenticate with a 40-character PriceCharting API token.

The client is under development: the clients can be created and used as context managers, but
their API methods are not implemented yet.
The client is under development: `product` is implemented on both clients, and the other API
methods are not implemented yet.

## Authentication

Expand All @@ -30,6 +30,76 @@ with PriceCharting("your-40-character-token") as client:
The environment variable is recommended, because it keeps the token out of your code. Both
clients raise `ValueError` if no token is found or the token is not 40 characters.

## Getting a product

`product` looks up a single product by exactly one of `id` (PriceCharting product ID), `upc`
(UPC barcode), or `q` (full text search, best match only):

```python
from pypricecharting import AsyncPriceCharting, PriceCharting

with PriceCharting() as client:
game = client.product(id="6910")
print(game.product_name, game.cib_price) # EarthBound 42995

async with AsyncPriceCharting() as client:
game = await client.product(upc="045496830434")
```

Prices are integer pennies, so `42995` is $429.95.

Create one client and reuse it for all your requests, so they share a connection pool. Close it
when you are done, either with a `with` block or by calling `close()` (`aclose()` for the async
client).

## Errors

All errors subclass `PriceChartingError` and can be imported from `pypricecharting`:

- `ParameterError` (also a `ValueError`) is raised before any request is sent when a method gets
invalid parameters, such as `product()` with none or more than one of `id`, `upc`, and `q`.
- `APIError` is raised when the API returns an error. It has the API's `message` and the HTTP
`status_code`.

```python
from pypricecharting import APIError

try:
game = client.product(id="0")
except APIError as error:
print(error.status_code, error.message)
```

## Client options

Both clients accept two optional arguments, mainly for testing:

- `base_url` sends requests to another server, such as a local mock server. It defaults to
`https://www.pricecharting.com`.
- `transport` replaces the `httpx2` transport that sends requests, such as
`httpx2.MockTransport`.

```python
from httpx2 import MockTransport, Response

client = PriceCharting(
base_url="http://localhost:8080",
transport=MockTransport(lambda request: Response(200, json={"status": "success"})),
)
```

## Imports

Everything public can be imported from `pypricecharting` directly: the clients, the errors, the
request and response models, the shared models (`ProductSummary`, `Offer`, `Buyer`), and the enums
in `types` (`Condition`, `Console`, `Genre`, `Status`, and others):

```python
from pypricecharting import Condition, PriceCharting, ProductResponse
```

They can also be imported from their own modules, such as `pypricecharting.responses`.

## Security

The PriceCharting API requires the token in the query string of `GET` requests, so it is part of
Expand Down
1 change: 1 addition & 0 deletions mkdocs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -46,4 +46,5 @@ nav:
- Requests: api/requests.md
- Responses: api/responses.md
- Types: api/types.md
- Errors: api/errors.md
- Routes: api/route.md
2 changes: 2 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ name = "pypricecharting"
description = "Python PriceCharting API Client"
version = "0.0.1"
requires-python = ">=3.15"
license = "MIT"
license-files = ["LICENSE"]

dependencies = [
"httpx2>=2.16.0",
Expand Down
62 changes: 61 additions & 1 deletion src/pypricecharting/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,64 @@
from pypricecharting.asyncpricecharting import AsyncPriceCharting
from pypricecharting.error import APIError, ParameterError, PriceChartingError
from pypricecharting.models import Buyer, Offer, PriceChartingModel, ProductSummary
from pypricecharting.pricecharting import PriceCharting
from pypricecharting.requests import OfferPublishRequest
from pypricecharting.responses import (
OfferDetailsResponse,
OfferEndResponse,
OfferFeedbackResponse,
OfferPublishResponse,
OfferRefundResponse,
OfferShipResponse,
OffersResponse,
ProductResponse,
ProductsResponse,
)
from pypricecharting.types import (
Cards,
Coins,
Comics,
Condition,
Console,
Genre,
OfferStatus,
RateLimit,
Rating,
State,
Status,
VideoGames,
)

__all__ = ["AsyncPriceCharting", "PriceCharting"]
__all__ = [
"APIError",
"AsyncPriceCharting",
"Buyer",
"Cards",
"Coins",
"Comics",
"Condition",
"Console",
"Genre",
"Offer",
"OfferDetailsResponse",
"OfferEndResponse",
"OfferFeedbackResponse",
"OfferPublishRequest",
"OfferPublishResponse",
"OfferRefundResponse",
"OfferShipResponse",
"OfferStatus",
"OffersResponse",
"ParameterError",
"PriceCharting",
"PriceChartingError",
"PriceChartingModel",
"ProductResponse",
"ProductSummary",
"ProductsResponse",
"RateLimit",
"Rating",
"State",
"Status",
"VideoGames",
]
55 changes: 48 additions & 7 deletions src/pypricecharting/asyncpricecharting.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,26 @@
from types import TracebackType
from typing import Self

from httpx2 import AsyncClient
from httpx2 import AsyncBaseTransport, AsyncClient
from pydantic import SecretStr

from pypricecharting._auth import _REDACT_FILTER, _TokenAuth
from pypricecharting.error import ParameterError
from pypricecharting.responses import ProductResponse, _parse
from pypricecharting.route import BASE_URL, Prices


class AsyncPriceCharting:
"""Asynchronous PriceCharting API client."""

TOKEN_KEY = "PRICECHARTING_TOKEN"

def __init__(self, token: str | None = None):
def __init__(
self,
token: str | None = None,
base_url: str = BASE_URL,
transport: AsyncBaseTransport | None = None,
):
"""Create a client authenticated with a PriceCharting API token.

The client adds a logging filter to the `httpx2` logger that replaces the token in
Expand All @@ -23,6 +31,11 @@ def __init__(self, token: str | None = None):
Args:
token: The 40-character PriceCharting API token. If omitted, it is read from the
`PRICECHARTING_TOKEN` environment variable.
base_url: The API base URL. Defaults to `route.BASE_URL`. Override it to send
requests to another server, such as a mock server in tests.
transport: The `httpx2` async transport that sends requests, such as
`httpx2.MockTransport` in tests. If omitted, the default `httpx2` transport is
used.

Raises:
ValueError: If no token is passed or set in the environment, or the token is not
Expand All @@ -39,12 +52,14 @@ def __init__(self, token: str | None = None):
raise ValueError("PriceCharting API token is not 40 characters")

self._token = SecretStr(token)
self.client = AsyncClient(auth=_TokenAuth(self._token))
self._client = AsyncClient(
base_url=base_url, auth=_TokenAuth(self._token), transport=transport
)
logging.getLogger("httpx2").addFilter(_REDACT_FILTER)

async def aclose(self):
"""Close the underlying HTTP client."""
await self.client.aclose()
await self._client.aclose()

async def __aenter__(self) -> Self:
"""Enter the async context and return the client."""
Expand All @@ -59,9 +74,35 @@ async def __aexit__(
"""Close the underlying HTTP client on exit."""
await self.aclose()

async def product(self):
"""Get a single product."""
pass
async def product(
self, id: str | None = None, upc: str | None = None, q: str | None = None
) -> ProductResponse:
"""Get a single product by exactly one of `id`, `upc`, or `q`.

Args:
id: PriceCharting product ID.
upc: UPC barcode.
q: Full text search on title and/or console. Only the best match is returned.

Returns:
The matching product.

Raises:
ParameterError: If not exactly one of `id`, `upc`, or `q` is given.
APIError: If the API returns an error.

"""
params = {
key: value for key, value in {"id": id, "upc": upc, "q": q}.items() if value is not None
}

if len(params) == 0:
raise ParameterError("Invalid parameters. Either id, upc, or q are required.")
if len(params) > 1:
raise ParameterError("Invalid parameters. Only one of id, upc, or q is allowed.")

response = await self._client.get(Prices.PRODUCT.value, params=params)
return _parse(response, ProductResponse)

async def products(self):
"""Search for products."""
Expand Down
16 changes: 16 additions & 0 deletions src/pypricecharting/error.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
class PriceChartingError(Exception):
"""Base class for all PriceCharting errors"""


class ParameterError(PriceChartingError, ValueError):
"""Raised when an API method is called with invalid parameters"""


class APIError(PriceChartingError):
"""Raised when the API returns an error response"""

def __init__(self, message: str, status_code: int):
"""Store the API error message and HTTP status code."""
super().__init__(f"{status_code}: {message}")
self.message = message
self.status_code = status_code
Loading
Loading