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
9 changes: 5 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,8 +72,8 @@ See [RELEASE.md](RELEASE.md) for how releases and release labels work.

## Usage

The client is under development. `product` is implemented on both clients; the other API methods
are not implemented yet.
Under development: the Prices API methods (`product`, `products`) are implemented; the Marketplace
API methods are not yet.

```python
from pypricecharting import AsyncPriceCharting, PriceCharting
Expand All @@ -84,10 +84,11 @@ with PriceCharting("<40-character API token>") as client:

async with AsyncPriceCharting("<40-character API token>") as client:
game = await client.product(q="earthbound")
results = await client.products("chrono trigger") # up to 20 matches
```

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

## Supporting Files

Expand Down
74 changes: 40 additions & 34 deletions docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,15 @@

Python client for the [PriceCharting API](https://www.pricecharting.com/api-documentation).

The package provides a synchronous client, `PriceCharting`, and an asynchronous client,
`AsyncPriceCharting`. Both authenticate with a 40-character PriceCharting API token.
It provides a synchronous client, `PriceCharting`, and an asynchronous client,
`AsyncPriceCharting`, both authenticated with a 40-character API token.

The client is under development: `product` is implemented on both clients, and the other API
methods are not implemented yet.
Under development: the Prices API methods (`product`, `products`) are implemented; the
Marketplace API methods are not yet.

## Authentication

Set your token in the `PRICECHARTING_TOKEN` environment variable and create a client without
Set the token in the `PRICECHARTING_TOKEN` environment variable and create a client without
arguments:

```python
Expand All @@ -20,20 +20,23 @@ with PriceCharting() as client:
...
```

You can also pass the token directly:
Or pass the token directly:

```python
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.
Prefer the environment variable, which keeps the token out of your code. Both clients raise
`ValueError` if the token is missing or not 40 characters.

Reuse one client for all requests, and close it when done: with a `with` block, or by calling
`close()` (`aclose()` for the async client).

## 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):
`product` looks up a 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
Expand All @@ -46,20 +49,29 @@ async with AsyncPriceCharting() as client:
game = await client.product(upc="045496830434")
```

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

## Searching products

`products` runs a full text search on title and/or console and returns up to 20 matches as
`ProductSummary` objects. Pass a result's `id` to `product` for prices:

```python
with PriceCharting() as client:
results = client.products("chrono trigger super nintendo")
for summary in results.products:
print(summary.id, summary.product_name, summary.console_name)
```

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).
An empty or whitespace-only query raises `ParameterError`.

## Errors

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

- `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`.
- `ParameterError` (also a `ValueError`): invalid method arguments, raised before any request is
sent.
- `APIError`: the API returned an error. Has `message` and `status_code`.

```python
from pypricecharting import APIError
Expand All @@ -72,12 +84,10 @@ except APIError as error:

## Client options

Both clients accept two optional arguments, mainly for testing:
Both clients take 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`.
- `base_url`: send requests to another server, such as a local mock server.
- `transport`: a custom `httpx2` transport, such as `httpx2.MockTransport`.

```python
from httpx2 import MockTransport, Response
Expand All @@ -90,21 +100,17 @@ client = PriceCharting(

## 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):
Everything public, including the clients, errors, models, and enums, can be imported from
`pypricecharting` or from its own module (such as `pypricecharting.responses`):

```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
the request URL. The clients redact it from the `httpx2` request log, which shows `t=REDACTED`
instead. Anything outside this library that records URLs can still see the token, such as
proxies or your own logging of requests.
The API requires the token in the query string of `GET` requests. The clients redact it from the
`httpx2` request log (`t=REDACTED`), but anything else that records URLs, such as proxies or your
own request logging, can still see it.

See the [API Reference](api/clients.md) for the classes and types in the package.
See the [API Reference](api/clients.md) for all classes and types.
50 changes: 34 additions & 16 deletions src/pypricecharting/asyncpricecharting.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,19 @@

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
from pypricecharting.responses import ProductResponse, ProductsResponse, _parse
from pypricecharting.route import BASE_URL, Route


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

Reuse one client for all requests and close it when done (`async with` or `aclose()`). The Marketplace API
methods are not implemented yet and return `None`.
"""

TOKEN_KEY = "PRICECHARTING_TOKEN"
"""Environment variable the token is read from when none is passed."""

def __init__(
self,
Expand All @@ -25,21 +30,16 @@ def __init__(
):
"""Create a client authenticated with a PriceCharting API token.

The client adds a logging filter to the `httpx2` logger that replaces the token in
request URLs with `REDACTED`.
The token is redacted from `httpx2` request logs.

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.
base_url: API base URL. Override it to use a mock server.
transport: Custom `httpx2` async transport, such as `httpx2.MockTransport` in tests.

Raises:
ValueError: If no token is passed or set in the environment, or the token is not
40 characters.
ValueError: If the token is missing or not 40 characters.

