diff --git a/README.md b/README.md index ef708a8..8eafe32 100644 --- a/README.md +++ b/README.md @@ -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 @@ -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 diff --git a/docs/index.md b/docs/index.md index 7a9d439..2347ec3 100644 --- a/docs/index.md +++ b/docs/index.md @@ -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 @@ -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 @@ -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 @@ -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 @@ -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. diff --git a/src/pypricecharting/asyncpricecharting.py b/src/pypricecharting/asyncpricecharting.py index fd8fac7..81a8dd6 100644 --- a/src/pypricecharting/asyncpricecharting.py +++ b/src/pypricecharting/asyncpricecharting.py @@ -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, @@ -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: @@ -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.""" diff --git a/src/pypricecharting/error.py b/src/pypricecharting/error.py index 2b6dc91..936f8da 100644 --- a/src/pypricecharting/error.py +++ b/src/pypricecharting/error.py @@ -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.""" diff --git a/src/pypricecharting/pricecharting.py b/src/pypricecharting/pricecharting.py index 2cd8508..1c1eb2f 100644 --- a/src/pypricecharting/pricecharting.py +++ b/src/pypricecharting/pricecharting.py @@ -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, @@ -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: @@ -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.""" diff --git a/src/pypricecharting/requests.py b/src/pypricecharting/requests.py index 6be1d22..aff4773 100644 --- a/src/pypricecharting/requests.py +++ b/src/pypricecharting/requests.py @@ -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") diff --git a/src/pypricecharting/responses.py b/src/pypricecharting/responses.py index 33752e2..d032ff5 100644 --- a/src/pypricecharting/responses.py +++ b/src/pypricecharting/responses.py @@ -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 """ @@ -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: diff --git a/src/pypricecharting/route.py b/src/pypricecharting/route.py index 69dbb87..4204e3b 100644 --- a/src/pypricecharting/route.py +++ b/src/pypricecharting/route.py @@ -1,35 +1,30 @@ -from enum import Enum, unique +from enum import StrEnum, unique # Source: https://www.pricecharting.com/api-documentation BASE_URL = "https://www.pricecharting.com" +"""Default API base URL.""" -@unique -class Prices(Enum): - """PriceCharting Prices API Routes""" +class Route: + """PriceCharting API routes, grouped by API""" - PRODUCT = "/api/product" - PRODUCTS = "/api/products" + @unique + class Prices(StrEnum): + """PriceCharting Prices API Routes""" + PRODUCT = "/api/product" + PRODUCTS = "/api/products" -@unique -class MarketPlace(Enum): - """PriceCharting MarketPlace API Routes""" + @unique + class Marketplace(StrEnum): + """PriceCharting Marketplace API Routes""" - OFFERS = "/api/offers" - OFFER_PUBLISH = "/api/offer-publish" - OFFER_DETAILS = "/api/offer-details" - OFFER_FEEDBACK = "/api/offer-feedback" - OFFER_SHIP = "/api/offer-ship" - OFFER_END = "/api/offer-end" - OFFER_REFUND = "/api/offer-refund" - - -@unique -class Route(Enum): - """PriceCharting API Routes""" - - PRICES = Prices - MARKETPLACE = MarketPlace + OFFERS = "/api/offers" + OFFER_PUBLISH = "/api/offer-publish" + OFFER_DETAILS = "/api/offer-details" + OFFER_FEEDBACK = "/api/offer-feedback" + OFFER_SHIP = "/api/offer-ship" + OFFER_END = "/api/offer-end" + OFFER_REFUND = "/api/offer-refund" diff --git a/src/pypricecharting/types.py b/src/pypricecharting/types.py index 63cf1b3..d58ea92 100644 --- a/src/pypricecharting/types.py +++ b/src/pypricecharting/types.py @@ -36,7 +36,7 @@ class Rating(Enum): @unique class State(Enum): - """State flag""" + """Value of a set form flag, such as an `OfferPublishRequest` condition tag""" ON = "on" diff --git a/tests/test_asyncpricecharting_prices.py b/tests/test_asyncpricecharting_prices.py index 80376b0..e179e1e 100644 --- a/tests/test_asyncpricecharting_prices.py +++ b/tests/test_asyncpricecharting_prices.py @@ -3,13 +3,11 @@ from pypricecharting.asyncpricecharting import AsyncPriceCharting from pypricecharting.error import APIError, ParameterError -from pypricecharting.responses import ProductResponse -from tests.mocks.json import PRODUCT_BASIC_JSON +from pypricecharting.responses import ProductResponse, ProductsResponse +from pypricecharting.types import Status +from tests.mocks.json import PRODUCT_BASIC_JSON, PRODUCTS_JSON from tests.mocks.mock_pricecharting import TOKEN, error_body, mocked_async_client -# Template tests: methods that are still placeholders only check they can be called. -# Replace their `is None` assertions once each method is implemented. - @pytest.mark.parametrize( ("kwargs", "param"), @@ -17,6 +15,7 @@ ) async def test_product(kwargs, param): requests: list[Request] = [] + async with mocked_async_client( TOKEN, Response(200, json=PRODUCT_BASIC_JSON), requests ) as client: @@ -37,6 +36,7 @@ async def test_product(kwargs, param): async def test_product_raises_api_error(): body = error_body("No such product") requests: list[Request] = [] + async with mocked_async_client(TOKEN, Response(404, json=body), requests) as client: with pytest.raises(APIError, match="404: No such product"): await client.product(id="0") @@ -52,6 +52,7 @@ async def test_product_raises_for_invalid_parameters(): async def test_product_raises_for_multiple_parameters(): requests: list[Request] = [] + async with mocked_async_client( TOKEN, Response(200, json=PRODUCT_BASIC_JSON), requests ) as client: @@ -64,6 +65,24 @@ async def test_product_raises_for_multiple_parameters(): async def test_products(): - client = AsyncPriceCharting(TOKEN) - assert await client.products() is None - await client.aclose() + requests: list[Request] = [] + + async with mocked_async_client(TOKEN, Response(200, json=PRODUCTS_JSON), requests) as client: + response = await client.products("Tactics Ogre") + + assert isinstance(response, ProductsResponse) + assert response.status == Status.SUCCESS + assert len(response.products) == 2 + assert response.products[0].product_name == "Tactics Ogre" + assert response.products[1].product_name == "Tactics Ogre" + + assert len(requests) == 1 + assert requests[0].method == "GET" + assert requests[0].url.path == "/api/products" + assert dict(requests[0].url.params) == {"q": "Tactics Ogre", "t": TOKEN} + + +async def test_products_raises_for_invalid_parameter(): + async with AsyncPriceCharting(TOKEN) as client: + with pytest.raises(ParameterError, match=r"Invalid parameter; Query string q was empty"): + await client.products("") diff --git a/tests/test_pricecharting_prices.py b/tests/test_pricecharting_prices.py index ea42b47..877ba61 100644 --- a/tests/test_pricecharting_prices.py +++ b/tests/test_pricecharting_prices.py @@ -3,13 +3,11 @@ from pypricecharting.error import APIError, ParameterError from pypricecharting.pricecharting import PriceCharting -from pypricecharting.responses import ProductResponse -from tests.mocks.json import PRODUCT_BASIC_JSON +from pypricecharting.responses import ProductResponse, ProductsResponse +from pypricecharting.types import Status +from tests.mocks.json import PRODUCT_BASIC_JSON, PRODUCTS_JSON from tests.mocks.mock_pricecharting import TOKEN, error_body, mocked_client -# Template tests: methods that are still placeholders only check they can be called. -# Replace their `is None` assertions once each method is implemented. - @pytest.mark.parametrize( ("kwargs", "param"), @@ -17,6 +15,7 @@ ) def test_product(kwargs, param): requests: list[Request] = [] + with mocked_client(TOKEN, Response(200, json=PRODUCT_BASIC_JSON), requests) as client: product = client.product(**kwargs) @@ -35,6 +34,7 @@ def test_product(kwargs, param): def test_product_raises_api_error(): body = error_body("No such product") requests: list[Request] = [] + with ( mocked_client(TOKEN, Response(404, json=body), requests) as client, pytest.raises(APIError, match="404: No such product"), @@ -54,6 +54,7 @@ def test_product_raises_for_invalid_parameters(): def test_product_raises_for_multiple_parameters(): requests: list[Request] = [] + with ( mocked_client(TOKEN, Response(200, json=PRODUCT_BASIC_JSON), requests) as client, pytest.raises( @@ -66,6 +67,26 @@ def test_product_raises_for_multiple_parameters(): def test_products(): - client = PriceCharting(TOKEN) - assert client.products() is None - client.close() + requests: list[Request] = [] + + with mocked_client(TOKEN, Response(200, json=PRODUCTS_JSON), requests) as client: + response = client.products("Tactics Ogre") + + assert isinstance(response, ProductsResponse) + assert response.status == Status.SUCCESS + assert len(response.products) == 2 + assert response.products[0].product_name == "Tactics Ogre" + assert response.products[1].product_name == "Tactics Ogre" + + assert len(requests) == 1 + assert requests[0].method == "GET" + assert requests[0].url.path == "/api/products" + assert dict(requests[0].url.params) == {"q": "Tactics Ogre", "t": TOKEN} + + +def test_products_raises_for_invalid_parameter(): + with ( + PriceCharting(TOKEN) as client, + pytest.raises(ParameterError, match=r"Invalid parameter; Query string q was empty."), + ): + client.products("") diff --git a/tests/test_route.py b/tests/test_route.py index b188e43..4b72cd1 100644 --- a/tests/test_route.py +++ b/tests/test_route.py @@ -1,58 +1,42 @@ import pytest -from pypricecharting.route import MarketPlace, Prices, Route +from pypricecharting.route import Route # Source: https://www.pricecharting.com/api-documentation def test_prices_route(): - assert len(Prices) == 2 - assert Prices.PRODUCT.value == "/api/product" - assert Prices.PRODUCTS.value == "/api/products" + assert len(Route.Prices) == 2 + assert Route.Prices.PRODUCT == "/api/product" + assert Route.Prices.PRODUCTS == "/api/products" def test_prices_lookup_by_value(): - for member in Prices: - assert Prices(member.value) is member + for member in Route.Prices: + assert Route.Prices(member) is member def test_prices_unknown_value_raises(): with pytest.raises(ValueError, match="is not a valid"): - Prices("Invalid Route") + Route.Prices("Invalid Route") def test_marketplace_route(): - assert len(MarketPlace) == 7 - assert MarketPlace.OFFERS.value == "/api/offers" - assert MarketPlace.OFFER_PUBLISH.value == "/api/offer-publish" - assert MarketPlace.OFFER_DETAILS.value == "/api/offer-details" - assert MarketPlace.OFFER_FEEDBACK.value == "/api/offer-feedback" - assert MarketPlace.OFFER_SHIP.value == "/api/offer-ship" - assert MarketPlace.OFFER_REFUND.value == "/api/offer-refund" - assert MarketPlace.OFFER_END.value == "/api/offer-end" + assert len(Route.Marketplace) == 7 + assert Route.Marketplace.OFFERS == "/api/offers" + assert Route.Marketplace.OFFER_PUBLISH == "/api/offer-publish" + assert Route.Marketplace.OFFER_DETAILS == "/api/offer-details" + assert Route.Marketplace.OFFER_FEEDBACK == "/api/offer-feedback" + assert Route.Marketplace.OFFER_SHIP == "/api/offer-ship" + assert Route.Marketplace.OFFER_REFUND == "/api/offer-refund" + assert Route.Marketplace.OFFER_END == "/api/offer-end" def test_marketplace_lookup_by_value(): - for member in MarketPlace: - assert MarketPlace(member.value) is member + for member in Route.Marketplace: + assert Route.Marketplace(member) is member def test_marketplace_unknown_value_raises(): with pytest.raises(ValueError, match="is not a valid"): - MarketPlace("Invalid Route") - - -def test_route_routes(): - assert len(Route) == 2 - assert Route.MARKETPLACE.value is MarketPlace - assert Route.PRICES.value is Prices - - -def test_route_lookup_by_value(): - for member in Route: - assert Route(member.value) is member - - -def test_route_unknown_value_raises(): - with pytest.raises(ValueError, match="is not a valid"): - Route("Invalid Route") + Route.Marketplace("Invalid Route")