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
11 changes: 11 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
2 changes: 1 addition & 1 deletion socialapis/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
)

Expand Down
13 changes: 12 additions & 1 deletion socialapis/_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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.

Expand Down
6 changes: 3 additions & 3 deletions socialapis/_errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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."""


Expand All @@ -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."""

Expand Down
2 changes: 1 addition & 1 deletion socialapis/_version.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
33 changes: 33 additions & 0 deletions tests/test_facebook.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down