diff --git a/CHANGELOG.md b/CHANGELOG.md index 8afc0aa..5f90f16 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,17 @@ All notable changes to this project will be documented here. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [0.1.4] — 2026-11-19 + +### Fixed + +- **Out of credits now raises `InsufficientCreditsError`.** The API answers + `403 {"error": "Insufficient credits", "creditsNeeded": n}` when the balance + is too low, but the SDK only mapped 402, so callers got a generic + `BadRequestError`. A 403 about credits (and still a 402) now raises + `InsufficientCreditsError`; other 403s (a deactivated account, an expired + plan) stay `BadRequestError`. + ## [0.1.3] — 2026-10-16 ### Added diff --git a/README.md b/README.md index c52b890..22263ef 100644 --- a/README.md +++ b/README.md @@ -212,7 +212,7 @@ import time from socialapis import ( Facebook, AuthenticationError, # 401 — bad token - InsufficientCreditsError, # 402 — out of credits + InsufficientCreditsError, # 403 — out of credits RateLimitError, # 429 — slow down BadRequestError, # 4xx — bad input APIServerError, # 5xx — retry safely diff --git a/pyproject.toml b/pyproject.toml index e3a4a4c..8105034 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -160,6 +160,7 @@ disallow_untyped_defs = false # Test fixtures can use Any for brevity [tool.pytest.ini_options] minversion = "8.0" asyncio_mode = "auto" +asyncio_default_fixture_loop_scope = "function" testpaths = ["tests"] addopts = [ "-ra", diff --git a/socialapis/__init__.py b/socialapis/__init__.py index f638159..7808c2e 100644 --- a/socialapis/__init__.py +++ b/socialapis/__init__.py @@ -27,7 +27,7 @@ from socialapis import ( AuthenticationError, # 401 — bad token - InsufficientCreditsError, # 402 — out of credits + InsufficientCreditsError, # 403 — out of credits RateLimitError, # 429 — slow down ) diff --git a/socialapis/_client.py b/socialapis/_client.py index 23a01a4..2ee0823 100644 --- a/socialapis/_client.py +++ b/socialapis/_client.py @@ -105,7 +105,9 @@ def _raise_for_status(self, response: httpx.Response) -> None: request_id=request_id, body=body, ) - if status == 402: + # Out of credits: the API answers 403 {"error": "Insufficient credits", + # "creditsNeeded": n}. 402 is kept for compatibility. + if status == 402 or (status == 403 and _is_credit_error(body)): raise InsufficientCreditsError( message, status_code=status, @@ -150,6 +152,15 @@ def _safe_json(response: httpx.Response) -> dict[str, Any]: return data if isinstance(data, dict) else {} +def _is_credit_error(body: Mapping[str, Any]) -> bool: + """A 403 that is about credits (not a paused account or an expired plan).""" + if "creditsNeeded" in body: + return True + return any( + isinstance(body.get(k), str) and "credit" in body[k].lower() for k in ("error", "message") + ) + + def _extract_message(body: Mapping[str, Any]) -> str | None: """Pull a human-readable error message from the API's error envelope. diff --git a/socialapis/_errors.py b/socialapis/_errors.py index 1089491..1565899 100644 --- a/socialapis/_errors.py +++ b/socialapis/_errors.py @@ -8,7 +8,7 @@ The classes mirror the API's documented error semantics: - 401 → AuthenticationError -- 402 → InsufficientCreditsError (returned when free-tier budget is spent) +- 403 "Insufficient credits" (or 402) → InsufficientCreditsError (not enough credits left) - 429 → RateLimitError - 4xx (other) → BadRequestError - 5xx → APIServerError @@ -56,7 +56,7 @@ def __init__( class BadRequestError(APIError): - """4xx (excluding 401/402/429). Client-side mistake — missing parameter, + """4xx (excluding 401/429 and the out-of-credits 402/403). Client-side mistake — missing parameter, invalid value, wrong endpoint. NOT safe to retry without fixing input.""" @@ -66,7 +66,7 @@ class AuthenticationError(APIError): class InsufficientCreditsError(APIError): - """402 — credit balance exhausted. Retrying after a refill / upgrade + """403 "Insufficient credits" (or 402) — not enough credits left. Retrying after a refill / upgrade works. Tracked as a distinct exception so paid integrations can auto-top-up on this signal.""" diff --git a/socialapis/_version.py b/socialapis/_version.py index 247510b..3fe7511 100644 --- a/socialapis/_version.py +++ b/socialapis/_version.py @@ -4,4 +4,4 @@ # this manually for a release — use `git tag vX.Y.Z` and the CI does the # rest via hatchling's dynamic-version feature (see pyproject.toml). -__version__ = "0.1.3" +__version__ = "0.1.4" diff --git a/tests/test_facebook.py b/tests/test_facebook.py index d23f107..8c661fe 100644 --- a/tests/test_facebook.py +++ b/tests/test_facebook.py @@ -258,6 +258,39 @@ def test_402_maps_to_insufficient_credits_error() -> None: fb.get_page_info("EngenSA") +@respx.mock +def test_403_insufficient_credits_maps_to_insufficient_credits_error() -> None: + respx.get("https://api.socialapis.io/facebook/pages/details").mock( + return_value=httpx.Response( + 403, + json={ + "error": "Insufficient credits", + "message": "You need 3 credits", + "creditsNeeded": 3, + }, + ) + ) + with Facebook(api_token="t") as fb, pytest.raises(InsufficientCreditsError) as exc_info: + fb.get_page_info("EngenSA") + assert exc_info.value.status_code == 403 + + +@respx.mock +def test_403_paused_account_stays_bad_request() -> None: + respx.get("https://api.socialapis.io/facebook/pages/details").mock( + return_value=httpx.Response( + 403, + json={ + "success": False, + "message": "Subscription expired", + "code": "SUBSCRIPTION_EXPIRED", + }, + ) + ) + with Facebook(api_token="t") as fb, pytest.raises(BadRequestError): + fb.get_page_info("EngenSA") + + @respx.mock def test_429_maps_to_rate_limit_error_with_retry_after() -> None: respx.get("https://api.socialapis.io/facebook/pages/details").mock(