From 7434749bf59c8af47102b9c9a4b6f06e601739c5 Mon Sep 17 00:00:00 2001 From: Vigo Walker Date: Sun, 29 Nov 2026 15:43:31 +0100 Subject: [PATCH 1/3] feat: rank, events, calendar, twitter, wallet and account endpoints Co-Authored-By: Claude Sonnet 5.5 --- .../plans/2026-11-29-more-endpoints.md | 15 ++ pyproject.toml | 6 +- src/futurenews/__init__.py | 16 +- src/futurenews/_base.py | 50 ++++- src/futurenews/client.py | 76 ++++++-- src/futurenews/errors.py | 15 ++ src/futurenews/models.py | 62 +++++- src/futurenews/resources/__init__.py | 17 +- src/futurenews/resources/_calls.py | 94 +++++++++ src/futurenews/resources/asynchronous.py | 86 +++++++++ src/futurenews/resources/sync.py | 86 +++++++++ src/futurenews/resources/trending.py | 65 ------- tests/test_client.py | 8 +- tests/test_endpoints.py | 182 ++++++++++++++++++ 14 files changed, 682 insertions(+), 96 deletions(-) create mode 100644 docs/superpowers/plans/2026-11-29-more-endpoints.md create mode 100644 src/futurenews/resources/_calls.py create mode 100644 src/futurenews/resources/asynchronous.py create mode 100644 src/futurenews/resources/sync.py delete mode 100644 src/futurenews/resources/trending.py create mode 100644 tests/test_endpoints.py diff --git a/docs/superpowers/plans/2026-11-29-more-endpoints.md b/docs/superpowers/plans/2026-11-29-more-endpoints.md new file mode 100644 index 0000000..49ceef0 --- /dev/null +++ b/docs/superpowers/plans/2026-11-29-more-endpoints.md @@ -0,0 +1,15 @@ +# More endpoints (plan, short) + +Spec: 2026-11-29-futurenews-api-design.md. Goal: add 6 endpoints from user-supplied curls, with detailed docs. + +| Resource | Method | Path | Auth | +|---|---|---|---| +| `rank.list` | POST | /events/api/rank | no | +| `events.get(slug)` | GET | /api/v1/event/polymarket/{slug} | no | +| `calendar.get` | GET | /api/v1/finance_calendar/polymarket | no | +| `twitter.activity` | GET | /fds/api/v1/market/twitter/activity/list | no | +| `wallet.balances` | GET | /td/api/v1/wallet/balances | Bearer | +| `account.user_info` | POST | /account/user_info | Bearer | + +Design calls: client gets `auth_token`; a `Call` value object is built by pure functions and sent by one sync/async `_send`; unknown response shapes -> permissive `ApiResponse` (`.data`, `.raw`); client-side `AuthRequiredError`, HTTP 401 -> `AuthenticationError`; tokens/wallets/cookies from the curls are never committed (fakes in tests/docs). +Tasks: (1) errors+models+Call/_send refactor, (2) six resources, tests first, (3) detailed docs per endpoint + auth page, (4) review, PR. diff --git a/pyproject.toml b/pyproject.toml index bc3debb..bff6000 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -47,7 +47,7 @@ addopts = "-m 'not live'" asyncio_default_fixture_loop_scope = "function" [tool.ruff] -line-length = 110 +line-length = 120 src = ["src", "tests"] [tool.ruff.lint] @@ -56,3 +56,7 @@ select = ["E", "F", "I", "UP", "B"] [tool.mypy] strict = true plugins = ["pydantic.mypy"] + +[tool.ruff.lint.per-file-ignores] +# pydantic evaluates annotations at runtime, so Optional[...] is required on Python 3.9 +"src/futurenews/models.py" = ["UP045"] diff --git a/src/futurenews/__init__.py b/src/futurenews/__init__.py index 7cf577e..f965ae2 100644 --- a/src/futurenews/__init__.py +++ b/src/futurenews/__init__.py @@ -8,23 +8,37 @@ from .client import AsyncFutureNews, FutureNews from .errors import ( APIError, + AuthenticationError, + AuthRequiredError, BlockedError, ConnectionFailure, FutureNewsError, RateLimitError, ) -from .models import TrendingItem, TrendingRequest, TrendingResponse +from .models import ( + ApiResponse, + RankRequest, + RankResponse, + TrendingItem, + TrendingRequest, + TrendingResponse, +) __version__ = "0.1.0" __all__ = [ "AFFILIATE_URL", "LINKS", "APIError", + "ApiResponse", + "AuthRequiredError", + "AuthenticationError", "AsyncFutureNews", "BlockedError", "ConnectionFailure", "FutureNews", "FutureNewsError", + "RankRequest", + "RankResponse", "RateLimitError", "TrendingItem", "TrendingRequest", diff --git a/src/futurenews/_base.py b/src/futurenews/_base.py index cead3f4..03926ec 100644 --- a/src/futurenews/_base.py +++ b/src/futurenews/_base.py @@ -7,13 +7,14 @@ from __future__ import annotations import uuid +from dataclasses import dataclass, field from datetime import datetime, timezone from email.utils import parsedate_to_datetime from typing import Any import httpx -from .errors import APIError, BlockedError, RateLimitError +from .errors import APIError, AuthenticationError, BlockedError, RateLimitError BASE_URL = "https://future.news" TRENDING_PATH = "/events/api/trending/list" @@ -27,8 +28,7 @@ "origin": BASE_URL, "referer": f"{BASE_URL}/trending", "user-agent": ( - "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) " - "Chrome/154.0.0.0 Safari/537.36" + "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/154.0.0.0 Safari/537.36" ), } @@ -82,9 +82,9 @@ def _is_challenge(resp: httpx.Response) -> bool: def parse_response(resp: httpx.Response) -> Any: """Raise the right :mod:`futurenews.errors` exception or return JSON.""" if resp.status_code == 403 or _is_challenge(resp): - raise BlockedError( - resp.status_code, "blocked (Cloudflare challenge?) - pass fresh cookies or a proxy" - ) + raise BlockedError(resp.status_code, "blocked (Cloudflare challenge?) - pass fresh cookies or a proxy") + if resp.status_code == 401: + raise AuthenticationError(401, "unauthorized - token missing, invalid or expired") if resp.status_code == 429: raise RateLimitError(429, "rate limited", retry_after=_retry_after(resp)) if resp.status_code >= 400: @@ -93,3 +93,41 @@ def parse_response(resp: httpx.Response) -> Any: return resp.json() except ValueError as exc: # empty/non-JSON body on a 200 raise APIError(resp.status_code, "response was not valid JSON") from exc + + +@dataclass(frozen=True) +class Call: + """A fully described API call, independent of sync/async transport. + + Resource builders return a ``Call``; the client's ``_send`` executes it. + Keeping this a plain value object makes every endpoint trivially testable. + """ + + method: str + path: str + params: tuple[tuple[str, str], ...] = () + json: Any = None + auth: bool = False # True -> needs ``Authorization: Bearer `` + meta: dict[str, Any] = field(default_factory=dict) + + +def request_kwargs(call: Call, device_id: str, token: str | None) -> dict[str, Any]: + """Translate a :class:`Call` into ``httpx`` request keyword arguments. + + Raises: + AuthRequiredError: the call needs auth and no token is configured. + """ + from .errors import AuthRequiredError + + headers: dict[str, str] = {} + if call.auth: + if not token: + raise AuthRequiredError(f"{call.method} {call.path} needs auth_token=... on the client") + headers["authorization"] = f"Bearer {token}" + kwargs: dict[str, Any] = { + "params": [*build_params(device_id).items(), *call.params], + "headers": headers, + } + if call.json is not None: + kwargs["json"] = call.json + return kwargs diff --git a/src/futurenews/client.py b/src/futurenews/client.py index 77106de..2053a46 100644 --- a/src/futurenews/client.py +++ b/src/futurenews/client.py @@ -6,11 +6,20 @@ from __future__ import annotations from types import TracebackType +from typing import Any import httpx -from ._base import BASE_URL, DEFAULT_HEADERS, new_device_id -from .resources.trending import AsyncTrending, Trending +from . import resources +from ._base import ( + BASE_URL, + DEFAULT_HEADERS, + Call, + new_device_id, + parse_response, + request_kwargs, +) +from .errors import ConnectionFailure def _headers(extra: dict[str, str] | None) -> dict[str, str]: @@ -20,7 +29,12 @@ def _headers(extra: dict[str, str] | None) -> dict[str, str]: class FutureNews: """Synchronous Future News client. + Resources: ``trending``, ``rank``, ``events``, ``calendar``, ``twitter`` + (public) and ``wallet``, ``account`` (need ``auth_token``). + Args: + auth_token: Bearer access token for authenticated endpoints. Treat it + like a password. It is never logged and hidden from ``repr``. cookies: Optional browser cookies (e.g. ``{"cf_clearance": ...}``) if Cloudflare challenges your IP. The library ships none. headers: Extra/override headers. @@ -32,6 +46,7 @@ class FutureNews: def __init__( self, *, + auth_token: str | None = None, cookies: dict[str, str] | None = None, headers: dict[str, str] | None = None, proxy: str | None = None, @@ -39,14 +54,29 @@ def __init__( device_id: str | None = None, ) -> None: self.device_id = device_id or new_device_id() + self._auth_token = auth_token self._http = httpx.Client( - base_url=BASE_URL, - cookies=cookies, - headers=_headers(headers), - proxy=proxy, - timeout=timeout, + base_url=BASE_URL, cookies=cookies, headers=_headers(headers), proxy=proxy, timeout=timeout ) - self.trending = Trending(self) + self.trending = resources.Trending(self) + self.rank = resources.Rank(self) + self.events = resources.Events(self) + self.calendar = resources.Calendar(self) + self.twitter = resources.Twitter(self) + self.wallet = resources.Wallet(self) + self.account = resources.Account(self) + + def __repr__(self) -> str: + return f"FutureNews(device_id={self.device_id!r}, authenticated={self._auth_token is not None})" + + def _send(self, call: Call) -> Any: + """Execute a :class:`Call`; returns parsed JSON or raises a FutureNewsError.""" + kwargs = request_kwargs(call, self.device_id, self._auth_token) + try: + resp = self._http.request(call.method, call.path, **kwargs) + except httpx.TransportError as exc: + raise ConnectionFailure(str(exc)) from exc + return parse_response(resp) def close(self) -> None: """Close the underlying connection pool.""" @@ -65,11 +95,12 @@ def __exit__( class AsyncFutureNews: - """Asynchronous Future News client (same arguments as :class:`FutureNews`).""" + """Asynchronous Future News client (same arguments and resources as :class:`FutureNews`).""" def __init__( self, *, + auth_token: str | None = None, cookies: dict[str, str] | None = None, headers: dict[str, str] | None = None, proxy: str | None = None, @@ -77,14 +108,29 @@ def __init__( device_id: str | None = None, ) -> None: self.device_id = device_id or new_device_id() + self._auth_token = auth_token self._http = httpx.AsyncClient( - base_url=BASE_URL, - cookies=cookies, - headers=_headers(headers), - proxy=proxy, - timeout=timeout, + base_url=BASE_URL, cookies=cookies, headers=_headers(headers), proxy=proxy, timeout=timeout ) - self.trending = AsyncTrending(self) + self.trending = resources.AsyncTrending(self) + self.rank = resources.AsyncRank(self) + self.events = resources.AsyncEvents(self) + self.calendar = resources.AsyncCalendar(self) + self.twitter = resources.AsyncTwitter(self) + self.wallet = resources.AsyncWallet(self) + self.account = resources.AsyncAccount(self) + + def __repr__(self) -> str: + return f"AsyncFutureNews(device_id={self.device_id!r}, authenticated={self._auth_token is not None})" + + async def _send(self, call: Call) -> Any: + """Async twin of :meth:`FutureNews._send`.""" + kwargs = request_kwargs(call, self.device_id, self._auth_token) + try: + resp = await self._http.request(call.method, call.path, **kwargs) + except httpx.TransportError as exc: + raise ConnectionFailure(str(exc)) from exc + return parse_response(resp) async def aclose(self) -> None: """Close the underlying connection pool.""" diff --git a/src/futurenews/errors.py b/src/futurenews/errors.py index b08dd10..ee8e389 100644 --- a/src/futurenews/errors.py +++ b/src/futurenews/errors.py @@ -37,3 +37,18 @@ def __init__(self, status_code: int, message: str = "", retry_after: float | Non class ConnectionFailure(FutureNewsError): """Network-level failure (DNS, timeout, connection refused).""" + + +class AuthRequiredError(FutureNewsError): + """An endpoint needs a bearer token but the client has no ``auth_token``. + + Raised *before* any request is sent. Pass ``auth_token=...`` to the client. + """ + + +class AuthenticationError(APIError): + """HTTP 401: the bearer token is missing, invalid or expired. + + Future News access tokens are short-lived (about 30 minutes), so refresh + the token and build a new client. + """ diff --git a/src/futurenews/models.py b/src/futurenews/models.py index fc56bec..9306e20 100644 --- a/src/futurenews/models.py +++ b/src/futurenews/models.py @@ -6,7 +6,8 @@ from __future__ import annotations -from typing import Any +from datetime import date +from typing import Any, Optional from pydantic import BaseModel, ConfigDict, Field, StrictInt @@ -80,3 +81,62 @@ def _find_items(payload: Any, depth: int = 0) -> tuple[list[Any] | None, dict[st outer = {k: v for k, v in payload.items() if k != key and k != "items"} return found, {**outer, **inner} return None, {k: v for k, v in payload.items() if k != "items"} + + +class RankRequest(BaseModel): + """Body for ``POST /events/api/rank`` (the "new", "trending"... tabs).""" + + model_config = ConfigDict(extra="forbid") + + exclude_series: bool = False + rank_type: str = "trending" + categories: list[str] = Field(default_factory=list) + subcategories: list[str] = Field(default_factory=list) + status: list[str] = Field(default_factory=lambda: ["active"]) + market_status: Optional[str] = None + order_by: str = "volume24h" + limit: StrictInt = Field(default=100, ge=1, le=100) + exclude_tags: list[str] = Field(default_factory=list) + + def to_body(self) -> dict[str, Any]: + """JSON body; optional fields are omitted when unset, like the web app.""" + body = self.model_dump(exclude_none=True) + if not body["exclude_tags"]: + del body["exclude_tags"] + return body + + +#: ``rank/list`` returns the same list shape as ``trending/list``. +RankResponse = TrendingResponse + + +class ApiResponse(BaseModel): + """Permissive wrapper for endpoints whose payload shape is not modelled yet. + + ``data`` is the ``"data"`` field of the JSON object (or the whole payload + when there is no such field); ``raw`` is always the untouched payload. + Other top-level fields (``code``, ``msg``...) are kept as attributes. + """ + + model_config = ConfigDict(extra="allow") + + data: Any = None + raw: Any = None + + @classmethod + def from_payload(cls, payload: Any) -> ApiResponse: + """Wrap any JSON payload.""" + if isinstance(payload, dict): + extras = {k: v for k, v in payload.items() if k not in ("data", "raw")} + return cls(data=payload.get("data", payload), raw=payload, **extras) + return cls(data=payload, raw=payload) + + +def iso_date(value: date | str, name: str) -> str: + """Return ``YYYY-MM-DD`` for a date or ISO string; ValueError otherwise.""" + if isinstance(value, date): + return value.isoformat() + try: + return date.fromisoformat(value).isoformat() + except (TypeError, ValueError) as exc: + raise ValueError(f"{name} must be a date or 'YYYY-MM-DD', got {value!r}") from exc diff --git a/src/futurenews/resources/__init__.py b/src/futurenews/resources/__init__.py index 81e669b..a6e8297 100644 --- a/src/futurenews/resources/__init__.py +++ b/src/futurenews/resources/__init__.py @@ -1 +1,16 @@ -"""API resources (one module per endpoint family).""" +"""API resources: ``_calls`` (request builders), ``sync`` and ``asynchronous`` (thin wrappers).""" + +from .asynchronous import Account as AsyncAccount +from .asynchronous import Calendar as AsyncCalendar +from .asynchronous import Events as AsyncEvents +from .asynchronous import Rank as AsyncRank +from .asynchronous import Trending as AsyncTrending +from .asynchronous import Twitter as AsyncTwitter +from .asynchronous import Wallet as AsyncWallet +from .sync import Account, Calendar, Events, Rank, Trending, Twitter, Wallet + +__all__ = [ + "Account", "Calendar", "Events", "Rank", "Trending", "Twitter", "Wallet", + "AsyncAccount", "AsyncCalendar", "AsyncEvents", "AsyncRank", "AsyncTrending", + "AsyncTwitter", "AsyncWallet", +] # fmt: skip diff --git a/src/futurenews/resources/_calls.py b/src/futurenews/resources/_calls.py new file mode 100644 index 0000000..eb506d8 --- /dev/null +++ b/src/futurenews/resources/_calls.py @@ -0,0 +1,94 @@ +"""Pure builders: arguments in, :class:`~futurenews._base.Call` out. + +No I/O lives here, so every endpoint's request shape is unit-testable and +shared by the sync and async clients. To add an endpoint, add a builder here, +then one thin method in ``sync.py`` and one in ``asynchronous.py``. +""" + +from __future__ import annotations + +from collections.abc import Iterable, Sequence +from datetime import date +from typing import Any, TypeVar +from urllib.parse import quote + +from pydantic import BaseModel + +from .._base import Call +from ..models import RankRequest, TrendingRequest, iso_date + +M = TypeVar("M", bound=BaseModel) + + +def merge(model: type[M], request: M | None, overrides: dict[str, Any]) -> M: + """Combine an optional prebuilt request with keyword overrides (validated).""" + base = request or model() + return model(**{**base.model_dump(), **overrides}) + + +def trending(request: TrendingRequest | None, overrides: dict[str, Any]) -> Call: + """``POST /events/api/trending/list``.""" + body = merge(TrendingRequest, request, overrides).to_body() + return Call("POST", "/events/api/trending/list", json=body) + + +def rank(request: RankRequest | None, overrides: dict[str, Any]) -> Call: + """``POST /events/api/rank``.""" + body = merge(RankRequest, request, overrides).to_body() + return Call("POST", "/events/api/rank", json=body) + + +def _slug(slug: str) -> str: + if not isinstance(slug, str) or not slug.strip(): + raise ValueError("slug must be a non-empty string") + return quote(slug.strip(), safe="") # a slug can never escape its path segment + + +def event(slug: str) -> Call: + """``GET /api/v1/event/polymarket/{slug}``.""" + return Call("GET", f"/api/v1/event/polymarket/{_slug(slug)}") + + +def calendar(category: str, from_date: date | str, to_date: date | str) -> Call: + """``GET /api/v1/finance_calendar/polymarket``.""" + if not category or not category.strip(): + raise ValueError("category must be a non-empty string") + params = ( + ("category", category.strip()), + ("from", iso_date(from_date, "from_date")), + ("to", iso_date(to_date, "to_date")), + ) + return Call("GET", "/api/v1/finance_calendar/polymarket", params=params) + + +def twitter_activity(event_slug: str, limit: int, cursor: str) -> Call: + """``GET /fds/api/v1/market/twitter/activity/list``.""" + if isinstance(limit, bool) or not isinstance(limit, int) or not 1 <= limit <= 100: + raise ValueError("limit must be an integer between 1 and 100") + if not event_slug or not event_slug.strip(): + raise ValueError("event_slug must be a non-empty string") + params = (("limit", str(limit)), ("cursor", cursor), ("event_slug", event_slug.strip())) + return Call("GET", "/fds/api/v1/market/twitter/activity/list", params=params) + + +def wallet_balances( + wallet_address: str, + chain: str, + token_addresses: Iterable[str], + token_ids: Iterable[str], +) -> Call: + """``GET /td/api/v1/wallet/balances`` (needs auth). Repeated params are sent as-is.""" + if not wallet_address or not wallet_address.strip(): + raise ValueError("wallet_address must be a non-empty string") + params: list[tuple[str, str]] = [("chain", chain), ("wallet_address", wallet_address.strip())] + params += [("token_addresses", str(a)) for a in token_addresses] + params += [("token_ids", str(i)) for i in token_ids] + return Call("GET", "/td/api/v1/wallet/balances", params=tuple(params), auth=True) + + +def user_info() -> Call: + """``POST /account/user_info`` (needs auth, empty body).""" + return Call("POST", "/account/user_info", auth=True) + + +Strs = Sequence[str] diff --git a/src/futurenews/resources/asynchronous.py b/src/futurenews/resources/asynchronous.py new file mode 100644 index 0000000..d0333f7 --- /dev/null +++ b/src/futurenews/resources/asynchronous.py @@ -0,0 +1,86 @@ +"""Asynchronous resource objects (``client.trending``, ``client.rank``...).""" + +from __future__ import annotations + +from collections.abc import Iterable +from datetime import date +from typing import TYPE_CHECKING, Any + +from ..models import ApiResponse, RankRequest, RankResponse, TrendingRequest, TrendingResponse +from . import _calls + +if TYPE_CHECKING: + from ..client import AsyncFutureNews + + +class _Resource: + def __init__(self, client: AsyncFutureNews) -> None: + self._client = client + + +class Trending(_Resource): + """Trending markets: ``POST /events/api/trending/list``.""" + + async def list(self, request: TrendingRequest | None = None, **overrides: Any) -> TrendingResponse: + """Fetch trending markets. ``overrides`` are TrendingRequest fields (e.g. ``limit=10``). + + Raises: + ValueError: invalid options (checked before any request is sent). + """ + payload = await self._client._send(_calls.trending(request, overrides)) + return TrendingResponse.from_payload(payload) + + +class Rank(_Resource): + """Ranked market lists (new, trending...): ``POST /events/api/rank``.""" + + async def list(self, request: RankRequest | None = None, **overrides: Any) -> RankResponse: + """Fetch a ranked list. ``overrides`` are RankRequest fields (e.g. ``rank_type="new"``).""" + return RankResponse.from_payload(await self._client._send(_calls.rank(request, overrides))) + + +class Events(_Resource): + """Single event details.""" + + async def get(self, slug: str) -> ApiResponse: + """Fetch one Polymarket-backed event by slug (``GET /api/v1/event/polymarket/{slug}``).""" + return ApiResponse.from_payload(await self._client._send(_calls.event(slug))) + + +class Calendar(_Resource): + """Finance calendar.""" + + async def get(self, category: str, from_date: date | str, to_date: date | str) -> ApiResponse: + """Fetch calendar entries, e.g. ``category="earnings"`` between two dates.""" + return ApiResponse.from_payload(await self._client._send(_calls.calendar(category, from_date, to_date))) + + +class Twitter(_Resource): + """Twitter/X activity attached to a market.""" + + async def activity(self, event_slug: str, limit: int = 10, cursor: str = "") -> ApiResponse: + """Fetch a page of tweets for an event. Pass the previous ``cursor`` to page.""" + return ApiResponse.from_payload(await self._client._send(_calls.twitter_activity(event_slug, limit, cursor))) + + +class Wallet(_Resource): + """On-chain wallet data. Requires ``auth_token``.""" + + async def balances( + self, + wallet_address: str, + chain: str = "polygon", + token_addresses: Iterable[str] = (), + token_ids: Iterable[str] = (), + ) -> ApiResponse: + """Fetch token balances for a wallet (``GET /td/api/v1/wallet/balances``).""" + call = _calls.wallet_balances(wallet_address, chain, token_addresses, token_ids) + return ApiResponse.from_payload(await self._client._send(call)) + + +class Account(_Resource): + """The signed-in account. Requires ``auth_token``.""" + + async def user_info(self) -> ApiResponse: + """Fetch the current user's profile (``POST /account/user_info``).""" + return ApiResponse.from_payload(await self._client._send(_calls.user_info())) diff --git a/src/futurenews/resources/sync.py b/src/futurenews/resources/sync.py new file mode 100644 index 0000000..1a7cbcd --- /dev/null +++ b/src/futurenews/resources/sync.py @@ -0,0 +1,86 @@ +"""Synchronous resource objects (``client.trending``, ``client.rank``...).""" + +from __future__ import annotations + +from collections.abc import Iterable +from datetime import date +from typing import TYPE_CHECKING, Any + +from ..models import ApiResponse, RankRequest, RankResponse, TrendingRequest, TrendingResponse +from . import _calls + +if TYPE_CHECKING: + from ..client import FutureNews + + +class _Resource: + def __init__(self, client: FutureNews) -> None: + self._client = client + + +class Trending(_Resource): + """Trending markets: ``POST /events/api/trending/list``.""" + + def list(self, request: TrendingRequest | None = None, **overrides: Any) -> TrendingResponse: + """Fetch trending markets. ``overrides`` are TrendingRequest fields (e.g. ``limit=10``). + + Raises: + ValueError: invalid options (checked before any request is sent). + """ + payload = self._client._send(_calls.trending(request, overrides)) + return TrendingResponse.from_payload(payload) + + +class Rank(_Resource): + """Ranked market lists (new, trending...): ``POST /events/api/rank``.""" + + def list(self, request: RankRequest | None = None, **overrides: Any) -> RankResponse: + """Fetch a ranked list. ``overrides`` are RankRequest fields (e.g. ``rank_type="new"``).""" + return RankResponse.from_payload(self._client._send(_calls.rank(request, overrides))) + + +class Events(_Resource): + """Single event details.""" + + def get(self, slug: str) -> ApiResponse: + """Fetch one Polymarket-backed event by slug (``GET /api/v1/event/polymarket/{slug}``).""" + return ApiResponse.from_payload(self._client._send(_calls.event(slug))) + + +class Calendar(_Resource): + """Finance calendar.""" + + def get(self, category: str, from_date: date | str, to_date: date | str) -> ApiResponse: + """Fetch calendar entries, e.g. ``category="earnings"`` between two dates.""" + return ApiResponse.from_payload(self._client._send(_calls.calendar(category, from_date, to_date))) + + +class Twitter(_Resource): + """Twitter/X activity attached to a market.""" + + def activity(self, event_slug: str, limit: int = 10, cursor: str = "") -> ApiResponse: + """Fetch a page of tweets for an event. Pass the previous ``cursor`` to page.""" + return ApiResponse.from_payload(self._client._send(_calls.twitter_activity(event_slug, limit, cursor))) + + +class Wallet(_Resource): + """On-chain wallet data. Requires ``auth_token``.""" + + def balances( + self, + wallet_address: str, + chain: str = "polygon", + token_addresses: Iterable[str] = (), + token_ids: Iterable[str] = (), + ) -> ApiResponse: + """Fetch token balances for a wallet (``GET /td/api/v1/wallet/balances``).""" + call = _calls.wallet_balances(wallet_address, chain, token_addresses, token_ids) + return ApiResponse.from_payload(self._client._send(call)) + + +class Account(_Resource): + """The signed-in account. Requires ``auth_token``.""" + + def user_info(self) -> ApiResponse: + """Fetch the current user's profile (``POST /account/user_info``).""" + return ApiResponse.from_payload(self._client._send(_calls.user_info())) diff --git a/src/futurenews/resources/trending.py b/src/futurenews/resources/trending.py deleted file mode 100644 index a368ef2..0000000 --- a/src/futurenews/resources/trending.py +++ /dev/null @@ -1,65 +0,0 @@ -"""``trending`` resource: sync and async variants.""" - -from __future__ import annotations - -from typing import TYPE_CHECKING, Any - -import httpx - -from .._base import TRENDING_PATH, build_params, parse_response -from ..errors import ConnectionFailure -from ..models import TrendingRequest, TrendingResponse - -if TYPE_CHECKING: - from ..client import AsyncFutureNews, FutureNews - - -def _request(request: TrendingRequest | None, overrides: dict[str, Any]) -> TrendingRequest: - """Merge an optional request object with keyword overrides (validates limit).""" - base = request or TrendingRequest() - return TrendingRequest(**{**base.model_dump(), **overrides}) - - -class Trending: - """Trending markets (sync). Access as ``client.trending``.""" - - def __init__(self, client: FutureNews) -> None: - self._client = client - - def list(self, request: TrendingRequest | None = None, **overrides: Any) -> TrendingResponse: - """Fetch trending markets. - - Args: - request: Optional prebuilt :class:`TrendingRequest`. - **overrides: Any TrendingRequest field, e.g. ``limit=10``. - - Raises: - ValueError: invalid ``limit`` (checked before any request is sent). - BlockedError / RateLimitError / APIError / ConnectionFailure. - """ - body = _request(request, overrides).to_body() - try: - resp = self._client._http.post( - TRENDING_PATH, params=build_params(self._client.device_id), json=body - ) - except httpx.TransportError as exc: - raise ConnectionFailure(str(exc)) from exc - return TrendingResponse.from_payload(parse_response(resp)) - - -class AsyncTrending: - """Trending markets (async). Access as ``client.trending``.""" - - def __init__(self, client: AsyncFutureNews) -> None: - self._client = client - - async def list(self, request: TrendingRequest | None = None, **overrides: Any) -> TrendingResponse: - """Async version of :meth:`Trending.list`.""" - body = _request(request, overrides).to_body() - try: - resp = await self._client._http.post( - TRENDING_PATH, params=build_params(self._client.device_id), json=body - ) - except httpx.TransportError as exc: - raise ConnectionFailure(str(exc)) from exc - return TrendingResponse.from_payload(parse_response(resp)) diff --git a/tests/test_client.py b/tests/test_client.py index 6b2c77a..51e82de 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -93,9 +93,7 @@ async def test_async_roundtrip_and_errors(): @respx.mock def test_503_cloudflare_challenge_is_blocked(): - respx.post(URL).mock( - return_value=httpx.Response(503, headers={"cf-mitigated": "challenge"}, text="") - ) + respx.post(URL).mock(return_value=httpx.Response(503, headers={"cf-mitigated": "challenge"}, text="")) with pytest.raises(BlockedError), FutureNews() as c: c.trending.list() @@ -103,9 +101,7 @@ def test_503_cloudflare_challenge_is_blocked(): @respx.mock def test_200_html_challenge_is_blocked(): respx.post(URL).mock( - return_value=httpx.Response( - 200, headers={"content-type": "text/html"}, text="Just a moment" - ) + return_value=httpx.Response(200, headers={"content-type": "text/html"}, text="Just a moment") ) with pytest.raises(BlockedError), FutureNews() as c: c.trending.list() diff --git a/tests/test_endpoints.py b/tests/test_endpoints.py new file mode 100644 index 0000000..a426044 --- /dev/null +++ b/tests/test_endpoints.py @@ -0,0 +1,182 @@ +"""Request-shape tests for every endpoint (respx; no network).""" + +import json +from datetime import date + +import httpx +import pytest +import respx + +from futurenews import ( + ApiResponse, + AsyncFutureNews, + AuthenticationError, + AuthRequiredError, + FutureNews, + RankRequest, +) + +B = "https://future.news" +OK = {"data": {"hello": "world"}, "code": 0} +FAKE_WALLET = "0x" + "ab" * 20 + + +def sent(route): + return route.calls[0].request + + +@respx.mock +def test_rank_list_body_and_no_market_status(): + route = respx.post(f"{B}/events/api/rank").mock(return_value=httpx.Response(200, json={"data": [{"id": 1}]})) + with FutureNews() as c: + res = c.rank.list(rank_type="new", order_by="create_timestamp", exclude_series=True, exclude_tags=["102127"]) + body = json.loads(sent(route).content) + assert body == { + "exclude_series": True, + "rank_type": "new", + "categories": [], + "subcategories": [], + "status": ["active"], + "order_by": "create_timestamp", + "limit": 100, + "exclude_tags": ["102127"], + } + assert len(res.items) == 1 + + +def test_rank_request_defaults_omit_empty_optionals(): + body = RankRequest().to_body() + assert "exclude_tags" not in body and "market_status" not in body + with pytest.raises(ValueError): + RankRequest(limit=0) + with pytest.raises(ValueError): + RankRequest(bogus=1) + + +@respx.mock +def test_events_get_path_and_slug_quoting(): + route = respx.get(f"{B}/api/v1/event/polymarket/dota2-liquid-ty-2026-11-29").mock( + return_value=httpx.Response(200, json=OK) + ) + with FutureNews() as c: + res = c.events.get("dota2-liquid-ty-2026-11-29") + assert isinstance(res, ApiResponse) and res.data == {"hello": "world"} and res.raw == OK + assert dict(sent(route).url.params)["from_app"] == "future-web" + + +@respx.mock +def test_events_slug_cannot_escape_path(): + route = respx.get(url__regex=r".*").mock(return_value=httpx.Response(200, json=OK)) + with FutureNews() as c: + c.events.get("a/../b?x=1") + assert "/api/v1/event/polymarket/a%2F..%2Fb%3Fx%3D1" in str(sent(route).url) + + +@pytest.mark.parametrize("slug", ["", " "]) +def test_events_empty_slug_rejected(slug): + with pytest.raises(ValueError), FutureNews() as c: + c.events.get(slug) + + +@respx.mock +def test_calendar_params_accept_dates_and_strings(): + route = respx.get(f"{B}/api/v1/finance_calendar/polymarket").mock(return_value=httpx.Response(200, json=OK)) + with FutureNews() as c: + c.calendar.get(category="earnings", from_date=date(2026, 11, 29), to_date="2026-12-29") + q = dict(sent(route).url.params) + assert (q["category"], q["from"], q["to"]) == ("earnings", "2026-11-29", "2026-12-29") + + +def test_calendar_bad_date_rejected(): + with pytest.raises(ValueError), FutureNews() as c: + c.calendar.get(category="earnings", from_date="29/11/2026", to_date="2026-12-29") + + +@respx.mock +def test_twitter_activity_params(): + route = respx.get(f"{B}/fds/api/v1/market/twitter/activity/list").mock(return_value=httpx.Response(200, json=OK)) + with FutureNews() as c: + c.twitter.activity("btc-up-or-down-5m", limit=10) + q = dict(sent(route).url.params) + assert q["event_slug"] == "btc-up-or-down-5m" and q["limit"] == "10" and q["cursor"] == "" + assert "authorization" not in sent(route).headers + + +def test_twitter_limit_validated(): + with pytest.raises(ValueError), FutureNews() as c: + c.twitter.activity("x", limit=0) + + +@respx.mock +def test_wallet_balances_repeats_params_and_sends_bearer(): + route = respx.get(f"{B}/td/api/v1/wallet/balances").mock(return_value=httpx.Response(200, json=OK)) + with FutureNews(auth_token="fake-token") as c: + c.wallet.balances(FAKE_WALLET, token_addresses=["0x1"], token_ids=["11", "22"]) + req = sent(route) + assert req.headers["authorization"] == "Bearer fake-token" + assert req.url.params.get_list("token_ids") == ["11", "22"] + assert req.url.params["chain"] == "polygon" and req.url.params["wallet_address"] == FAKE_WALLET + + +def test_auth_required_before_any_request(): + with respx.mock(assert_all_called=False) as m: + route = m.get(f"{B}/td/api/v1/wallet/balances").mock(return_value=httpx.Response(200, json=OK)) + with pytest.raises(AuthRequiredError), FutureNews() as c: + c.wallet.balances(FAKE_WALLET) + with pytest.raises(AuthRequiredError), FutureNews() as c: + c.account.user_info() + assert not route.called + + +@respx.mock +def test_user_info_is_empty_post_with_bearer(): + route = respx.post(f"{B}/account/user_info").mock(return_value=httpx.Response(200, json=OK)) + with FutureNews(auth_token="fake-token") as c: + res = c.account.user_info() + req = sent(route) + assert req.content == b"" and req.headers["authorization"] == "Bearer fake-token" + assert res.data == {"hello": "world"} + + +@respx.mock +def test_401_is_authentication_error(): + respx.post(f"{B}/account/user_info").mock(return_value=httpx.Response(401, text="expired")) + with pytest.raises(AuthenticationError) as e, FutureNews(auth_token="old") as c: + c.account.user_info() + assert e.value.status_code == 401 + + +def test_token_is_not_leaked_in_repr(): + c = FutureNews(auth_token="super-secret") + assert "super-secret" not in repr(c) + c.close() + + +@respx.mock +def test_non_dict_payload_wrapped(): + respx.get(f"{B}/api/v1/event/polymarket/x").mock(return_value=httpx.Response(200, json=[1, 2])) + with FutureNews() as c: + assert c.events.get("x").data == [1, 2] + + +@respx.mock +async def test_async_all_resources(): + for method, path in [ + ("post", "/events/api/rank"), + ("get", "/api/v1/event/polymarket/s"), + ("get", "/api/v1/finance_calendar/polymarket"), + ("get", "/fds/api/v1/market/twitter/activity/list"), + ("get", "/td/api/v1/wallet/balances"), + ("post", "/account/user_info"), + ]: + getattr(respx, method)(f"{B}{path}").mock(return_value=httpx.Response(200, json=OK)) + async with AsyncFutureNews(auth_token="t") as c: + assert (await c.rank.list(limit=1)).items == [] + assert (await c.events.get("s")).data + assert (await c.calendar.get("earnings", "2026-11-29", "2026-12-29")).data + assert (await c.twitter.activity("s")).data + assert (await c.wallet.balances(FAKE_WALLET)).data + assert (await c.account.user_info()).data + async with AsyncFutureNews() as c: + with pytest.raises(AuthRequiredError): + await c.account.user_info() From df22ffe804cb921ae2aa99d982d70d266c60cf79 Mon Sep 17 00:00:00 2001 From: Vigo Walker Date: Sun, 29 Nov 2026 15:44:51 +0100 Subject: [PATCH 2/3] docs: detailed per-endpoint pages, authentication guide, API reference Co-Authored-By: Claude Sonnet 5.5 --- CHANGELOG.md | 5 +++ README.md | 10 +++++ docs/authentication.md | 36 +++++++++++++++++ docs/contributing.md | 2 +- docs/endpoints/account.md | 65 +++++++++++++++++++++++++++++++ docs/endpoints/calendar.md | 70 +++++++++++++++++++++++++++++++++ docs/endpoints/events.md | 67 ++++++++++++++++++++++++++++++++ docs/endpoints/index.md | 28 ++++++++++++++ docs/endpoints/rank.md | 78 +++++++++++++++++++++++++++++++++++++ docs/endpoints/trending.md | 79 ++++++++++++++++++++++++++++++-------- docs/endpoints/twitter.md | 70 +++++++++++++++++++++++++++++++++ docs/endpoints/wallet.md | 78 +++++++++++++++++++++++++++++++++++++ docs/errors.md | 6 +-- docs/quickstart.md | 2 + docs/reference.md | 28 ++++++++++++++ examples/event_and_rank.py | 14 +++++++ mkdocs.yml | 11 +++++- 17 files changed, 627 insertions(+), 22 deletions(-) create mode 100644 docs/authentication.md create mode 100644 docs/endpoints/account.md create mode 100644 docs/endpoints/calendar.md create mode 100644 docs/endpoints/events.md create mode 100644 docs/endpoints/index.md create mode 100644 docs/endpoints/rank.md create mode 100644 docs/endpoints/twitter.md create mode 100644 docs/endpoints/wallet.md create mode 100644 docs/reference.md create mode 100644 examples/event_and_rank.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 41b8e0f..e420d8f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,4 +1,9 @@ # Changelog +## Unreleased +- New endpoints: `rank.list`, `events.get`, `calendar.get`, `twitter.activity`, `wallet.balances`, `account.user_info`. +- `auth_token` client option, `AuthRequiredError`, `AuthenticationError`. +- Detailed per-endpoint docs and an authentication guide. + ## 0.1.0 - Initial release: sync + async clients, `trending.list`, typed models, error hierarchy. By Chipa dev team. diff --git a/README.md b/README.md index ec4ecfc..dae22e6 100644 --- a/README.md +++ b/README.md @@ -19,6 +19,16 @@ with FutureNews() as client: ``` +## Endpoints + +| Resource | Auth | +|---|---| +| `client.trending.list()` · `client.rank.list()` | no | +| `client.events.get(slug)` · `client.calendar.get(...)` · `client.twitter.activity(...)` | no | +| `client.wallet.balances(...)` · `client.account.user_info()` | bearer `auth_token` | + +Every method has an `await`-able twin on `AsyncFutureNews`. Full docs: https://chipadevteam.github.io/FutureNewsAPI/ + ## Why this exists Future News has no official Python SDK. This library gives you typed models, sync and async clients and clear errors for the Future News trending markets API. diff --git a/docs/authentication.md b/docs/authentication.md new file mode 100644 index 0000000..ed1158b --- /dev/null +++ b/docs/authentication.md @@ -0,0 +1,36 @@ +--- +title: Future News API authentication in Python (bearer token) +description: How to authenticate Future News API calls from Python with the futurenews library: bearer tokens, expiry, and keeping secrets safe. +--- + +# Authentication + +Public endpoints (trending, rank, events, calendar, Twitter) need no login. **Wallet** and **account** endpoints need a bearer access token. + +```python +import os +from futurenews import FutureNews + +client = FutureNews(auth_token=os.environ["FUTURENEWS_TOKEN"]) +``` + +- The token is sent as `Authorization: Bearer ` only on endpoints that need it. +- It is hidden from `repr(client)` and never logged. +- Calling an authenticated endpoint without a token raises `AuthRequiredError` before any network request. +- An invalid or expired token raises `AuthenticationError` (HTTP 401). + +## Getting a token +The library does not log in for you. Access tokens are issued to your browser session when you are signed in at [future.news](https://future.news/41L85FOV); they are short-lived (about 30 minutes), so refresh and rebuild the client when you see `AuthenticationError`. + +!!! danger "Treat tokens and cookies like passwords" + Never commit them, paste them in issues, or share curl commands that contain them. Use environment variables or a secrets manager. If a token leaks, sign out of Future News to invalidate your session. + +--- + +**Related:** [Authentication](authentication.md) · [Errors & Cloudflare](errors.md) · [All endpoints](endpoints/index.md) + +!!! tip "Don't have a Future News account?" + [Sign up with our link](https://future.news/41L85FOV). It's free for you and supports this library. + +!!! info "Build something with this data" + Chipa dev team builds trading bots and tools: [Bot development](https://chipatrade.com/services/bot-development) · [ChipaX exchange](https://exchange.chipatrade.com/en/trade/BTC) · [Chipa Editor](https://chipaeditor.com) · [Discord](https://discord.com/invite/qwQZ7rHzGb) diff --git a/docs/contributing.md b/docs/contributing.md index 42e239e..00f9ea6 100644 --- a/docs/contributing.md +++ b/docs/contributing.md @@ -12,6 +12,6 @@ pip install -e ".[dev,docs]" pytest && ruff check . && mypy src ``` -Adding an endpoint: add models in `models.py`, a resource in `resources/`, wire it in `client.py`, write respx tests first, add a docs page. Questions? [Discord](https://discord.com/invite/qwQZ7rHzGb). +Adding an endpoint: write respx tests first, add a pure builder returning a `Call` in `resources/_calls.py`, then one thin method each in `resources/sync.py` and `resources/asynchronous.py`, and a docs page under `docs/endpoints/` (add it to `mkdocs.yml`). Questions? [Discord](https://discord.com/invite/qwQZ7rHzGb). Supporting the project is free: [sign up to Future News with our link](https://future.news/41L85FOV). diff --git a/docs/endpoints/account.md b/docs/endpoints/account.md new file mode 100644 index 0000000..92b71fd --- /dev/null +++ b/docs/endpoints/account.md @@ -0,0 +1,65 @@ +--- +title: Future News account API in Python: user info +description: Use client.account.user_info to fetch the signed-in Future News user profile from Python. Requires an auth token. +--- + +# Account: `account.user_info` + +Fetches the profile of the signed-in user. + +| | | +|---|---| +| HTTP | `POST https://future.news/account/user_info` (empty body) | +| Auth | **required**: `FutureNews(auth_token=...)`, see [Authentication](../authentication.md) | +| Returns | `ApiResponse` | + +## Example (sync) + +```python +import os +from futurenews import FutureNews, AuthenticationError + +with FutureNews(auth_token=os.environ["FUTURENEWS_TOKEN"]) as client: + try: + print(client.account.user_info().data) + except AuthenticationError: + print("Token expired: get a fresh one and build a new client.") +``` + +## Example (async) + +```python +import asyncio, os +from futurenews import AsyncFutureNews + + +async def main(): + async with AsyncFutureNews(auth_token=os.environ["FUTURENEWS_TOKEN"]) as client: + print((await client.account.user_info()).data) + + +asyncio.run(main()) +``` + +!!! warning "Personal data" + The response contains your account details. Don't paste it into public issues or logs. + +## Equivalent request + +```bash +curl -X POST 'https://future.news/account/user_info?from_app=future-web&os=web' \ + -H 'authorization: Bearer ' -H 'content-length: 0' +``` + +!!! note "About the response" + Future News does not publish a schema. The library returns the payload as an [`ApiResponse`](../reference.md#futurenews.models.ApiResponse): `.data` holds the `"data"` field (or the whole JSON when there is none) and `.raw` always holds the untouched JSON. Unknown fields are never dropped. Field-level models are added once sample responses are confirmed, so treat the shape as subject to change. + +--- + +**Related:** [Authentication](../authentication.md) · [Errors & Cloudflare](../errors.md) · [All endpoints](../endpoints/index.md) + +!!! tip "Don't have a Future News account?" + [Sign up with our link](https://future.news/41L85FOV). It's free for you and supports this library. + +!!! info "Build something with this data" + Chipa dev team builds trading bots and tools: [Bot development](https://chipatrade.com/services/bot-development) · [ChipaX exchange](https://exchange.chipatrade.com/en/trade/BTC) · [Chipa Editor](https://chipaeditor.com) · [Discord](https://discord.com/invite/qwQZ7rHzGb) diff --git a/docs/endpoints/calendar.md b/docs/endpoints/calendar.md new file mode 100644 index 0000000..ad7d9ae --- /dev/null +++ b/docs/endpoints/calendar.md @@ -0,0 +1,70 @@ +--- +title: Future News finance calendar API in Python (earnings and more) +description: Use client.calendar.get to fetch the Future News finance calendar (earnings and other categories) between two dates from Python. +--- + +# Finance calendar: `calendar.get` + +Fetches the finance calendar shown on the *Earnings calendar* tab of the trending page. + +| | | +|---|---| +| HTTP | `GET https://future.news/api/v1/finance_calendar/polymarket` | +| Auth | none | +| Returns | `ApiResponse` | + +## Parameters + +| Parameter | Type | Notes | +|---|---|---| +| `category` | `str` | e.g. `"earnings"`. Non-empty. | +| `from_date` | `date \| str` | start, sent as `from=YYYY-MM-DD` | +| `to_date` | `date \| str` | end, sent as `to=YYYY-MM-DD` | + +Strings must be ISO dates (`YYYY-MM-DD`); anything else raises `ValueError` before a request is made. (`from_date` is used because `from` is a Python keyword.) + +## Example (sync) + +```python +from datetime import date, timedelta +from futurenews import FutureNews + +with FutureNews() as client: + today = date.today() + cal = client.calendar.get("earnings", today, today + timedelta(days=30)) + print(cal.data) +``` + +## Example (async) + +```python +import asyncio +from futurenews import AsyncFutureNews + + +async def main(): + async with AsyncFutureNews() as client: + print((await client.calendar.get("earnings", "2026-11-29", "2026-12-29")).data) + + +asyncio.run(main()) +``` + +## Equivalent request + +```bash +curl 'https://future.news/api/v1/finance_calendar/polymarket?category=earnings&from=2026-11-29&to=2026-12-29&from_app=future-web&os=web' +``` + +!!! note "About the response" + Future News does not publish a schema. The library returns the payload as an [`ApiResponse`](../reference.md#futurenews.models.ApiResponse): `.data` holds the `"data"` field (or the whole JSON when there is none) and `.raw` always holds the untouched JSON. Unknown fields are never dropped. Field-level models are added once sample responses are confirmed, so treat the shape as subject to change. + +--- + +**Related:** [Authentication](../authentication.md) · [Errors & Cloudflare](../errors.md) · [All endpoints](../endpoints/index.md) + +!!! tip "Don't have a Future News account?" + [Sign up with our link](https://future.news/41L85FOV). It's free for you and supports this library. + +!!! info "Build something with this data" + Chipa dev team builds trading bots and tools: [Bot development](https://chipatrade.com/services/bot-development) · [ChipaX exchange](https://exchange.chipatrade.com/en/trade/BTC) · [Chipa Editor](https://chipaeditor.com) · [Discord](https://discord.com/invite/qwQZ7rHzGb) diff --git a/docs/endpoints/events.md b/docs/endpoints/events.md new file mode 100644 index 0000000..c49f8ba --- /dev/null +++ b/docs/endpoints/events.md @@ -0,0 +1,67 @@ +--- +title: Future News event API in Python: get a market by slug +description: Use client.events.get(slug) to fetch a single Future News (Polymarket-backed) event by its slug from Python. +--- + +# Event details: `events.get` + +Fetches one event (a market page on Future News) by its **slug**, the last part of the event URL. + +| | | +|---|---| +| HTTP | `GET https://future.news/api/v1/event/polymarket/{slug}` | +| Auth | none | +| Returns | `ApiResponse` | + +## Parameters + +| Parameter | Type | Notes | +|---|---|---| +| `slug` | `str` | e.g. `"dota2-liquid-ty-2026-11-29"`. Must be non-empty. It is URL-encoded, so it can never alter the request path. | + +## Example (sync) + +```python +from futurenews import FutureNews + +with FutureNews() as client: + event = client.events.get("dota2-liquid-ty-2026-11-29") + print(event.data) +``` + +## Example (async) + +```python +import asyncio +from futurenews import AsyncFutureNews + + +async def main(): + async with AsyncFutureNews() as client: + print((await client.events.get("dota2-liquid-ty-2026-11-29")).data) + + +asyncio.run(main()) +``` + +## Where do slugs come from? +Call [`rank.list`](rank.md) or [`trending.list`](trending.md) and read the slug of each entry, or copy it from the event URL on future.news. + +## Equivalent request + +```bash +curl 'https://future.news/api/v1/event/polymarket/dota2-liquid-ty-2026-11-29?from_app=future-web&os=web' +``` + +!!! note "About the response" + Future News does not publish a schema. The library returns the payload as an [`ApiResponse`](../reference.md#futurenews.models.ApiResponse): `.data` holds the `"data"` field (or the whole JSON when there is none) and `.raw` always holds the untouched JSON. Unknown fields are never dropped. Field-level models are added once sample responses are confirmed, so treat the shape as subject to change. + +--- + +**Related:** [Authentication](../authentication.md) · [Errors & Cloudflare](../errors.md) · [All endpoints](../endpoints/index.md) + +!!! tip "Don't have a Future News account?" + [Sign up with our link](https://future.news/41L85FOV). It's free for you and supports this library. + +!!! info "Build something with this data" + Chipa dev team builds trading bots and tools: [Bot development](https://chipatrade.com/services/bot-development) · [ChipaX exchange](https://exchange.chipatrade.com/en/trade/BTC) · [Chipa Editor](https://chipaeditor.com) · [Discord](https://discord.com/invite/qwQZ7rHzGb) diff --git a/docs/endpoints/index.md b/docs/endpoints/index.md new file mode 100644 index 0000000..b9c0927 --- /dev/null +++ b/docs/endpoints/index.md @@ -0,0 +1,28 @@ +--- +title: Future News API endpoints (Python reference) +description: All Future News API endpoints supported by the futurenews Python library: trending, rank, events, calendar, Twitter activity, wallet and account. +--- + +# Endpoints + +| Resource | Method | Auth | Page | +|---|---|---|---| +| `client.trending.list()` | `POST /events/api/trending/list` | no | [Trending](trending.md) | +| `client.rank.list()` | `POST /events/api/rank` | no | [Rank](rank.md) | +| `client.events.get(slug)` | `GET /api/v1/event/polymarket/{slug}` | no | [Events](events.md) | +| `client.calendar.get(...)` | `GET /api/v1/finance_calendar/polymarket` | no | [Calendar](calendar.md) | +| `client.twitter.activity(...)` | `GET /fds/api/v1/market/twitter/activity/list` | no | [Twitter](twitter.md) | +| `client.wallet.balances(...)` | `GET /td/api/v1/wallet/balances` | **yes** | [Wallet](wallet.md) | +| `client.account.user_info()` | `POST /account/user_info` | **yes** | [Account](account.md) | + +Every method has an identical `await`-able twin on `AsyncFutureNews`. + +--- + +**Related:** [Authentication](../authentication.md) · [Errors & Cloudflare](../errors.md) · [All endpoints](../endpoints/index.md) + +!!! tip "Don't have a Future News account?" + [Sign up with our link](https://future.news/41L85FOV). It's free for you and supports this library. + +!!! info "Build something with this data" + Chipa dev team builds trading bots and tools: [Bot development](https://chipatrade.com/services/bot-development) · [ChipaX exchange](https://exchange.chipatrade.com/en/trade/BTC) · [Chipa Editor](https://chipaeditor.com) · [Discord](https://discord.com/invite/qwQZ7rHzGb) diff --git a/docs/endpoints/rank.md b/docs/endpoints/rank.md new file mode 100644 index 0000000..59cc465 --- /dev/null +++ b/docs/endpoints/rank.md @@ -0,0 +1,78 @@ +--- +title: Future News rank API in Python: new, trending and ranked markets +description: Use client.rank.list to fetch ranked Future News market lists (new, trending, by volume) from Python. Sync and async examples. +--- + +# Rank list: `rank.list` + +Fetches the ranked market lists behind the tabs on the Future News trending page (for example **New** or **Trending**). It is the same list shape as [`trending.list`](trending.md), with a few extra filters. + +| | | +|---|---| +| HTTP | `POST https://future.news/events/api/rank` | +| Auth | none | +| Returns | `RankResponse` (`.items`, a list of entries; unknown fields kept) | + +## Parameters + +Pass them as keyword arguments or build a `RankRequest`. + +| Parameter | Type | Default | Notes | +|---|---|---|---| +| `rank_type` | `str` | `"trending"` | e.g. `"new"`, `"trending"` | +| `order_by` | `str` | `"volume24h"` | e.g. `"create_timestamp"` for newest first | +| `limit` | `int` | `100` | 1 to 100 (strict integer) | +| `status` | `list[str]` | `["active"]` | | +| `categories`, `subcategories` | `list[str]` | `[]` | | +| `exclude_series` | `bool` | `False` | hide recurring series markets | +| `exclude_tags` | `list[str]` | `[]` | tag ids to hide; omitted from the body when empty | +| `market_status` | `str \| None` | `None` | omitted from the body when unset | + +Misspelled options raise `ValueError` before any request is sent. + +## Example (sync) + +```python +from futurenews import FutureNews + +with FutureNews() as client: + newest = client.rank.list(rank_type="new", order_by="create_timestamp", limit=20, exclude_series=True) + for item in newest.items: + print(item.model_dump()) +``` + +## Example (async) + +```python +import asyncio +from futurenews import AsyncFutureNews + + +async def main(): + async with AsyncFutureNews() as client: + res = await client.rank.list(rank_type="new", limit=20) + print(len(res.items)) + + +asyncio.run(main()) +``` + +## Equivalent request + +```bash +curl 'https://future.news/events/api/rank?from_app=future-web&os=web&app_lang=en-US' \ + -H 'content-type: application/json' \ + --data-raw '{"exclude_series":true,"rank_type":"new","categories":[],"subcategories":[],"status":["active"],"order_by":"create_timestamp","limit":100}' +``` + +The library adds the remaining query parameters (`device_id`, `client_id`, `app_ver`...) for you. If Cloudflare answers 403, see [Errors & Cloudflare](../errors.md). + +--- + +**Related:** [Authentication](../authentication.md) · [Errors & Cloudflare](../errors.md) · [All endpoints](../endpoints/index.md) + +!!! tip "Don't have a Future News account?" + [Sign up with our link](https://future.news/41L85FOV). It's free for you and supports this library. + +!!! info "Build something with this data" + Chipa dev team builds trading bots and tools: [Bot development](https://chipatrade.com/services/bot-development) · [ChipaX exchange](https://exchange.chipatrade.com/en/trade/BTC) · [Chipa Editor](https://chipaeditor.com) · [Discord](https://discord.com/invite/qwQZ7rHzGb) diff --git a/docs/endpoints/trending.md b/docs/endpoints/trending.md index f1c5cff..d05509d 100644 --- a/docs/endpoints/trending.md +++ b/docs/endpoints/trending.md @@ -1,30 +1,75 @@ --- title: Future News trending markets API in Python -description: Use client.trending.list to fetch trending markets from Future News with typed Python models. +description: Use client.trending.list to fetch trending markets from Future News with typed Python models. Sync and async examples. --- -# Future News trending markets API (`trending.list`) +# Trending markets: `trending.list` -Wraps `POST https://future.news/events/api/trending/list`. +Fetches the trending markets list shown on the Future News trending page. + +| | | +|---|---| +| HTTP | `POST https://future.news/events/api/trending/list` | +| Auth | none | +| Returns | `TrendingResponse` (`.items`; unknown fields kept) | + +## Parameters + +| Parameter | Type | Default | Notes | +|---|---|---|---| +| `limit` | `int` | `100` | 1 to 100 (strict integer), validated before the request | +| `order_by` | `str` | `"volume24h"` | | +| `rank_type` | `str` | `"trending"` | | +| `status` | `list[str]` | `["active"]` | | +| `market_status` | `str` | `"active"` | | +| `categories`, `subcategories` | `list[str]` | `[]` | | +| `exclude_series` | `bool` | `False` | | + +Misspelled options raise `ValueError`. + +## Example (sync) ```python -client.trending.list(limit=50, order_by="volume24h") +from futurenews import FutureNews + +with FutureNews() as client: + for item in client.trending.list(limit=10).items: + print(item.model_dump()) ``` -| Parameter | Default | Notes | -|---|---|---| -| `limit` | `100` | 1–100, validated before the request | -| `order_by` | `"volume24h"` | | -| `rank_type` | `"trending"` | | -| `status` | `["active"]` | | -| `market_status` | `"active"` | | -| `categories`, `subcategories` | `[]` | | -| `exclude_series` | `False` | | +## Example (async) + +```python +import asyncio +from futurenews import AsyncFutureNews + + +async def main(): + async with AsyncFutureNews() as client: + print(len((await client.trending.list(limit=10)).items)) -Response fields are kept as returned (models allow extra fields), so new Future News fields never break your code. -::: futurenews.models.TrendingRequest +asyncio.run(main()) +``` + +Need the "new" tab or tag filters? Use [`rank.list`](rank.md). + +## Equivalent request + +```bash +curl 'https://future.news/events/api/trending/list?from_app=future-web&os=web' \ + -H 'content-type: application/json' \ + --data-raw '{"exclude_series":false,"rank_type":"trending","categories":[],"subcategories":[],"status":["active"],"market_status":"active","order_by":"volume24h","limit":100}' +``` + +Blocked with 403? See [Errors & Cloudflare](../errors.md). + +--- + +**Related:** [Authentication](../authentication.md) · [All endpoints](index.md) -::: futurenews.models.TrendingResponse +!!! tip "Don't have a Future News account?" + [Sign up with our link](https://future.news/41L85FOV). It's free for you and supports this library. -[Open Future News](https://future.news/41L85FOV) · [Build a bot with Chipa](https://chipatrade.com/services/bot-development) +!!! info "Build something with this data" + Chipa dev team builds trading bots and tools: [Bot development](https://chipatrade.com/services/bot-development) · [ChipaX exchange](https://exchange.chipatrade.com/en/trade/BTC) · [Chipa Editor](https://chipaeditor.com) · [Discord](https://discord.com/invite/qwQZ7rHzGb) diff --git a/docs/endpoints/twitter.md b/docs/endpoints/twitter.md new file mode 100644 index 0000000..fbcd1cd --- /dev/null +++ b/docs/endpoints/twitter.md @@ -0,0 +1,70 @@ +--- +title: Future News Twitter/X activity API in Python +description: Use client.twitter.activity to page through the tweets attached to a Future News market from Python. +--- + +# Twitter/X activity: `twitter.activity` + +Fetches the tweet feed shown beside a market, newest first, with cursor pagination. + +| | | +|---|---| +| HTTP | `GET https://future.news/fds/api/v1/market/twitter/activity/list` | +| Auth | none | +| Returns | `ApiResponse` | + +## Parameters + +| Parameter | Type | Default | Notes | +|---|---|---|---| +| `event_slug` | `str` | required | e.g. `"btc-up-or-down-5m"`. Non-empty. | +| `limit` | `int` | `10` | 1 to 100 | +| `cursor` | `str` | `""` | empty for the first page; pass the cursor from the previous page to continue | + +## Example (sync) + +```python +from futurenews import FutureNews + +with FutureNews() as client: + page = client.twitter.activity("btc-up-or-down-5m", limit=10) + print(page.data) + # next page: client.twitter.activity("btc-up-or-down-5m", limit=10, cursor="") +``` + +## Example (async) + +```python +import asyncio +from futurenews import AsyncFutureNews + + +async def main(): + async with AsyncFutureNews() as client: + print((await client.twitter.activity("btc-up-or-down-5m")).data) + + +asyncio.run(main()) +``` + +## Equivalent request + +```bash +curl 'https://future.news/fds/api/v1/market/twitter/activity/list?limit=10&cursor=&event_slug=btc-up-or-down-5m&from_app=future-web&os=web' +``` + +!!! note "About the response" + Future News does not publish a schema. The library returns the payload as an [`ApiResponse`](../reference.md#futurenews.models.ApiResponse): `.data` holds the `"data"` field (or the whole JSON when there is none) and `.raw` always holds the untouched JSON. Unknown fields are never dropped. Field-level models are added once sample responses are confirmed, so treat the shape as subject to change. + +!!! info + The exact name of the next-page cursor in the response is not confirmed yet. Inspect `page.raw` to find it. + +--- + +**Related:** [Authentication](../authentication.md) · [Errors & Cloudflare](../errors.md) · [All endpoints](../endpoints/index.md) + +!!! tip "Don't have a Future News account?" + [Sign up with our link](https://future.news/41L85FOV). It's free for you and supports this library. + +!!! info "Build something with this data" + Chipa dev team builds trading bots and tools: [Bot development](https://chipatrade.com/services/bot-development) · [ChipaX exchange](https://exchange.chipatrade.com/en/trade/BTC) · [Chipa Editor](https://chipaeditor.com) · [Discord](https://discord.com/invite/qwQZ7rHzGb) diff --git a/docs/endpoints/wallet.md b/docs/endpoints/wallet.md new file mode 100644 index 0000000..9f4af69 --- /dev/null +++ b/docs/endpoints/wallet.md @@ -0,0 +1,78 @@ +--- +title: Future News wallet balances API in Python +description: Use client.wallet.balances to read token balances for a wallet on Polygon through the Future News API from Python. Requires an auth token. +--- + +# Wallet balances: `wallet.balances` + +Reads on-chain token balances (for example outcome tokens) of a wallet. + +| | | +|---|---| +| HTTP | `GET https://future.news/td/api/v1/wallet/balances` | +| Auth | **required**: `FutureNews(auth_token=...)`, see [Authentication](../authentication.md) | +| Returns | `ApiResponse` | + +## Parameters + +| Parameter | Type | Default | Notes | +|---|---|---|---| +| `wallet_address` | `str` | required | `0x...` address. Non-empty. | +| `chain` | `str` | `"polygon"` | | +| `token_addresses` | `Iterable[str]` | `()` | repeated query parameter, one per address | +| `token_ids` | `Iterable[str]` | `()` | repeated query parameter, one per id. Pass big ids as **strings** to avoid precision loss. | + +Without `auth_token` the call raises `AuthRequiredError` *before* any request is sent. + +## Example (sync) + +```python +import os +from futurenews import FutureNews + +with FutureNews(auth_token=os.environ["FUTURENEWS_TOKEN"]) as client: + balances = client.wallet.balances( + "0xYourWalletAddress", + token_addresses=["0xTokenContract"], + token_ids=["1234567890", "9876543210"], + ) + print(balances.data) +``` + +## Example (async) + +```python +import asyncio, os +from futurenews import AsyncFutureNews + + +async def main(): + async with AsyncFutureNews(auth_token=os.environ["FUTURENEWS_TOKEN"]) as client: + print((await client.wallet.balances("0xYourWalletAddress")).data) + + +asyncio.run(main()) +``` + +!!! warning "Keep your token secret" + Read it from an environment variable, never hard-code or commit it. Access tokens expire after roughly 30 minutes; an expired token raises `AuthenticationError`. + +## Equivalent request + +```bash +curl 'https://future.news/td/api/v1/wallet/balances?chain=polygon&wallet_address=0x...&token_addresses=0x...&token_ids=1&token_ids=2' \ + -H 'authorization: Bearer ' +``` + +!!! note "About the response" + Future News does not publish a schema. The library returns the payload as an [`ApiResponse`](../reference.md#futurenews.models.ApiResponse): `.data` holds the `"data"` field (or the whole JSON when there is none) and `.raw` always holds the untouched JSON. Unknown fields are never dropped. Field-level models are added once sample responses are confirmed, so treat the shape as subject to change. + +--- + +**Related:** [Authentication](../authentication.md) · [Errors & Cloudflare](../errors.md) · [All endpoints](../endpoints/index.md) + +!!! tip "Don't have a Future News account?" + [Sign up with our link](https://future.news/41L85FOV). It's free for you and supports this library. + +!!! info "Build something with this data" + Chipa dev team builds trading bots and tools: [Bot development](https://chipatrade.com/services/bot-development) · [ChipaX exchange](https://exchange.chipatrade.com/en/trade/BTC) · [Chipa Editor](https://chipaeditor.com) · [Discord](https://discord.com/invite/qwQZ7rHzGb) diff --git a/docs/errors.md b/docs/errors.md index 8ab15c9..7c84427 100644 --- a/docs/errors.md +++ b/docs/errors.md @@ -10,6 +10,8 @@ All errors inherit `FutureNewsError`. | Exception | When | |---|---| | `BlockedError` | HTTP 403, usually a Cloudflare challenge | +| `AuthRequiredError` | an authenticated endpoint was called without `auth_token` (raised before any request) | +| `AuthenticationError` | HTTP 401: token invalid or expired | | `RateLimitError` | HTTP 429; see `.retry_after` | | `APIError` | any other HTTP error | | `ConnectionFailure` | network failure or timeout | @@ -24,6 +26,4 @@ FutureNews(cookies={"cf_clearance": ""}, proxy="http://user:p !!! warning Treat cookies like passwords. Never commit them. -::: futurenews.errors - -Need a hand? Ask on [Discord](https://discord.com/invite/qwQZ7rHzGb). Don't have an account yet? [Sign up to Future News](https://future.news/41L85FOV). +Full signatures: [API reference](reference.md). diff --git a/docs/quickstart.md b/docs/quickstart.md index 1533b8c..4ed7b0a 100644 --- a/docs/quickstart.md +++ b/docs/quickstart.md @@ -29,6 +29,8 @@ async def main(): asyncio.run(main()) ``` +More endpoints: [rank](endpoints/rank.md), [events](endpoints/events.md), [calendar](endpoints/calendar.md), [Twitter](endpoints/twitter.md), plus [wallet and account](authentication.md) (need a token). + Blocked by Cloudflare? See [Errors & Cloudflare](errors.md). !!! info "Automate it" diff --git a/docs/reference.md b/docs/reference.md new file mode 100644 index 0000000..254661c --- /dev/null +++ b/docs/reference.md @@ -0,0 +1,28 @@ +--- +title: futurenews Python API reference +description: Full API reference for the futurenews library: clients, models and exceptions. +--- + +# API reference + +## Clients + +::: futurenews.client + +## Models + +::: futurenews.models + +## Exceptions + +::: futurenews.errors + +--- + +**Related:** [Authentication](authentication.md) · [Errors & Cloudflare](errors.md) · [All endpoints](endpoints/index.md) + +!!! tip "Don't have a Future News account?" + [Sign up with our link](https://future.news/41L85FOV). It's free for you and supports this library. + +!!! info "Build something with this data" + Chipa dev team builds trading bots and tools: [Bot development](https://chipatrade.com/services/bot-development) · [ChipaX exchange](https://exchange.chipatrade.com/en/trade/BTC) · [Chipa Editor](https://chipaeditor.com) · [Discord](https://discord.com/invite/qwQZ7rHzGb) diff --git a/examples/event_and_rank.py b/examples/event_and_rank.py new file mode 100644 index 0000000..139709c --- /dev/null +++ b/examples/event_and_rank.py @@ -0,0 +1,14 @@ +"""Newest markets, then details of the first one. + +Made by Chipa dev team - https://chipatrade.com/community +Sign up to Future News: https://future.news/41L85FOV +""" + +from futurenews import FutureNews + +with FutureNews() as client: + newest = client.rank.list(rank_type="new", order_by="create_timestamp", limit=5, exclude_series=True) + print(f"{len(newest.items)} new markets") + # Slugs live inside each entry; inspect one to find the field you need: + if newest.items: + print(newest.items[0].model_dump()) diff --git a/mkdocs.yml b/mkdocs.yml index b82cb48..6ec4637 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -19,8 +19,17 @@ nav: - Installation: installation.md - Quickstart: quickstart.md - Endpoints: - - Trending markets: endpoints/trending.md + - Overview: endpoints/index.md + - Trending: endpoints/trending.md + - Rank: endpoints/rank.md + - Events: endpoints/events.md + - Calendar: endpoints/calendar.md + - Twitter activity: endpoints/twitter.md + - Wallet balances: endpoints/wallet.md + - Account: endpoints/account.md + - Authentication: authentication.md - Errors & Cloudflare: errors.md + - API reference: reference.md - FAQ: faq.md - From Chipa dev team: chipa.md - Contributing: contributing.md From e6eb2596d18474f6dc74410b37db0ca2b555aaf2 Mon Sep 17 00:00:00 2001 From: Vigo Walker Date: Sun, 29 Nov 2026 15:47:30 +0100 Subject: [PATCH 3/3] fix: harden slug/params/date handling, drop JSON content-type on bodyless calls, fix docs notes Co-Authored-By: Claude Sonnet 5.5 --- docs/endpoints/account.md | 3 +- docs/endpoints/calendar.md | 3 +- docs/endpoints/events.md | 5 +-- docs/endpoints/twitter.md | 3 +- docs/endpoints/wallet.md | 5 +-- docs/reference.md | 4 ++ src/futurenews/_base.py | 7 +--- src/futurenews/models.py | 7 +++- src/futurenews/resources/_calls.py | 47 ++++++++++++---------- src/futurenews/resources/asynchronous.py | 4 +- src/futurenews/resources/sync.py | 4 +- tests/test_endpoints.py | 51 ++++++++++++++++++++++++ 12 files changed, 100 insertions(+), 43 deletions(-) diff --git a/docs/endpoints/account.md b/docs/endpoints/account.md index 92b71fd..d28149a 100644 --- a/docs/endpoints/account.md +++ b/docs/endpoints/account.md @@ -52,8 +52,7 @@ curl -X POST 'https://future.news/account/user_info?from_app=future-web&os=web' ``` !!! note "About the response" - Future News does not publish a schema. The library returns the payload as an [`ApiResponse`](../reference.md#futurenews.models.ApiResponse): `.data` holds the `"data"` field (or the whole JSON when there is none) and `.raw` always holds the untouched JSON. Unknown fields are never dropped. Field-level models are added once sample responses are confirmed, so treat the shape as subject to change. - + Future News does not publish a schema. The library returns the payload as an [`ApiResponse`](../reference.md#futurenews.models.ApiResponse): `.data` holds the `"data"` field (or the whole JSON when there is none) and `.raw` always holds the untouched JSON. Unknown fields are never dropped. Field-level models are added once sample responses are confirmed, so treat the shape as subject to change. --- **Related:** [Authentication](../authentication.md) · [Errors & Cloudflare](../errors.md) · [All endpoints](../endpoints/index.md) diff --git a/docs/endpoints/calendar.md b/docs/endpoints/calendar.md index ad7d9ae..5f0508b 100644 --- a/docs/endpoints/calendar.md +++ b/docs/endpoints/calendar.md @@ -57,8 +57,7 @@ curl 'https://future.news/api/v1/finance_calendar/polymarket?category=earnings&f ``` !!! note "About the response" - Future News does not publish a schema. The library returns the payload as an [`ApiResponse`](../reference.md#futurenews.models.ApiResponse): `.data` holds the `"data"` field (or the whole JSON when there is none) and `.raw` always holds the untouched JSON. Unknown fields are never dropped. Field-level models are added once sample responses are confirmed, so treat the shape as subject to change. - + Future News does not publish a schema. The library returns the payload as an [`ApiResponse`](../reference.md#futurenews.models.ApiResponse): `.data` holds the `"data"` field (or the whole JSON when there is none) and `.raw` always holds the untouched JSON. Unknown fields are never dropped. Field-level models are added once sample responses are confirmed, so treat the shape as subject to change. --- **Related:** [Authentication](../authentication.md) · [Errors & Cloudflare](../errors.md) · [All endpoints](../endpoints/index.md) diff --git a/docs/endpoints/events.md b/docs/endpoints/events.md index c49f8ba..19a9bde 100644 --- a/docs/endpoints/events.md +++ b/docs/endpoints/events.md @@ -17,7 +17,7 @@ Fetches one event (a market page on Future News) by its **slug**, the last part | Parameter | Type | Notes | |---|---|---| -| `slug` | `str` | e.g. `"dota2-liquid-ty-2026-11-29"`. Must be non-empty. It is URL-encoded, so it can never alter the request path. | +| `slug` | `str` | e.g. `"dota2-liquid-ty-2026-11-29"`. Must be non-empty. It is URL-encoded, and slugs made only of dots (`.`, `..`) are rejected, so a slug cannot alter the request path. | ## Example (sync) @@ -54,8 +54,7 @@ curl 'https://future.news/api/v1/event/polymarket/dota2-liquid-ty-2026-11-29?fro ``` !!! note "About the response" - Future News does not publish a schema. The library returns the payload as an [`ApiResponse`](../reference.md#futurenews.models.ApiResponse): `.data` holds the `"data"` field (or the whole JSON when there is none) and `.raw` always holds the untouched JSON. Unknown fields are never dropped. Field-level models are added once sample responses are confirmed, so treat the shape as subject to change. - + Future News does not publish a schema. The library returns the payload as an [`ApiResponse`](../reference.md#futurenews.models.ApiResponse): `.data` holds the `"data"` field (or the whole JSON when there is none) and `.raw` always holds the untouched JSON. Unknown fields are never dropped. Field-level models are added once sample responses are confirmed, so treat the shape as subject to change. --- **Related:** [Authentication](../authentication.md) · [Errors & Cloudflare](../errors.md) · [All endpoints](../endpoints/index.md) diff --git a/docs/endpoints/twitter.md b/docs/endpoints/twitter.md index fbcd1cd..bb89a6d 100644 --- a/docs/endpoints/twitter.md +++ b/docs/endpoints/twitter.md @@ -54,8 +54,7 @@ curl 'https://future.news/fds/api/v1/market/twitter/activity/list?limit=10&curso ``` !!! note "About the response" - Future News does not publish a schema. The library returns the payload as an [`ApiResponse`](../reference.md#futurenews.models.ApiResponse): `.data` holds the `"data"` field (or the whole JSON when there is none) and `.raw` always holds the untouched JSON. Unknown fields are never dropped. Field-level models are added once sample responses are confirmed, so treat the shape as subject to change. - + Future News does not publish a schema. The library returns the payload as an [`ApiResponse`](../reference.md#futurenews.models.ApiResponse): `.data` holds the `"data"` field (or the whole JSON when there is none) and `.raw` always holds the untouched JSON. Unknown fields are never dropped. Field-level models are added once sample responses are confirmed, so treat the shape as subject to change. !!! info The exact name of the next-page cursor in the response is not confirmed yet. Inspect `page.raw` to find it. diff --git a/docs/endpoints/wallet.md b/docs/endpoints/wallet.md index 9f4af69..a413876 100644 --- a/docs/endpoints/wallet.md +++ b/docs/endpoints/wallet.md @@ -20,7 +20,7 @@ Reads on-chain token balances (for example outcome tokens) of a wallet. | `wallet_address` | `str` | required | `0x...` address. Non-empty. | | `chain` | `str` | `"polygon"` | | | `token_addresses` | `Iterable[str]` | `()` | repeated query parameter, one per address | -| `token_ids` | `Iterable[str]` | `()` | repeated query parameter, one per id. Pass big ids as **strings** to avoid precision loss. | +| `token_ids` | `Iterable[str]` | `()` | repeated query parameter, one per id. Pass them as strings (or ints). Don't round-trip them through floats or JSON numbers first, which loses digits. | Without `auth_token` the call raises `AuthRequiredError` *before* any request is sent. @@ -65,8 +65,7 @@ curl 'https://future.news/td/api/v1/wallet/balances?chain=polygon&wallet_address ``` !!! note "About the response" - Future News does not publish a schema. The library returns the payload as an [`ApiResponse`](../reference.md#futurenews.models.ApiResponse): `.data` holds the `"data"` field (or the whole JSON when there is none) and `.raw` always holds the untouched JSON. Unknown fields are never dropped. Field-level models are added once sample responses are confirmed, so treat the shape as subject to change. - + Future News does not publish a schema. The library returns the payload as an [`ApiResponse`](../reference.md#futurenews.models.ApiResponse): `.data` holds the `"data"` field (or the whole JSON when there is none) and `.raw` always holds the untouched JSON. Unknown fields are never dropped. Field-level models are added once sample responses are confirmed, so treat the shape as subject to change. --- **Related:** [Authentication](../authentication.md) · [Errors & Cloudflare](../errors.md) · [All endpoints](../endpoints/index.md) diff --git a/docs/reference.md b/docs/reference.md index 254661c..1201ef0 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -26,3 +26,7 @@ description: Full API reference for the futurenews library: clients, models and !!! info "Build something with this data" Chipa dev team builds trading bots and tools: [Bot development](https://chipatrade.com/services/bot-development) · [ChipaX exchange](https://exchange.chipatrade.com/en/trade/BTC) · [Chipa Editor](https://chipaeditor.com) · [Discord](https://discord.com/invite/qwQZ7rHzGb) + +## Resources + +::: futurenews.resources.sync diff --git a/src/futurenews/_base.py b/src/futurenews/_base.py index 03926ec..41d3333 100644 --- a/src/futurenews/_base.py +++ b/src/futurenews/_base.py @@ -7,7 +7,7 @@ from __future__ import annotations import uuid -from dataclasses import dataclass, field +from dataclasses import dataclass from datetime import datetime, timezone from email.utils import parsedate_to_datetime from typing import Any @@ -17,14 +17,12 @@ from .errors import APIError, AuthenticationError, BlockedError, RateLimitError BASE_URL = "https://future.news" -TRENDING_PATH = "/events/api/trending/list" APP_VERSION = "20261127-1776-04df410" #: Browser-like headers the Future News web app sends (no secrets in here). DEFAULT_HEADERS: dict[str, str] = { "accept": "application/json, text/plain, */*", "accept-language": "en-US,en;q=0.9", - "content-type": "application/json", "origin": BASE_URL, "referer": f"{BASE_URL}/trending", "user-agent": ( @@ -108,7 +106,6 @@ class Call: params: tuple[tuple[str, str], ...] = () json: Any = None auth: bool = False # True -> needs ``Authorization: Bearer `` - meta: dict[str, Any] = field(default_factory=dict) def request_kwargs(call: Call, device_id: str, token: str | None) -> dict[str, Any]: @@ -129,5 +126,5 @@ def request_kwargs(call: Call, device_id: str, token: str | None) -> dict[str, A "headers": headers, } if call.json is not None: - kwargs["json"] = call.json + kwargs["json"] = call.json # httpx adds content-type: application/json itself return kwargs diff --git a/src/futurenews/models.py b/src/futurenews/models.py index 9306e20..2239806 100644 --- a/src/futurenews/models.py +++ b/src/futurenews/models.py @@ -6,7 +6,7 @@ from __future__ import annotations -from datetime import date +from datetime import date, datetime from typing import Any, Optional from pydantic import BaseModel, ConfigDict, Field, StrictInt @@ -115,7 +115,8 @@ class ApiResponse(BaseModel): ``data`` is the ``"data"`` field of the JSON object (or the whole payload when there is no such field); ``raw`` is always the untouched payload. - Other top-level fields (``code``, ``msg``...) are kept as attributes. + Other top-level fields (``code``, ``msg``...) are kept in ``model_extra`` (and as + attributes unless the name clashes with a pydantic method; use ``raw`` then). """ model_config = ConfigDict(extra="allow") @@ -134,6 +135,8 @@ def from_payload(cls, payload: Any) -> ApiResponse: def iso_date(value: date | str, name: str) -> str: """Return ``YYYY-MM-DD`` for a date or ISO string; ValueError otherwise.""" + if isinstance(value, datetime): # datetime is a date subclass: keep only the day + return value.date().isoformat() if isinstance(value, date): return value.isoformat() try: diff --git a/src/futurenews/resources/_calls.py b/src/futurenews/resources/_calls.py index eb506d8..b952ec3 100644 --- a/src/futurenews/resources/_calls.py +++ b/src/futurenews/resources/_calls.py @@ -7,7 +7,7 @@ from __future__ import annotations -from collections.abc import Iterable, Sequence +from collections.abc import Iterable from datetime import date from typing import Any, TypeVar from urllib.parse import quote @@ -38,10 +38,23 @@ def rank(request: RankRequest | None, overrides: dict[str, Any]) -> Call: return Call("POST", "/events/api/rank", json=body) +def _text(value: Any, name: str) -> str: + """Return a stripped non-empty string or raise ValueError (never AttributeError).""" + if not isinstance(value, str) or not value.strip(): + raise ValueError(f"{name} must be a non-empty string") + return value.strip() + + +def _many(value: Iterable[str] | str) -> list[str]: + """A bare string is ONE item, not an iterable of characters.""" + return [value] if isinstance(value, str) else [str(v) for v in value] + + def _slug(slug: str) -> str: - if not isinstance(slug, str) or not slug.strip(): - raise ValueError("slug must be a non-empty string") - return quote(slug.strip(), safe="") # a slug can never escape its path segment + slug = _text(slug, "slug") + if not slug.strip("."): # ".", ".." etc. would be normalised away by the HTTP layer + raise ValueError("slug must not consist only of dots") + return quote(slug, safe="") # "/", "?", "#" are percent-encoded: no path/query injection def event(slug: str) -> Call: @@ -51,10 +64,8 @@ def event(slug: str) -> Call: def calendar(category: str, from_date: date | str, to_date: date | str) -> Call: """``GET /api/v1/finance_calendar/polymarket``.""" - if not category or not category.strip(): - raise ValueError("category must be a non-empty string") params = ( - ("category", category.strip()), + ("category", _text(category, "category")), ("from", iso_date(from_date, "from_date")), ("to", iso_date(to_date, "to_date")), ) @@ -65,30 +76,26 @@ def twitter_activity(event_slug: str, limit: int, cursor: str) -> Call: """``GET /fds/api/v1/market/twitter/activity/list``.""" if isinstance(limit, bool) or not isinstance(limit, int) or not 1 <= limit <= 100: raise ValueError("limit must be an integer between 1 and 100") - if not event_slug or not event_slug.strip(): - raise ValueError("event_slug must be a non-empty string") - params = (("limit", str(limit)), ("cursor", cursor), ("event_slug", event_slug.strip())) + params = (("limit", str(limit)), ("cursor", str(cursor)), ("event_slug", _text(event_slug, "event_slug"))) return Call("GET", "/fds/api/v1/market/twitter/activity/list", params=params) def wallet_balances( wallet_address: str, chain: str, - token_addresses: Iterable[str], - token_ids: Iterable[str], + token_addresses: Iterable[str] | str, + token_ids: Iterable[str] | str, ) -> Call: """``GET /td/api/v1/wallet/balances`` (needs auth). Repeated params are sent as-is.""" - if not wallet_address or not wallet_address.strip(): - raise ValueError("wallet_address must be a non-empty string") - params: list[tuple[str, str]] = [("chain", chain), ("wallet_address", wallet_address.strip())] - params += [("token_addresses", str(a)) for a in token_addresses] - params += [("token_ids", str(i)) for i in token_ids] + params: list[tuple[str, str]] = [ + ("chain", _text(chain, "chain")), + ("wallet_address", _text(wallet_address, "wallet_address")), + ] + params += [("token_addresses", a) for a in _many(token_addresses)] + params += [("token_ids", i) for i in _many(token_ids)] return Call("GET", "/td/api/v1/wallet/balances", params=tuple(params), auth=True) def user_info() -> Call: """``POST /account/user_info`` (needs auth, empty body).""" return Call("POST", "/account/user_info", auth=True) - - -Strs = Sequence[str] diff --git a/src/futurenews/resources/asynchronous.py b/src/futurenews/resources/asynchronous.py index d0333f7..38bf951 100644 --- a/src/futurenews/resources/asynchronous.py +++ b/src/futurenews/resources/asynchronous.py @@ -70,8 +70,8 @@ async def balances( self, wallet_address: str, chain: str = "polygon", - token_addresses: Iterable[str] = (), - token_ids: Iterable[str] = (), + token_addresses: Iterable[str] | str = (), + token_ids: Iterable[str] | str = (), ) -> ApiResponse: """Fetch token balances for a wallet (``GET /td/api/v1/wallet/balances``).""" call = _calls.wallet_balances(wallet_address, chain, token_addresses, token_ids) diff --git a/src/futurenews/resources/sync.py b/src/futurenews/resources/sync.py index 1a7cbcd..de9286e 100644 --- a/src/futurenews/resources/sync.py +++ b/src/futurenews/resources/sync.py @@ -70,8 +70,8 @@ def balances( self, wallet_address: str, chain: str = "polygon", - token_addresses: Iterable[str] = (), - token_ids: Iterable[str] = (), + token_addresses: Iterable[str] | str = (), + token_ids: Iterable[str] | str = (), ) -> ApiResponse: """Fetch token balances for a wallet (``GET /td/api/v1/wallet/balances``).""" call = _calls.wallet_balances(wallet_address, chain, token_addresses, token_ids) diff --git a/tests/test_endpoints.py b/tests/test_endpoints.py index a426044..0dce794 100644 --- a/tests/test_endpoints.py +++ b/tests/test_endpoints.py @@ -180,3 +180,54 @@ async def test_async_all_resources(): async with AsyncFutureNews() as c: with pytest.raises(AuthRequiredError): await c.account.user_info() + + +@pytest.mark.parametrize("slug", [".", "..", "...", " .. "]) +def test_dot_only_slug_rejected(slug): + with pytest.raises(ValueError), FutureNews() as c: + c.events.get(slug) + + +@respx.mock +def test_bare_string_token_params_are_one_item(): + route = respx.get(f"{B}/td/api/v1/wallet/balances").mock(return_value=httpx.Response(200, json=OK)) + with FutureNews(auth_token="t") as c: + c.wallet.balances(FAKE_WALLET, token_addresses="0xabc", token_ids="123") + p = sent(route).url.params + assert p.get_list("token_addresses") == ["0xabc"] and p.get_list("token_ids") == ["123"] + + +@respx.mock +def test_calendar_datetime_sends_date_only(): + from datetime import datetime + + route = respx.get(f"{B}/api/v1/finance_calendar/polymarket").mock(return_value=httpx.Response(200, json=OK)) + with FutureNews() as c: + c.calendar.get("earnings", datetime(2026, 1, 1, 5, 0), datetime(2026, 2, 1, 23, 59)) + q = dict(sent(route).url.params) + assert q["from"] == "2026-01-01" and q["to"] == "2026-02-01" + + +@respx.mock +def test_content_type_only_when_json_body_sent(): + get = respx.get(f"{B}/api/v1/event/polymarket/x").mock(return_value=httpx.Response(200, json=OK)) + post = respx.post(f"{B}/account/user_info").mock(return_value=httpx.Response(200, json=OK)) + rank = respx.post(f"{B}/events/api/rank").mock(return_value=httpx.Response(200, json=OK)) + with FutureNews(auth_token="t") as c: + c.events.get("x") + c.account.user_info() + c.rank.list() + assert "content-type" not in sent(get).headers and "content-type" not in sent(post).headers + assert sent(rank).headers["content-type"] == "application/json" + + +@pytest.mark.parametrize("bad", [None, 5]) +def test_non_string_inputs_raise_value_error(bad): + with FutureNews() as c: + for fn in ( + lambda: c.twitter.activity(bad), + lambda: c.calendar.get(bad, "2026-01-01", "2026-02-01"), + lambda: c.events.get(bad), + ): + with pytest.raises(ValueError): + fn()