"""
if token is not None and len(token) != 40:
Expand Down Expand Up @@ -101,12 +101,30 @@ async def product(
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)
response = await self._client.get(Route.Prices.PRODUCT, params=params)
return _parse(response, ProductResponse)

async def products(self):
"""Search for products."""
pass
async def products(self, q: str) -> ProductsResponse:
"""Search for products by title and/or console.

Args:
q: Full text search on title and/or console. Surrounding whitespace is stripped.

Returns:
Up to 20 matching products.

Raises:
ParameterError: If `q` is empty or only whitespace.
APIError: If the API returns an error.

"""
q = q.strip()

if len(q) == 0:
raise ParameterError("Invalid parameter; Query string q was empty.")

response = await self._client.get(Route.Prices.PRODUCTS, params={"q": q})
return _parse(response, ProductsResponse)

async def offers(self):
"""List marketplace offers."""
Expand Down
13 changes: 11 additions & 2 deletions src/pypricecharting/error.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,20 @@ class PriceChartingError(Exception):


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

Raised before any request is sent.
"""


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

Attributes:
message: The API's `error-message`, or the HTTP reason phrase if it has none.
status_code: The HTTP status code of the response.

"""

def __init__(self, message: str, status_code: int):
"""Store the API error message and HTTP status code."""
Expand Down
50 changes: 34 additions & 16 deletions src/pypricecharting/pricecharting.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,19 @@

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
from pypricecharting.responses import ProductResponse, ProductsResponse, _parse
from pypricecharting.route import BASE_URL, Route


class PriceCharting:
"""Synchronous PriceCharting API client."""
"""Synchronous PriceCharting API client.

Reuse one client for all requests and close it when done (`with` or `close()`). The Marketplace API
methods are not implemented yet and return `None`.
"""

TOKEN_KEY = "PRICECHARTING_TOKEN"
"""Environment variable the token is read from when none is passed."""

def __init__(
self,
Expand All @@ -25,21 +30,16 @@ def __init__(
):
"""Create a client authenticated with a PriceCharting API token.

The client adds a logging filter to the `httpx2` logger that replaces the token in
request URLs with `REDACTED`.
The token is redacted from `httpx2` request logs.

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` transport that sends requests, such as
`httpx2.MockTransport` in tests. If omitted, the default `httpx2` transport is
used.
base_url: API base URL. Override it to use a mock server.
transport: Custom `httpx2` transport, such as `httpx2.MockTransport` in tests.

Raises:
ValueError: If no token is passed or set in the environment, or the token is not
40 characters.
ValueError: If the token is missing or not 40 characters.

"""
if token is not None and len(token) != 40:
Expand Down Expand Up @@ -100,12 +100,30 @@ def product(
if len(params) > 1:
raise ParameterError("Invalid parameters. Only one of id, upc, or q is allowed.")

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

def products(self):
"""Search for products."""
pass
def products(self, q: str) -> ProductsResponse:
"""Search for products by title and/or console.

Args:
q: Full text search on title and/or console. Surrounding whitespace is stripped.

Returns:
Up to 20 matching products.

Raises:
ParameterError: If `q` is empty or only whitespace.
APIError: If the API returns an error.

"""
q = q.strip()

if len(q) == 0:
raise ParameterError("Invalid parameter; Query string q was empty.")

response = self._client.get(Route.Prices.PRODUCTS, params={"q": q})
return _parse(response, ProductsResponse)

def offers(self):
"""List marketplace offers."""
Expand Down
9 changes: 7 additions & 2 deletions src/pypricecharting/requests.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,9 +51,14 @@ class OfferPublishRequest(PriceChartingModel):

@model_validator(mode="after")
def check_identifier(self) -> Self:
"""Validate at least one identifier provided"""
"""Check that at least one of `product`, `upc`, `asin`, `epid`, or `offer_id` is set.

Raises:
ValueError: If none of them is set.

"""
ids = [self.product, self.upc, self.asin, self.epid, self.offer_id]
for id in ids:
if id is not None:
return self
raise ValueError("One of product, upc, asin, epid, or offer_id not provided")
raise ValueError("One of product, upc, asin, epid, or offer_id is required")
7 changes: 3 additions & 4 deletions src/pypricecharting/responses.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@
class ErrorResponse(PriceChartingModel):
"""Error response from any endpoint

Returned with a 4xx or 5xx status code and `status: error`. The clients raise
`error.APIError` with the message instead of returning this model.
Returned with a 4xx or 5xx status code. The clients raise `error.APIError` instead of
returning it.

https://www.pricecharting.com/api-documentation
"""
Expand Down Expand Up @@ -271,8 +271,7 @@ def _parse[M: PriceChartingModel](response: Response, model: type[M]) -> M:

Raises:
APIError: If the response is not JSON or has a non-2xx status code. The message is
the `error-message` from the body, parsed as an `ErrorResponse`, or the HTTP
reason phrase if the body has none.
the body's `error-message`, or the HTTP reason phrase.

"""
try:
Expand Down
Loading
Loading