Skip to content

title: futurenews Python API reference description: Full API reference for the futurenews library: clients, models and exceptions.


API reference

Clients

Public clients: :class:FutureNews (sync) and :class:AsyncFutureNews.

Made by Chipa dev team. Sign up to Future News: https://future.news/41L85FOV

AsyncFutureNews

Asynchronous Future News client (same arguments and resources as :class:FutureNews).

Source code in src/futurenews/client.py
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
class AsyncFutureNews:
    """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,
        timeout: float = 30.0,
        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
        )
        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."""
        await self._http.aclose()

    async def __aenter__(self) -> AsyncFutureNews:
        return self

    async def __aexit__(
        self,
        exc_type: type[BaseException] | None,
        exc: BaseException | None,
        tb: TracebackType | None,
    ) -> None:
        await self.aclose()

aclose() async

Close the underlying connection pool.

Source code in src/futurenews/client.py
135
136
137
async def aclose(self) -> None:
    """Close the underlying connection pool."""
    await self._http.aclose()

FutureNews

Synchronous Future News client.

Resources: trending, rank, events, calendar, twitter (public) and wallet, account (need auth_token).

Parameters:

Name Type Description Default
auth_token str | None

Bearer access token for authenticated endpoints. Treat it like a password. It is never logged and hidden from repr.

None
cookies dict[str, str] | None

Optional browser cookies (e.g. {"cf_clearance": ...}) if Cloudflare challenges your IP. The library ships none.

None
headers dict[str, str] | None

Extra/override headers.

None
proxy str | None

Proxy URL, e.g. http://user:pass@host:port.

None
timeout float

Seconds. Default 30.

30.0
device_id str | None

Reuse a device id; random uuid4 by default.

None
Source code in src/futurenews/client.py
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
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.
        proxy: Proxy URL, e.g. ``http://user:pass@host:port``.
        timeout: Seconds. Default 30.
        device_id: Reuse a device id; random uuid4 by default.
    """

    def __init__(
        self,
        *,
        auth_token: str | None = None,
        cookies: dict[str, str] | None = None,
        headers: dict[str, str] | None = None,
        proxy: str | None = None,
        timeout: float = 30.0,
        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
        )
        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."""
        self._http.close()

    def __enter__(self) -> FutureNews:
        return self

    def __exit__(
        self,
        exc_type: type[BaseException] | None,
        exc: BaseException | None,
        tb: TracebackType | None,
    ) -> None:
        self.close()

close()

Close the underlying connection pool.

Source code in src/futurenews/client.py
81
82
83
def close(self) -> None:
    """Close the underlying connection pool."""
    self._http.close()

Models

Pydantic models for the trending/list endpoint.

Response models are deliberately permissive (extra="allow"): Future News can add fields at any time and we never want that to break your code.

ApiResponse

Bases: 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 in model_extra (and as attributes unless the name clashes with a pydantic method; use raw then).

Source code in src/futurenews/models.py
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
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 in ``model_extra`` (and as
    attributes unless the name clashes with a pydantic method; use ``raw`` then).
    """

    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)

from_payload(payload) classmethod

Wrap any JSON payload.

Source code in src/futurenews/models.py
127
128
129
130
131
132
133
@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)

RankRequest

Bases: BaseModel

Body for POST /events/api/rank (the "new", "trending"... tabs).

Source code in src/futurenews/models.py
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
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

to_body()

JSON body; optional fields are omitted when unset, like the web app.

Source code in src/futurenews/models.py
101
102
103
104
105
106
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

TrendingItem

Bases: BaseModel

One trending entry. Unknown fields are preserved.

Source code in src/futurenews/models.py
37
38
39
40
class TrendingItem(BaseModel):
    """One trending entry. Unknown fields are preserved."""

    model_config = ConfigDict(extra="allow")

TrendingRequest

Bases: BaseModel

Body sent to POST /events/api/trending/list.

Unknown option names are rejected so typos (limt=5) fail loudly.

Source code in src/futurenews/models.py
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class TrendingRequest(BaseModel):
    """Body sent to ``POST /events/api/trending/list``.

    Unknown option names are rejected so typos (``limt=5``) fail loudly.
    """

    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: str = "active"
    order_by: str = "volume24h"
    limit: StrictInt = Field(default=100, ge=1, le=100)

    def to_body(self) -> dict[str, Any]:
        """Return the JSON body exactly as the Future News web app sends it."""
        return self.model_dump()

to_body()

Return the JSON body exactly as the Future News web app sends it.

Source code in src/futurenews/models.py
32
33
34
def to_body(self) -> dict[str, Any]:
    """Return the JSON body exactly as the Future News web app sends it."""
    return self.model_dump()

TrendingResponse

Bases: BaseModel

Parsed trending/list response.

Source code in src/futurenews/models.py
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
class TrendingResponse(BaseModel):
    """Parsed ``trending/list`` response."""

    model_config = ConfigDict(extra="allow")

    items: list[TrendingItem] = Field(default_factory=list)

    @classmethod
    def from_payload(cls, payload: Any) -> TrendingResponse:
        """Build from raw JSON, tolerating null/missing/odd shapes.

        Entries are looked up under the well-known keys ``data``, ``events``,
        ``items`` and ``list`` (recursing into nested envelopes such as
        ``{"data": {"list": [...]}}``). Any other list is NOT guessed at, so
        an error body can never be mistaken for trending items. Remaining
        top-level fields (``code``, ``msg``, pagination...) are preserved.
        """
        raw, extras = _find_items(payload)
        items = [TrendingItem.model_validate(i) for i in (raw or []) if isinstance(i, dict)]
        return cls(items=items, **extras)

from_payload(payload) classmethod

Build from raw JSON, tolerating null/missing/odd shapes.

Entries are looked up under the well-known keys data, events, items and list (recursing into nested envelopes such as {"data": {"list": [...]}}). Any other list is NOT guessed at, so an error body can never be mistaken for trending items. Remaining top-level fields (code, msg, pagination...) are preserved.

Source code in src/futurenews/models.py
50
51
52
53
54
55
56
57
58
59
60
61
62
@classmethod
def from_payload(cls, payload: Any) -> TrendingResponse:
    """Build from raw JSON, tolerating null/missing/odd shapes.

    Entries are looked up under the well-known keys ``data``, ``events``,
    ``items`` and ``list`` (recursing into nested envelopes such as
    ``{"data": {"list": [...]}}``). Any other list is NOT guessed at, so
    an error body can never be mistaken for trending items. Remaining
    top-level fields (``code``, ``msg``, pagination...) are preserved.
    """
    raw, extras = _find_items(payload)
    items = [TrendingItem.model_validate(i) for i in (raw or []) if isinstance(i, dict)]
    return cls(items=items, **extras)

iso_date(value, name)

Return YYYY-MM-DD for a date or ISO string; ValueError otherwise.

Source code in src/futurenews/models.py
136
137
138
139
140
141
142
143
144
145
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:
        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

Exceptions

Exception hierarchy for futurenews.

Catch :class:FutureNewsError to handle everything this library raises.

APIError

Bases: FutureNewsError

The API answered with an HTTP error status.

Source code in src/futurenews/errors.py
13
14
15
16
17
18
19
class APIError(FutureNewsError):
    """The API answered with an HTTP error status."""

    def __init__(self, status_code: int, message: str = "") -> None:
        super().__init__(f"HTTP {status_code}: {message}" if message else f"HTTP {status_code}")
        self.status_code = status_code
        self.message = message

AuthRequiredError

Bases: 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.

Source code in src/futurenews/errors.py
42
43
44
45
46
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.
    """

AuthenticationError

Bases: 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.

Source code in src/futurenews/errors.py
49
50
51
52
53
54
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.
    """

BlockedError

Bases: APIError

Request was blocked (HTTP 403), typically a Cloudflare challenge.

Pass fresh browser cookies (e.g. cf_clearance) or a proxy to the client. See the docs page on errors.

Source code in src/futurenews/errors.py
22
23
24
25
26
27
class BlockedError(APIError):
    """Request was blocked (HTTP 403), typically a Cloudflare challenge.

    Pass fresh browser ``cookies`` (e.g. ``cf_clearance``) or a ``proxy``
    to the client. See the docs page on errors.
    """

ConnectionFailure

Bases: FutureNewsError

Network-level failure (DNS, timeout, connection refused).

Source code in src/futurenews/errors.py
38
39
class ConnectionFailure(FutureNewsError):
    """Network-level failure (DNS, timeout, connection refused)."""

FutureNewsError

Bases: Exception

Base class for all errors raised by futurenews.

Source code in src/futurenews/errors.py
 9
10
class FutureNewsError(Exception):
    """Base class for all errors raised by futurenews."""

RateLimitError

Bases: APIError

Too many requests (HTTP 429). retry_after is in seconds if sent.

Source code in src/futurenews/errors.py
30
31
32
33
34
35
class RateLimitError(APIError):
    """Too many requests (HTTP 429). ``retry_after`` is in seconds if sent."""

    def __init__(self, status_code: int, message: str = "", retry_after: float | None = None) -> None:
        super().__init__(status_code, message)
        self.retry_after = retry_after

Related: Authentication · Errors & Cloudflare · All endpoints

Don't have a Future News account?

Sign up with our link. It's free for you and supports this library.

Build something with this data

Chipa dev team builds trading bots and tools: Bot development · ChipaX exchange · Chipa Editor · Discord

Resources

Synchronous resource objects (client.trending, client.rank...).

Account

Bases: _Resource

The signed-in account. Requires auth_token.

Source code in src/futurenews/resources/sync.py
81
82
83
84
85
86
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()))

user_info()

Fetch the current user's profile (POST /account/user_info).

Source code in src/futurenews/resources/sync.py
84
85
86
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()))

Calendar

Bases: _Resource

Finance calendar.

Source code in src/futurenews/resources/sync.py
50
51
52
53
54
55
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)))

get(category, from_date, to_date)

Fetch calendar entries, e.g. category="earnings" between two dates.

Source code in src/futurenews/resources/sync.py
53
54
55
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)))

Events

Bases: _Resource

Single event details.

Source code in src/futurenews/resources/sync.py
42
43
44
45
46
47
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)))

get(slug)

Fetch one Polymarket-backed event by slug (GET /api/v1/event/polymarket/{slug}).

Source code in src/futurenews/resources/sync.py
45
46
47
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)))

Rank

Bases: _Resource

Ranked market lists (new, trending...): POST /events/api/rank.

Source code in src/futurenews/resources/sync.py
34
35
36
37
38
39
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)))

list(request=None, **overrides)

Fetch a ranked list. overrides are RankRequest fields (e.g. rank_type="new").

Source code in src/futurenews/resources/sync.py
37
38
39
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)))

Trending

Bases: _Resource

Trending markets: POST /events/api/trending/list.

Source code in src/futurenews/resources/sync.py
21
22
23
24
25
26
27
28
29
30
31
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)

list(request=None, **overrides)

Fetch trending markets. overrides are TrendingRequest fields (e.g. limit=10).

Raises:

Type Description
ValueError

invalid options (checked before any request is sent).

Source code in src/futurenews/resources/sync.py
24
25
26
27
28
29
30
31
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)

Twitter

Bases: _Resource

Twitter/X activity attached to a market.

Source code in src/futurenews/resources/sync.py
58
59
60
61
62
63
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)))

activity(event_slug, limit=10, cursor='')

Fetch a page of tweets for an event. Pass the previous cursor to page.

Source code in src/futurenews/resources/sync.py
61
62
63
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)))

Wallet

Bases: _Resource

On-chain wallet data. Requires auth_token.

Source code in src/futurenews/resources/sync.py
66
67
68
69
70
71
72
73
74
75
76
77
78
class Wallet(_Resource):
    """On-chain wallet data. Requires ``auth_token``."""

    def balances(
        self,
        wallet_address: str,
        chain: str = "polygon",
        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)
        return ApiResponse.from_payload(self._client._send(call))

balances(wallet_address, chain='polygon', token_addresses=(), token_ids=())

Fetch token balances for a wallet (GET /td/api/v1/wallet/balances).

Source code in src/futurenews/resources/sync.py
69
70
71
72
73
74
75
76
77
78
def balances(
    self,
    wallet_address: str,
    chain: str = "polygon",
    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)
    return ApiResponse.from_payload(self._client._send(call))