From 7b66cccd5bf79dd6b281f4a119aeaa6df8def909 Mon Sep 17 00:00:00 2001 From: Vigo Walker Date: Sun, 29 Nov 2026 15:18:58 +0100 Subject: [PATCH 01/11] docs: add design and implementation plan Co-Authored-By: Claude Sonnet 5.5 --- .../plans/2026-11-29-futurenews-api.md | 85 +++++++++++++++++++ 1 file changed, 85 insertions(+) create mode 100644 docs/superpowers/plans/2026-11-29-futurenews-api.md diff --git a/docs/superpowers/plans/2026-11-29-futurenews-api.md b/docs/superpowers/plans/2026-11-29-futurenews-api.md new file mode 100644 index 0000000..b56b043 --- /dev/null +++ b/docs/superpowers/plans/2026-11-29-futurenews-api.md @@ -0,0 +1,85 @@ +# FutureNewsAPI Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Ship `futurenews`, a typed sync+async Python wrapper for Future News `trending/list`, with SEO-focused GitHub Pages docs promoting Chipa dev team. + +**Architecture:** A shared `_base` builds request params/headers and parses responses; `FutureNews` (httpx.Client) and `AsyncFutureNews` (httpx.AsyncClient) expose a `trending` resource. Pydantic v2 models are permissive (`extra="allow"`). HTTP errors map to an exception hierarchy. + +**Tech Stack:** Python >=3.9, httpx, pydantic v2, hatchling, pytest, respx, pytest-asyncio, ruff, mypy, MkDocs Material. + +**Spec:** docs/superpowers/specs/2026-11-29-futurenews-api-design.md + +## Global Constraints + +- Package import name `futurenews`; PyPI name `future-news-api`; MIT; copyright "Chipa dev team". +- Affiliate link `https://future.news/41L85FOV` in README, docs footer, package metadata and `futurenews.AFFILIATE_URL`. +- Chipa links: https://chipatrade.com/services/bot-development, https://exchange.chipatrade.com/en/trade/BTC, https://chipaeditor.com, Discord https://discord.com/invite/qwQZ7rHzGb, community https://chipatrade.com/community (single source: `futurenews/_links.py`, mirrored in docs). +- NEVER commit cookies, tokens, device ids or the pasted curl's secrets; tests use fake values. Library ships no cookies/Cloudflare bypass; users may pass `cookies`, `headers`, `proxy`. +- Endpoint: `POST https://future.news/events/api/trending/list` with query params (`device_id, fp_did=unknown, client_id, from_app=future-web, app_ver, tz_name, tz_offset, app_lang=en-US, os=web, worker=0`) and JSON body `{"exclude_series":false,"rank_type":"trending","categories":[],"subcategories":[],"status":["active"],"market_status":"active","order_by":"volume24h","limit":100}`; headers origin/referer `https://future.news[/trending]`. +- Heavy docstrings/comments; ruff + mypy --strict clean. + +## Review Focus + +- Empty/`null` result list -> returns empty list, no crash. +- HTTP 403 (Cloudflare challenge, HTML body) -> `BlockedError`, not JSON decode error. +- HTTP 429 -> `RateLimitError` with `retry_after` from header if present. +- Unknown extra fields in response -> preserved, not rejected. +- `limit` outside 1..100 -> `ValueError` before any request. + +--- + +### Task 1: Project scaffold + +**Files:** Create `pyproject.toml`, `LICENSE`, `.gitignore`, `src/futurenews/__init__.py`, `src/futurenews/_links.py`, `src/futurenews/py.typed`, `tests/test_links.py`; Modify `README.md`. + +**Interfaces:** Produces `futurenews.__version__: str`, `futurenews.AFFILIATE_URL: str`, `futurenews._links.LINKS: dict[str, str]` (keys `bot_development, exchange, editor, discord, community, affiliate`). + +- [ ] **Step 1:** Write `tests/test_links.py::test_affiliate_and_links` asserting `AFFILIATE_URL == "https://future.news/41L85FOV"` and all 6 LINKS keys are https URLs. +- [ ] **Step 2:** Run `pytest tests/test_links.py -v`; expect FAIL (ImportError). +- [ ] **Step 3:** Create files; hatchling src layout, deps httpx/pydantic, dev extras, ruff/mypy/pytest config (asyncio_mode=auto); README with credit, affiliate link, badges, Chipa promo section. +- [ ] **Step 4:** `pip install -e ".[dev]" && pytest tests/test_links.py -v`; expect PASS. +- [ ] **Step 5:** Commit `chore: scaffold project`. + +### Task 2: Errors and models + +**Files:** Create `src/futurenews/errors.py`, `src/futurenews/models.py`, `tests/test_models.py`, `tests/test_errors.py`. + +**Interfaces:** Produces `FutureNewsError`; subclasses `APIError(status_code, message)`, `BlockedError(APIError)`, `RateLimitError(APIError, retry_after: float|None)`, `ConnectionFailure(FutureNewsError)`; `TrendingRequest(limit:int=100, order_by:str="volume24h", rank_type:str="trending", status:list[str]=["active"], market_status:str="active", categories:list[str]=[], subcategories:list[str]=[], exclude_series:bool=False)` with `to_body() -> dict` and limit validator (1..100, ValueError); `TrendingResponse` with `items: list[TrendingItem]` (permissive, `extra="allow"`, accepts null/missing). + +- [ ] **Step 1:** Tests: `test_request_body_matches_curl` (default `to_body()` equals the body in Global Constraints), `test_limit_out_of_range_raises`, `test_response_keeps_extra_fields`, `test_response_null_items_is_empty`, `test_errors_hierarchy`. +- [ ] **Step 2:** Run; expect FAIL. +- [ ] **Step 3:** Implement. Response model field names come from a live/real sample (Task 4 step 1) — until then, `items` is parsed from the top-level list or the first list-valued key. +- [ ] **Step 4:** Run; expect PASS. **Step 5:** Commit. + +### Task 3: Sync + async clients + +**Files:** Create `src/futurenews/_base.py`, `client.py`, `resources/__init__.py`, `resources/trending.py`, `tests/test_client.py`; Modify `__init__.py` exports. + +**Interfaces:** Consumes Task 2. Produces `FutureNews(*, cookies: dict|None, headers: dict|None, proxy: str|None, timeout: float=30.0, device_id: str|None=None)` with `.trending.list(request: TrendingRequest|None=None, **overrides) -> TrendingResponse`, context-manager + `close()`; `AsyncFutureNews` same with `await`/`aclose()`. `_base.build_params(device_id) -> dict`, `_base.raise_for_response(resp)` mapping 403->BlockedError, 429->RateLimitError(retry_after), other >=400->APIError, httpx transport errors->ConnectionFailure. Random uuid4 device_id by default. + +- [ ] **Step 1:** respx tests (sync and async): `test_trending_list_sends_curl_shape` (method, path, params, JSON body, origin header), `test_403_html_raises_blocked`, `test_429_retry_after`, `test_cookies_forwarded`, `test_connect_error_wrapped`, `test_limit_validated_before_request`. +- [ ] **Step 2:** Run; expect FAIL. **Step 3:** Implement with shared logic in `_base`. **Step 4:** PASS, mypy --strict clean. **Step 5:** Commit. + +### Task 4: Live verification and examples + +**Files:** Create `examples/trending_sync.py`, `examples/trending_async.py`, `tests/test_live.py` (marked `live`, skipped by default); Modify `models.py` fields. + +- [ ] **Step 1:** Call the endpoint without cookies (and report result). If blocked, document the cookie/proxy option; if user supplies a sample, replace permissive parsing with real field names and add a test with an anonymized fixture in `tests/fixtures/trending.json`. +- [ ] **Step 2:** Examples use only public API; run them against live if allowed. **Step 3:** Commit. + +### Task 5: Docs site (SEO) + +**Files:** Create `mkdocs.yml`, `docs/index.md`, `docs/quickstart.md`, `docs/installation.md`, `docs/endpoints/trending.md`, `docs/errors.md`, `docs/faq.md`, `docs/chipa.md`, `docs/contributing.md`, `docs/robots.txt`, `.github/workflows/docs.yml`. + +- [ ] **Step 1:** mkdocs.yml: Material theme, `site_url`, `site_description`, social/meta plugins, API reference via mkdocstrings, footer with affiliate + Chipa links. Keyword-rich titles ("Future News API Python wrapper", "Future News trending markets API"). +- [ ] **Step 2:** Write pages (each with affiliate link and a Chipa promo admonition). **Step 3:** `mkdocs build --strict` passes. **Step 4:** Workflow deploys to GitHub Pages on push to main. **Step 5:** Commit. + +### Task 6: Contributor and CI files + +**Files:** Create `CONTRIBUTING.md`, `CODE_OF_CONDUCT.md`, `SECURITY.md`, `CHANGELOG.md`, `.github/ISSUE_TEMPLATE/{bug,feature}.md`, `.github/pull_request_template.md`, `.github/workflows/ci.yml`. + +- [ ] **Step 1:** CI matrix py3.9–3.13 runs ruff, mypy, pytest. **Step 2:** Run all three locally; expect clean. **Step 3:** Commit. + +## Self-review +Spec coverage: layout, clients, models, errors, optional cookies/proxy, docs/SEO, CI, community files, affiliate/Chipa links all mapped to tasks 1–6. Names consistent across tasks. From 0e79c2aec669b972765d17cf07544288e1909dfb Mon Sep 17 00:00:00 2001 From: Vigo Walker Date: Sun, 29 Nov 2026 15:19:36 +0100 Subject: [PATCH 02/11] feat: initialize project structure and add core functionality - Update .gitignore to include necessary directories and files. - Modify LICENSE to reflect the full name of the copyright holder. - Enhance README with installation instructions, usage examples, and project purpose. - Create progress tracking document for development tasks. - Add pyproject.toml for project metadata and dependencies. - Implement initial module structure in src/futurenews with versioning and affiliate links. - Add tests for affiliate links to ensure correctness. --- .gitignore | 226 ++--------------------------------- .superpowers/sdd/progress.md | 3 + LICENSE | 2 +- README.md | 33 ++++- pyproject.toml | 52 ++++++++ src/futurenews/__init__.py | 10 ++ src/futurenews/_links.py | 19 +++ src/futurenews/py.typed | 0 tests/test_links.py | 8 ++ 9 files changed, 132 insertions(+), 221 deletions(-) create mode 100644 .superpowers/sdd/progress.md create mode 100644 pyproject.toml create mode 100644 src/futurenews/__init__.py create mode 100644 src/futurenews/_links.py create mode 100644 src/futurenews/py.typed create mode 100644 tests/test_links.py diff --git a/.gitignore b/.gitignore index 6ff7378..9614178 100644 --- a/.gitignore +++ b/.gitignore @@ -1,223 +1,11 @@ -# Byte-compiled / optimized / DLL files +.venv/ __pycache__/ -*.py[codz] -*$py.class - -# C extensions -*.so - -# Distribution / packaging -.Python -build/ -develop-eggs/ -dist/ -downloads/ -eggs/ -.eggs/ -lib/ -lib64/ -parts/ -sdist/ -var/ -wheels/ -share/python-wheels/ *.egg-info/ -.installed.cfg -*.egg -MANIFEST - -# PyInstaller -# Usually these files are written by a python script from a template -# before PyInstaller builds the exe, so as to inject date/other infos into it. -*.manifest -*.spec - -# Installer logs -pip-log.txt -pip-delete-this-directory.txt - -# Unit test / coverage reports -htmlcov/ -.tox/ -.nox/ -.coverage -.coverage.* -.cache -nosetests.xml -coverage.xml -*.cover -*.py.cover -*.lcov -.hypothesis/ -.pytest_cache/ -cover/ - -# Translations -*.mo -*.pot - -# Django stuff: -*.log -local_settings.py -db.sqlite3 -db.sqlite3-journal - -# Flask stuff: -instance/ -.webassets-cache - -# Scrapy stuff: -.scrapy - -# Sphinx documentation -docs/_build/ - -# PyBuilder -.pybuilder/ -target/ - -# Jupyter Notebook -.ipynb_checkpoints - -# IPython -profile_default/ -ipython_config.py - -# pyenv -# For a library or package, you might want to ignore these files since the code is -# intended to run in multiple environments; otherwise, check them in: -# .python-version - -# pipenv -# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. -# However, in case of collaboration, if having platform-specific dependencies or dependencies -# having no cross-platform support, pipenv may install dependencies that don't work, or not -# install all needed dependencies. -# Pipfile.lock - -# uv -# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control. -# This is especially recommended for binary packages to ensure reproducibility, and is more -# commonly ignored for libraries. -# uv.lock - -# poetry -# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. -# This is especially recommended for binary packages to ensure reproducibility, and is more -# commonly ignored for libraries. -# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control -# poetry.lock -# poetry.toml - -# pdm -# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. -# pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python. -# https://pdm-project.org/en/latest/usage/project/#working-with-version-control -# pdm.lock -# pdm.toml -.pdm-python -.pdm-build/ - -# pixi -# Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control. -# pixi.lock -# Pixi creates a virtual environment in the .pixi directory, just like venv module creates one -# in the .venv directory. It is recommended not to include this directory in version control. -.pixi/* -!.pixi/config.toml - -# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm -__pypackages__/ - -# Celery stuff -celerybeat-schedule* -celerybeat.pid - -# Redis -*.rdb -*.aof -*.pid - -# RabbitMQ -mnesia/ -rabbitmq/ -rabbitmq-data/ - -# ActiveMQ -activemq-data/ - -# SageMath parsed files -*.sage.py - -# Environments -.env -.envrc -.venv -env/ -venv/ -ENV/ -env.bak/ -venv.bak/ - -# Conda environments -conda-meta/ - -# Spyder project settings -.spyderproject -.spyproject - -# Rope project settings -.ropeproject - -# mkdocs/Zensical documentation -/site - -# mypy +dist/ +build/ +site/ .mypy_cache/ -.dmypy.json -dmypy.json - -# Pyre type checker -.pyre/ - -# pytype static type analyzer -.pytype/ - -# Cython debug symbols -cython_debug/ - -# PyCharm -# JetBrains specific template is maintained in a separate JetBrains.gitignore that can -# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore -# and can be added to the global gitignore or merged into this file. For a more nuclear -# option (not recommended) you can uncomment the following to ignore the entire idea folder. -# .idea/ - -# Abstra -# Abstra is an AI-powered process automation framework. -# Ignore directories containing user credentials, local state, and settings. -# Learn more at https://abstra.io/docs -.abstra/ - -# Visual Studio Code -# Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore that -# can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore -# and can be added to the global gitignore or merged into this file. However, if you prefer, you -# could uncomment the following to ignore the entire vscode folder -# .vscode/ -# Temporary file for partial code execution -tempCodeRunnerFile.py - -# Ruff stuff: .ruff_cache/ - -# PyPI configuration file -.pypirc - -# Marimo -marimo/_static/ -marimo/_lsp/ -__marimo__/ - -# Streamlit -.streamlit/secrets.toml +.pytest_cache/ +.env +cookies*.json diff --git a/.superpowers/sdd/progress.md b/.superpowers/sdd/progress.md new file mode 100644 index 0000000..2aaa5d8 --- /dev/null +++ b/.superpowers/sdd/progress.md @@ -0,0 +1,3 @@ +# SDD ledger — plan: docs/superpowers/plans/2026-11-29-futurenews-api.md +Pre-flight: Task 3 consumes Task 2 (TrendingRequest/TrendingResponse/errors) - consistent. +Ruling: no worktree, used branch feat/initial-library — repo empty, single contributor — none diff --git a/LICENSE b/LICENSE index e6dfa21..51a174b 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ MIT License -Copyright (c) 2026 Chipa +Copyright (c) 2026 Chipa dev team Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/README.md b/README.md index 5fa2a39..9dffe81 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,33 @@ # FutureNewsAPI -the https://future.news/41L85FOV API for Python + +**Free, open-source Python wrapper (sync + async) for the [Future News](https://future.news/41L85FOV) API.** +Built and maintained by **Chipa dev team**. + +> New to Future News? [Sign up with our link](https://future.news/41L85FOV) — it supports this free project. + +```bash +pip install future-news-api +``` + +```python +from futurenews import FutureNews + +with FutureNews() as client: + trending = client.trending.list(limit=10) + for market in trending.items: + print(market) +``` + +(Client API lands in the next commits; see the docs.) + +## 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. + +## From Chipa dev team +- 🤖 [Custom 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) · [Community](https://chipatrade.com/community) + +## License +MIT © Chipa dev team. Not affiliated with Future News beyond the referral link above. diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..53fee5e --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,52 @@ +[build-system] +requires = ["hatchling"] +build-backend = "hatchling.build" + +[project] +name = "future-news-api" +version = "0.1.0" +description = "Free, open-source Python wrapper (sync + async) for the Future News API, by Chipa dev team." +readme = "README.md" +license = { text = "MIT" } +requires-python = ">=3.9" +authors = [{ name = "Chipa dev team" }] +keywords = ["future news", "future.news api", "prediction markets", "trending markets", "python api wrapper", "chipa"] +classifiers = [ + "Development Status :: 3 - Alpha", + "Intended Audience :: Developers", + "License :: OSI Approved :: MIT License", + "Programming Language :: Python :: 3", + "Typing :: Typed", +] +dependencies = ["httpx>=0.27", "pydantic>=2.5"] + +[project.optional-dependencies] +dev = ["pytest>=8", "pytest-asyncio>=0.23", "respx>=0.21", "ruff>=0.5", "mypy>=1.10"] +docs = ["mkdocs-material>=9.5", "mkdocstrings[python]>=0.25"] + +[project.urls] +Homepage = "https://future.news/41L85FOV" +Documentation = "https://chipa-dev-team.github.io/FutureNewsAPI/" +Source = "https://github.com/chipa-dev-team/FutureNewsAPI" +Discord = "https://discord.com/invite/qwQZ7rHzGb" +Community = "https://chipatrade.com/community" + +[tool.hatch.build.targets.wheel] +packages = ["src/futurenews"] + +[tool.pytest.ini_options] +asyncio_mode = "auto" +testpaths = ["tests"] +markers = ["live: hits the real Future News API (skipped by default)"] +addopts = "-m 'not live'" + +[tool.ruff] +line-length = 100 +src = ["src", "tests"] + +[tool.ruff.lint] +select = ["E", "F", "I", "UP", "B"] + +[tool.mypy] +strict = true +plugins = ["pydantic.mypy"] diff --git a/src/futurenews/__init__.py b/src/futurenews/__init__.py new file mode 100644 index 0000000..97563cf --- /dev/null +++ b/src/futurenews/__init__.py @@ -0,0 +1,10 @@ +"""futurenews: free, open-source Python wrapper for the Future News API. + +Made with love by **Chipa dev team** (https://chipatrade.com/community). +Sign up to Future News with our link: https://future.news/41L85FOV +""" + +from ._links import AFFILIATE_URL, LINKS + +__version__ = "0.1.0" +__all__ = ["AFFILIATE_URL", "LINKS", "__version__"] diff --git a/src/futurenews/_links.py b/src/futurenews/_links.py new file mode 100644 index 0000000..dd49d74 --- /dev/null +++ b/src/futurenews/_links.py @@ -0,0 +1,19 @@ +"""Single source of truth for every Chipa dev team / affiliate link. + +Keeping the links in one module means the README, docs and package +metadata can never drift apart. +""" + +from __future__ import annotations + +#: Future News affiliate link (shown everywhere, supports Chipa dev team). +AFFILIATE_URL = "https://future.news/41L85FOV" + +LINKS: dict[str, str] = { + "affiliate": AFFILIATE_URL, + "bot_development": "https://chipatrade.com/services/bot-development", + "exchange": "https://exchange.chipatrade.com/en/trade/BTC", + "editor": "https://chipaeditor.com", + "discord": "https://discord.com/invite/qwQZ7rHzGb", + "community": "https://chipatrade.com/community", +} diff --git a/src/futurenews/py.typed b/src/futurenews/py.typed new file mode 100644 index 0000000..e69de29 diff --git a/tests/test_links.py b/tests/test_links.py new file mode 100644 index 0000000..400c756 --- /dev/null +++ b/tests/test_links.py @@ -0,0 +1,8 @@ +import futurenews +from futurenews._links import LINKS + + +def test_affiliate_and_links(): + assert futurenews.AFFILIATE_URL == "https://future.news/41L85FOV" + assert set(LINKS) == {"bot_development", "exchange", "editor", "discord", "community", "affiliate"} + assert all(v.startswith("https://") for v in LINKS.values()) From 4062310d4f18637badf91e70f4acfdfb844fef88 Mon Sep 17 00:00:00 2001 From: Vigo Walker Date: Sun, 29 Nov 2026 15:19:37 +0100 Subject: [PATCH 03/11] chore: scaffold project Co-Authored-By: Claude Sonnet 5.5 --- pyproject.toml | 1 + 1 file changed, 1 insertion(+) diff --git a/pyproject.toml b/pyproject.toml index 53fee5e..fd2fdb2 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -39,6 +39,7 @@ asyncio_mode = "auto" testpaths = ["tests"] markers = ["live: hits the real Future News API (skipped by default)"] addopts = "-m 'not live'" +asyncio_default_fixture_loop_scope = "function" [tool.ruff] line-length = 100 From 444ac49a5cd2d70ec59abf7daa6634083c17a853 Mon Sep 17 00:00:00 2001 From: Vigo Walker Date: Sun, 29 Nov 2026 15:19:49 +0100 Subject: [PATCH 04/11] feat: add initial tests for error handling and model responses --- .superpowers/sdd/progress.md | 1 + src/futurenews/errors.py | 39 +++++++++++++++++++++++ src/futurenews/models.py | 61 ++++++++++++++++++++++++++++++++++++ tests/test_errors.py | 10 ++++++ tests/test_models.py | 38 ++++++++++++++++++++++ 5 files changed, 149 insertions(+) create mode 100644 src/futurenews/errors.py create mode 100644 src/futurenews/models.py create mode 100644 tests/test_errors.py create mode 100644 tests/test_models.py diff --git a/.superpowers/sdd/progress.md b/.superpowers/sdd/progress.md index 2aaa5d8..7727b7a 100644 --- a/.superpowers/sdd/progress.md +++ b/.superpowers/sdd/progress.md @@ -1,3 +1,4 @@ # SDD ledger — plan: docs/superpowers/plans/2026-11-29-futurenews-api.md Pre-flight: Task 3 consumes Task 2 (TrendingRequest/TrendingResponse/errors) - consistent. Ruling: no worktree, used branch feat/initial-library — repo empty, single contributor — none +Task 1: complete (pytest tests/test_links.py → 1 passed) diff --git a/src/futurenews/errors.py b/src/futurenews/errors.py new file mode 100644 index 0000000..b08dd10 --- /dev/null +++ b/src/futurenews/errors.py @@ -0,0 +1,39 @@ +"""Exception hierarchy for futurenews. + +Catch :class:`FutureNewsError` to handle everything this library raises. +""" + +from __future__ import annotations + + +class FutureNewsError(Exception): + """Base class for all errors raised by futurenews.""" + + +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 + + +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. + """ + + +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 + + +class ConnectionFailure(FutureNewsError): + """Network-level failure (DNS, timeout, connection refused).""" diff --git a/src/futurenews/models.py b/src/futurenews/models.py new file mode 100644 index 0000000..bfccf78 --- /dev/null +++ b/src/futurenews/models.py @@ -0,0 +1,61 @@ +"""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. +""" + +from __future__ import annotations + +from typing import Any + +from pydantic import BaseModel, ConfigDict, Field + + +class TrendingRequest(BaseModel): + """Body sent to ``POST /events/api/trending/list``.""" + + 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: int = 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() + + +class TrendingItem(BaseModel): + """One trending entry. Unknown fields are preserved.""" + + model_config = ConfigDict(extra="allow") + + +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. + + Accepts a top-level list, or a dict whose first list value + (preferring ``data``/``events``/``items``/``list``) holds the entries. + """ + raw: Any = None + if isinstance(payload, list): + raw = payload + elif isinstance(payload, dict): + for key in ("data", "events", "items", "list"): + if isinstance(payload.get(key), list): + raw = payload[key] + break + else: + raw = next((v for v in payload.values() if isinstance(v, list)), None) + return cls(items=[TrendingItem.model_validate(i) for i in (raw or []) if isinstance(i, dict)]) diff --git a/tests/test_errors.py b/tests/test_errors.py new file mode 100644 index 0000000..34d6e5a --- /dev/null +++ b/tests/test_errors.py @@ -0,0 +1,10 @@ +from futurenews.errors import APIError, BlockedError, ConnectionFailure, FutureNewsError, RateLimitError + + +def test_errors_hierarchy(): + assert issubclass(APIError, FutureNewsError) + assert issubclass(BlockedError, APIError) + assert issubclass(RateLimitError, APIError) + assert issubclass(ConnectionFailure, FutureNewsError) + e = RateLimitError(429, "slow down", retry_after=3.0) + assert e.status_code == 429 and e.retry_after == 3.0 diff --git a/tests/test_models.py b/tests/test_models.py new file mode 100644 index 0000000..7c5cfa6 --- /dev/null +++ b/tests/test_models.py @@ -0,0 +1,38 @@ +import pytest + +from futurenews.models import TrendingRequest, TrendingResponse + +CURL_BODY = { + "exclude_series": False, + "rank_type": "trending", + "categories": [], + "subcategories": [], + "status": ["active"], + "market_status": "active", + "order_by": "volume24h", + "limit": 100, +} + + +def test_request_body_matches_curl(): + assert TrendingRequest().to_body() == CURL_BODY + + +@pytest.mark.parametrize("limit", [0, 101, -1]) +def test_limit_out_of_range_raises(limit): + with pytest.raises(ValueError): + TrendingRequest(limit=limit) + + +def test_response_keeps_extra_fields(): + r = TrendingResponse.from_payload({"data": [{"id": "a", "weird": 1}]}) + assert r.items[0].model_dump()["weird"] == 1 + + +@pytest.mark.parametrize("payload", [None, {}, {"data": None}, []]) +def test_response_null_items_is_empty(payload): + assert TrendingResponse.from_payload(payload).items == [] + + +def test_response_accepts_top_level_list(): + assert len(TrendingResponse.from_payload([{"id": 1}, {"id": 2}]).items) == 2 From e110f6f79dd433394b3b8594a3fe9b3d29c08cab Mon Sep 17 00:00:00 2001 From: Vigo Walker Date: Sun, 29 Nov 2026 15:20:01 +0100 Subject: [PATCH 05/11] chore: restore original .gitignore, untrack local ledger Co-Authored-By: Claude Sonnet 5.5 --- .gitignore | 230 ++++++++++++++++++++++++++++++++++- .superpowers/sdd/progress.md | 4 - 2 files changed, 224 insertions(+), 10 deletions(-) delete mode 100644 .superpowers/sdd/progress.md diff --git a/.gitignore b/.gitignore index 9614178..d7de296 100644 --- a/.gitignore +++ b/.gitignore @@ -1,11 +1,229 @@ -.venv/ +# Byte-compiled / optimized / DLL files __pycache__/ -*.egg-info/ -dist/ +*.py[codz] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python build/ -site/ -.mypy_cache/ -.ruff_cache/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py.cover +*.lcov +.hypothesis/ .pytest_cache/ +cover/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +.pybuilder/ +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +# For a library or package, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# .python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +# Pipfile.lock + +# uv +# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +# uv.lock + +# poetry +# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control +# poetry.lock +# poetry.toml + +# pdm +# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. +# pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python. +# https://pdm-project.org/en/latest/usage/project/#working-with-version-control +# pdm.lock +# pdm.toml +.pdm-python +.pdm-build/ + +# pixi +# Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control. +# pixi.lock +# Pixi creates a virtual environment in the .pixi directory, just like venv module creates one +# in the .venv directory. It is recommended not to include this directory in version control. +.pixi/* +!.pixi/config.toml + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm +__pypackages__/ + +# Celery stuff +celerybeat-schedule* +celerybeat.pid + +# Redis +*.rdb +*.aof +*.pid + +# RabbitMQ +mnesia/ +rabbitmq/ +rabbitmq-data/ + +# ActiveMQ +activemq-data/ + +# SageMath parsed files +*.sage.py + +# Environments .env +.envrc +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Conda environments +conda-meta/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs/Zensical documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_debug/ + +# PyCharm +# JetBrains specific template is maintained in a separate JetBrains.gitignore that can +# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore +# and can be added to the global gitignore or merged into this file. For a more nuclear +# option (not recommended) you can uncomment the following to ignore the entire idea folder. +# .idea/ + +# Abstra +# Abstra is an AI-powered process automation framework. +# Ignore directories containing user credentials, local state, and settings. +# Learn more at https://abstra.io/docs +.abstra/ + +# Visual Studio Code +# Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore that +# can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore +# and can be added to the global gitignore or merged into this file. However, if you prefer, you +# could uncomment the following to ignore the entire vscode folder +# .vscode/ +# Temporary file for partial code execution +tempCodeRunnerFile.py + +# Ruff stuff: +.ruff_cache/ + +# PyPI configuration file +.pypirc + +# Marimo +marimo/_static/ +marimo/_lsp/ +__marimo__/ + +# Streamlit +.streamlit/secrets.toml + +# futurenews +.superpowers/ +.venv/ +site/ cookies*.json diff --git a/.superpowers/sdd/progress.md b/.superpowers/sdd/progress.md deleted file mode 100644 index 7727b7a..0000000 --- a/.superpowers/sdd/progress.md +++ /dev/null @@ -1,4 +0,0 @@ -# SDD ledger — plan: docs/superpowers/plans/2026-11-29-futurenews-api.md -Pre-flight: Task 3 consumes Task 2 (TrendingRequest/TrendingResponse/errors) - consistent. -Ruling: no worktree, used branch feat/initial-library — repo empty, single contributor — none -Task 1: complete (pytest tests/test_links.py → 1 passed) From a4aa0b16e6b562ead7bf57187b0d4e870ab07898 Mon Sep 17 00:00:00 2001 From: Vigo Walker Date: Sun, 29 Nov 2026 15:20:53 +0100 Subject: [PATCH 06/11] feat: sync and async clients with trending.list Co-Authored-By: Claude Sonnet 5.5 --- pyproject.toml | 2 +- src/futurenews/__init__.py | 25 ++++++- src/futurenews/_base.py | 73 +++++++++++++++++++ src/futurenews/client.py | 102 +++++++++++++++++++++++++++ src/futurenews/resources/__init__.py | 1 + src/futurenews/resources/trending.py | 65 +++++++++++++++++ tests/test_client.py | 91 ++++++++++++++++++++++++ tests/test_errors.py | 8 ++- tests/test_links.py | 9 ++- 9 files changed, 372 insertions(+), 4 deletions(-) create mode 100644 src/futurenews/_base.py create mode 100644 src/futurenews/client.py create mode 100644 src/futurenews/resources/__init__.py create mode 100644 src/futurenews/resources/trending.py create mode 100644 tests/test_client.py diff --git a/pyproject.toml b/pyproject.toml index fd2fdb2..43b1fb9 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -42,7 +42,7 @@ addopts = "-m 'not live'" asyncio_default_fixture_loop_scope = "function" [tool.ruff] -line-length = 100 +line-length = 110 src = ["src", "tests"] [tool.ruff.lint] diff --git a/src/futurenews/__init__.py b/src/futurenews/__init__.py index 97563cf..7cf577e 100644 --- a/src/futurenews/__init__.py +++ b/src/futurenews/__init__.py @@ -5,6 +5,29 @@ """ from ._links import AFFILIATE_URL, LINKS +from .client import AsyncFutureNews, FutureNews +from .errors import ( + APIError, + BlockedError, + ConnectionFailure, + FutureNewsError, + RateLimitError, +) +from .models import TrendingItem, TrendingRequest, TrendingResponse __version__ = "0.1.0" -__all__ = ["AFFILIATE_URL", "LINKS", "__version__"] +__all__ = [ + "AFFILIATE_URL", + "LINKS", + "APIError", + "AsyncFutureNews", + "BlockedError", + "ConnectionFailure", + "FutureNews", + "FutureNewsError", + "RateLimitError", + "TrendingItem", + "TrendingRequest", + "TrendingResponse", + "__version__", +] diff --git a/src/futurenews/_base.py b/src/futurenews/_base.py new file mode 100644 index 0000000..99005f5 --- /dev/null +++ b/src/futurenews/_base.py @@ -0,0 +1,73 @@ +"""Shared, I/O-free helpers used by both the sync and async clients. + +Keeping request building and response handling here means the two clients +stay thin and can never drift apart. +""" + +from __future__ import annotations + +import uuid +from typing import Any + +import httpx + +from .errors import APIError, 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": ( + "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) " + "Chrome/154.0.0.0 Safari/537.36" + ), +} + + +def new_device_id() -> str: + """Random per-client device id (the web app uses a uuid4).""" + return str(uuid.uuid4()) + + +def build_params(device_id: str) -> dict[str, str]: + """Query string the web app attaches to every events API call.""" + return { + "device_id": device_id, + "fp_did": "unknown", + "client_id": f"future_web_{APP_VERSION}", + "from_app": "future-web", + "app_ver": APP_VERSION, + "tz_name": "UTC", + "tz_offset": "0", + "app_lang": "en-US", + "os": "web", + "worker": "0", + } + + +def _retry_after(resp: httpx.Response) -> float | None: + try: + return float(resp.headers["retry-after"]) + except (KeyError, ValueError): + return None + + +def parse_response(resp: httpx.Response) -> Any: + """Raise the right :mod:`futurenews.errors` exception or return JSON.""" + if resp.status_code == 403: + raise BlockedError(403, "blocked (Cloudflare challenge?) - pass fresh cookies or a proxy") + if resp.status_code == 429: + raise RateLimitError(429, "rate limited", retry_after=_retry_after(resp)) + if resp.status_code >= 400: + raise APIError(resp.status_code, resp.text[:200]) + try: + return resp.json() + except ValueError as exc: # HTML/empty body on a 200 + raise APIError(resp.status_code, "response was not valid JSON") from exc diff --git a/src/futurenews/client.py b/src/futurenews/client.py new file mode 100644 index 0000000..77106de --- /dev/null +++ b/src/futurenews/client.py @@ -0,0 +1,102 @@ +"""Public clients: :class:`FutureNews` (sync) and :class:`AsyncFutureNews`. + +Made by Chipa dev team. Sign up to Future News: https://future.news/41L85FOV +""" + +from __future__ import annotations + +from types import TracebackType + +import httpx + +from ._base import BASE_URL, DEFAULT_HEADERS, new_device_id +from .resources.trending import AsyncTrending, Trending + + +def _headers(extra: dict[str, str] | None) -> dict[str, str]: + return {**DEFAULT_HEADERS, **(extra or {})} + + +class FutureNews: + """Synchronous Future News client. + + Args: + 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, + *, + 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._http = httpx.Client( + base_url=BASE_URL, + cookies=cookies, + headers=_headers(headers), + proxy=proxy, + timeout=timeout, + ) + self.trending = Trending(self) + + 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() + + +class AsyncFutureNews: + """Asynchronous Future News client (same arguments as :class:`FutureNews`).""" + + def __init__( + self, + *, + 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._http = httpx.AsyncClient( + base_url=BASE_URL, + cookies=cookies, + headers=_headers(headers), + proxy=proxy, + timeout=timeout, + ) + self.trending = AsyncTrending(self) + + 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() diff --git a/src/futurenews/resources/__init__.py b/src/futurenews/resources/__init__.py new file mode 100644 index 0000000..81e669b --- /dev/null +++ b/src/futurenews/resources/__init__.py @@ -0,0 +1 @@ +"""API resources (one module per endpoint family).""" diff --git a/src/futurenews/resources/trending.py b/src/futurenews/resources/trending.py new file mode 100644 index 0000000..a368ef2 --- /dev/null +++ b/src/futurenews/resources/trending.py @@ -0,0 +1,65 @@ +"""``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 new file mode 100644 index 0000000..e24d57b --- /dev/null +++ b/tests/test_client.py @@ -0,0 +1,91 @@ +import json + +import httpx +import pytest +import respx + +from futurenews import AsyncFutureNews, FutureNews +from futurenews.errors import APIError, BlockedError, ConnectionFailure, RateLimitError + +URL = "https://future.news/events/api/trending/list" +OK = {"data": [{"id": "m1", "title": "x"}]} + + +@respx.mock +def test_trending_list_sends_curl_shape(): + route = respx.post(URL).mock(return_value=httpx.Response(200, json=OK)) + with FutureNews(device_id="dev-1") as c: + res = c.trending.list(limit=5) + req = route.calls[0].request + assert json.loads(req.content)["limit"] == 5 + assert json.loads(req.content)["order_by"] == "volume24h" + q = dict(req.url.params) + assert q["device_id"] == "dev-1" and q["from_app"] == "future-web" and q["os"] == "web" + assert q["fp_did"] == "unknown" and q["worker"] == "0" and q["app_lang"] == "en-US" + assert req.headers["origin"] == "https://future.news" + assert req.headers["referer"] == "https://future.news/trending" + assert res.items[0].model_dump()["id"] == "m1" + + +@respx.mock +def test_403_html_raises_blocked(): + respx.post(URL).mock(return_value=httpx.Response(403, text="Just a moment")) + with pytest.raises(BlockedError), FutureNews() as c: + c.trending.list() + + +@respx.mock +def test_429_retry_after(): + respx.post(URL).mock(return_value=httpx.Response(429, headers={"retry-after": "7"}, text="no")) + with pytest.raises(RateLimitError) as e, FutureNews() as c: + c.trending.list() + assert e.value.retry_after == 7.0 + + +@respx.mock +def test_500_is_api_error(): + respx.post(URL).mock(return_value=httpx.Response(500, text="boom")) + with pytest.raises(APIError) as e, FutureNews() as c: + c.trending.list() + assert e.value.status_code == 500 + + +@respx.mock +def test_cookies_forwarded(): + route = respx.post(URL).mock(return_value=httpx.Response(200, json=OK)) + with FutureNews(cookies={"cf_clearance": "fake"}) as c: + c.trending.list() + assert "cf_clearance=fake" in route.calls[0].request.headers["cookie"] + + +@respx.mock +def test_connect_error_wrapped(): + respx.post(URL).mock(side_effect=httpx.ConnectError("down")) + with pytest.raises(ConnectionFailure), FutureNews() as c: + c.trending.list() + + +@respx.mock +def test_limit_validated_before_request(): + route = respx.post(URL).mock(return_value=httpx.Response(200, json=OK)) + with pytest.raises(ValueError), FutureNews() as c: + c.trending.list(limit=1000) + assert not route.called + + +@respx.mock +def test_empty_and_null_payload(): + respx.post(URL).mock(return_value=httpx.Response(200, json={"data": None})) + with FutureNews() as c: + assert c.trending.list().items == [] + + +@respx.mock +async def test_async_roundtrip_and_errors(): + respx.post(URL).mock(return_value=httpx.Response(200, json=OK)) + async with AsyncFutureNews() as c: + assert len((await c.trending.list()).items) == 1 + respx.post(URL).mock(return_value=httpx.Response(403, text="")) + with pytest.raises(BlockedError): + async with AsyncFutureNews() as c: + await c.trending.list() diff --git a/tests/test_errors.py b/tests/test_errors.py index 34d6e5a..d3e2e6a 100644 --- a/tests/test_errors.py +++ b/tests/test_errors.py @@ -1,4 +1,10 @@ -from futurenews.errors import APIError, BlockedError, ConnectionFailure, FutureNewsError, RateLimitError +from futurenews.errors import ( + APIError, + BlockedError, + ConnectionFailure, + FutureNewsError, + RateLimitError, +) def test_errors_hierarchy(): diff --git a/tests/test_links.py b/tests/test_links.py index 400c756..efb8884 100644 --- a/tests/test_links.py +++ b/tests/test_links.py @@ -4,5 +4,12 @@ def test_affiliate_and_links(): assert futurenews.AFFILIATE_URL == "https://future.news/41L85FOV" - assert set(LINKS) == {"bot_development", "exchange", "editor", "discord", "community", "affiliate"} + assert set(LINKS) == { + "bot_development", + "exchange", + "editor", + "discord", + "community", + "affiliate", + } assert all(v.startswith("https://") for v in LINKS.values()) From 4329c0d3f8451d8a052e8ca690b125ed692e7ef1 Mon Sep 17 00:00:00 2001 From: Vigo Walker Date: Sun, 29 Nov 2026 15:21:05 +0100 Subject: [PATCH 07/11] feat: examples and opt-in live test Co-Authored-By: Claude Sonnet 5.5 --- examples/trending_async.py | 14 ++++++++++++++ examples/trending_sync.py | 19 +++++++++++++++++++ tests/test_live.py | 19 +++++++++++++++++++ 3 files changed, 52 insertions(+) create mode 100644 examples/trending_async.py create mode 100644 examples/trending_sync.py create mode 100644 tests/test_live.py diff --git a/examples/trending_async.py b/examples/trending_async.py new file mode 100644 index 0000000..0cab24e --- /dev/null +++ b/examples/trending_async.py @@ -0,0 +1,14 @@ +"""List trending Future News markets (async). By Chipa dev team.""" + +import asyncio + +from futurenews import AsyncFutureNews + + +async def main() -> None: + async with AsyncFutureNews() as client: + res = await client.trending.list(limit=10) + print(len(res.items), "markets") + + +asyncio.run(main()) diff --git a/examples/trending_sync.py b/examples/trending_sync.py new file mode 100644 index 0000000..e8ed525 --- /dev/null +++ b/examples/trending_sync.py @@ -0,0 +1,19 @@ +"""List trending Future News markets (sync). + +Made by Chipa dev team - https://chipatrade.com/community +Sign up to Future News: https://future.news/41L85FOV +""" + +import os + +from futurenews import BlockedError, FutureNews + +# Optional: if Cloudflare blocks you, copy `cf_clearance` from your browser. +cookies = {"cf_clearance": os.environ["FN_CF_CLEARANCE"]} if "FN_CF_CLEARANCE" in os.environ else None + +with FutureNews(cookies=cookies) as client: + try: + for item in client.trending.list(limit=10).items: + print(item.model_dump()) + except BlockedError: + print("Blocked by Cloudflare - set FN_CF_CLEARANCE or use a proxy.") diff --git a/tests/test_live.py b/tests/test_live.py new file mode 100644 index 0000000..99f9c6c --- /dev/null +++ b/tests/test_live.py @@ -0,0 +1,19 @@ +"""Hits the real API. Run with: pytest -m live (set FN_CF_CLEARANCE if blocked).""" + +import os + +import pytest + +from futurenews import BlockedError, FutureNews + +pytestmark = pytest.mark.live + + +def test_live_trending(): + cookies = {"cf_clearance": os.environ["FN_CF_CLEARANCE"]} if "FN_CF_CLEARANCE" in os.environ else None + with FutureNews(cookies=cookies) as c: + try: + res = c.trending.list(limit=3) + except BlockedError: + pytest.skip("Cloudflare blocked the request") + assert len(res.items) <= 3 From 9f2caea3eb2c49b18ff1753a0b696645685a3887 Mon Sep 17 00:00:00 2001 From: Vigo Walker Date: Sun, 29 Nov 2026 15:21:48 +0100 Subject: [PATCH 08/11] docs: SEO docs site with Chipa promotion Co-Authored-By: Claude Sonnet 5.5 --- .github/workflows/docs.yml | 15 +++++++++++++++ docs/chipa.md | 9 +++++++++ docs/contributing.md | 10 ++++++++++ docs/endpoints/trending.md | 25 +++++++++++++++++++++++++ docs/errors.md | 22 ++++++++++++++++++++++ docs/faq.md | 11 +++++++++++ docs/index.md | 25 +++++++++++++++++++++++++ docs/installation.md | 10 ++++++++++ docs/quickstart.md | 28 ++++++++++++++++++++++++++++ mkdocs.yml | 30 ++++++++++++++++++++++++++++++ pyproject.toml | 4 ++-- 11 files changed, 187 insertions(+), 2 deletions(-) create mode 100644 .github/workflows/docs.yml create mode 100644 docs/chipa.md create mode 100644 docs/contributing.md create mode 100644 docs/endpoints/trending.md create mode 100644 docs/errors.md create mode 100644 docs/faq.md create mode 100644 docs/index.md create mode 100644 docs/installation.md create mode 100644 docs/quickstart.md create mode 100644 mkdocs.yml diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml new file mode 100644 index 0000000..f61c87f --- /dev/null +++ b/.github/workflows/docs.yml @@ -0,0 +1,15 @@ +name: docs +on: + push: + branches: [main] +permissions: + contents: write +jobs: + deploy: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: { python-version: "3.12" } + - run: pip install -e ".[docs]" + - run: mkdocs gh-deploy --force --strict diff --git a/docs/chipa.md b/docs/chipa.md new file mode 100644 index 0000000..c3d311e --- /dev/null +++ b/docs/chipa.md @@ -0,0 +1,9 @@ +# From Chipa dev team + +We build free tools and trading infrastructure. + +- [Custom 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) · [Community](https://chipatrade.com/community) +- [Future News (our referral link)](https://future.news/41L85FOV) diff --git a/docs/contributing.md b/docs/contributing.md new file mode 100644 index 0000000..b4a746f --- /dev/null +++ b/docs/contributing.md @@ -0,0 +1,10 @@ +# Contributing + +```bash +git clone https://github.com/ChipaDevTeam/FutureNewsAPI && cd FutureNewsAPI +python -m venv .venv && . .venv/bin/activate +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). diff --git a/docs/endpoints/trending.md b/docs/endpoints/trending.md new file mode 100644 index 0000000..08d77a6 --- /dev/null +++ b/docs/endpoints/trending.md @@ -0,0 +1,25 @@ +# Future News trending markets API (`trending.list`) + +Wraps `POST https://future.news/events/api/trending/list`. + +```python +client.trending.list(limit=50, order_by="volume24h") +``` + +| 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` | | + +Response fields are kept as returned (models allow extra fields), so new Future News fields never break your code. + +::: futurenews.models.TrendingRequest + +::: futurenews.models.TrendingResponse + +[Open Future News](https://future.news/41L85FOV) · [Build a bot with Chipa](https://chipatrade.com/services/bot-development) diff --git a/docs/errors.md b/docs/errors.md new file mode 100644 index 0000000..cd72708 --- /dev/null +++ b/docs/errors.md @@ -0,0 +1,22 @@ +# Errors and Cloudflare + +All errors inherit `FutureNewsError`. + +| Exception | When | +|---|---| +| `BlockedError` | HTTP 403, usually a Cloudflare challenge | +| `RateLimitError` | HTTP 429; see `.retry_after` | +| `APIError` | any other HTTP error | +| `ConnectionFailure` | network failure or timeout | + +## Getting past a Cloudflare block +Future News sits behind Cloudflare. If you get `BlockedError`, pass your own browser cookie or a proxy. This library never ships cookies: + +```python +FutureNews(cookies={"cf_clearance": ""}, proxy="http://user:pass@host:port") +``` + +!!! warning + Treat cookies like passwords. Never commit them. + +::: futurenews.errors diff --git a/docs/faq.md b/docs/faq.md new file mode 100644 index 0000000..f2120f8 --- /dev/null +++ b/docs/faq.md @@ -0,0 +1,11 @@ +# FAQ + +**Is there an official Future News Python SDK?** Not that we know of; this is a community library by Chipa dev team. + +**Is it free?** Yes, MIT-licensed. + +**Is it affiliated with Future News?** No, other than the [referral link](https://future.news/41L85FOV). + +**Why do I get 403?** See [Errors & Cloudflare](errors.md). + +**Can you build me a bot?** Yes: [Chipa bot development](https://chipatrade.com/services/bot-development). diff --git a/docs/index.md b/docs/index.md new file mode 100644 index 0000000..4831a42 --- /dev/null +++ b/docs/index.md @@ -0,0 +1,25 @@ +--- +title: Future News API for Python – free open-source wrapper +description: futurenews is a free Python library for the Future News API (future.news). Sync and async, typed, by Chipa dev team. +--- + +# Future News API for Python + +**futurenews** is a free, open-source Python wrapper for the [Future News](https://future.news/41L85FOV) API: sync and async clients, typed Pydantic models and clear errors for the trending markets endpoint. + +```bash +pip install future-news-api +``` + +```python +from futurenews import FutureNews + +with FutureNews() as client: + print(client.trending.list(limit=10).items) +``` + +!!! tip "Support the project" + [Create your Future News account with our link](https://future.news/41L85FOV). It costs you nothing and funds this library. + +!!! info "More from Chipa dev team" + Need a trading bot? [Custom 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/installation.md b/docs/installation.md new file mode 100644 index 0000000..b8fe646 --- /dev/null +++ b/docs/installation.md @@ -0,0 +1,10 @@ +# Install the Future News Python library + +```bash +pip install future-news-api +``` + +Requires Python 3.9+. Dependencies: `httpx`, `pydantic>=2`. + +!!! note + Don't have a Future News account yet? [Sign up here](https://future.news/41L85FOV). diff --git a/docs/quickstart.md b/docs/quickstart.md new file mode 100644 index 0000000..5eb2ca6 --- /dev/null +++ b/docs/quickstart.md @@ -0,0 +1,28 @@ +# Quickstart: call the Future News API from Python + +## Sync +```python +from futurenews import FutureNews + +with FutureNews() as client: + res = client.trending.list(limit=10) + for item in res.items: + print(item.model_dump()) +``` + +## Async +```python +import asyncio +from futurenews import AsyncFutureNews + +async def main(): + async with AsyncFutureNews() as client: + print((await client.trending.list(limit=10)).items) + +asyncio.run(main()) +``` + +Blocked by Cloudflare? See [Errors & Cloudflare](errors.md). + +!!! info "Automate it" + Want a bot built on this data? [Chipa bot development](https://chipatrade.com/services/bot-development). diff --git a/mkdocs.yml b/mkdocs.yml new file mode 100644 index 0000000..b82cb48 --- /dev/null +++ b/mkdocs.yml @@ -0,0 +1,30 @@ +site_name: Future News API for Python – futurenews +site_url: https://chipadevteam.github.io/FutureNewsAPI/ +site_description: Free, open-source Python wrapper for the Future News API (future.news). Sync and async clients, typed models, trending markets endpoint. By Chipa dev team. +site_author: Chipa dev team +repo_url: https://github.com/ChipaDevTeam/FutureNewsAPI +repo_name: ChipaDevTeam/FutureNewsAPI +copyright: © 2026 Chipa dev team · MIT · Sign up to Future News · Discord · Community +theme: + name: material + features: [navigation.sections, content.code.copy, search.suggest] +plugins: + - search + - mkdocstrings: + handlers: + python: + paths: [src] +nav: + - Home: index.md + - Installation: installation.md + - Quickstart: quickstart.md + - Endpoints: + - Trending markets: endpoints/trending.md + - Errors & Cloudflare: errors.md + - FAQ: faq.md + - From Chipa dev team: chipa.md + - Contributing: contributing.md +markdown_extensions: [admonition, attr_list, toc: {permalink: true}] + +exclude_docs: | + superpowers/ diff --git a/pyproject.toml b/pyproject.toml index 43b1fb9..3fff549 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -26,8 +26,8 @@ docs = ["mkdocs-material>=9.5", "mkdocstrings[python]>=0.25"] [project.urls] Homepage = "https://future.news/41L85FOV" -Documentation = "https://chipa-dev-team.github.io/FutureNewsAPI/" -Source = "https://github.com/chipa-dev-team/FutureNewsAPI" +Documentation = "https://chipadevteam.github.io/FutureNewsAPI/" +Source = "https://github.com/ChipaDevTeam/FutureNewsAPI" Discord = "https://discord.com/invite/qwQZ7rHzGb" Community = "https://chipatrade.com/community" From 1afa218c0c582d488df5ecb5a70939079e8756c9 Mon Sep 17 00:00:00 2001 From: Vigo Walker Date: Sun, 29 Nov 2026 15:21:55 +0100 Subject: [PATCH 09/11] chore: contributor files and CI Co-Authored-By: Claude Sonnet 5.5 --- .github/ISSUE_TEMPLATE/bug.md | 10 ++++++++++ .github/ISSUE_TEMPLATE/feature.md | 6 ++++++ .github/pull_request_template.md | 6 ++++++ .github/workflows/ci.yml | 16 ++++++++++++++++ CHANGELOG.md | 4 ++++ CODE_OF_CONDUCT.md | 3 +++ CONTRIBUTING.md | 14 ++++++++++++++ SECURITY.md | 3 +++ docs/quickstart.md | 2 ++ 9 files changed, 64 insertions(+) create mode 100644 .github/ISSUE_TEMPLATE/bug.md create mode 100644 .github/ISSUE_TEMPLATE/feature.md create mode 100644 .github/pull_request_template.md create mode 100644 .github/workflows/ci.yml create mode 100644 CHANGELOG.md create mode 100644 CODE_OF_CONDUCT.md create mode 100644 CONTRIBUTING.md create mode 100644 SECURITY.md diff --git a/.github/ISSUE_TEMPLATE/bug.md b/.github/ISSUE_TEMPLATE/bug.md new file mode 100644 index 0000000..79edf7b --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug.md @@ -0,0 +1,10 @@ +--- +name: Bug report +about: Something is broken +labels: bug +--- +**What happened?** + +**Minimal code** (remove cookies/tokens!) + +**Version** (`pip show future-news-api`): diff --git a/.github/ISSUE_TEMPLATE/feature.md b/.github/ISSUE_TEMPLATE/feature.md new file mode 100644 index 0000000..f38725b --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature.md @@ -0,0 +1,6 @@ +--- +name: Feature / endpoint request +about: Suggest an endpoint or improvement +labels: enhancement +--- +**What do you need?** (include the curl with secrets removed) diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 0000000..9721e37 --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,6 @@ +## What +## Checklist +- [ ] Tests added (failing first) +- [ ] `pytest`, `ruff`, `mypy` pass +- [ ] Docs updated +- [ ] No cookies/tokens committed diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..667fa4d --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,16 @@ +name: ci +on: [push, pull_request] +jobs: + test: + runs-on: ubuntu-latest + strategy: + matrix: + python: ["3.9", "3.10", "3.11", "3.12", "3.13"] + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: { python-version: "${{ matrix.python }}" } + - run: pip install -e ".[dev]" + - run: ruff check . && ruff format --check . + - run: mypy src + - run: pytest diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..41b8e0f --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,4 @@ +# Changelog + +## 0.1.0 +- Initial release: sync + async clients, `trending.list`, typed models, error hierarchy. By Chipa dev team. diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..f209fe6 --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,3 @@ +# Code of Conduct + +We follow the [Contributor Covenant 2.1](https://www.contributor-covenant.org/version/2/1/code_of_conduct/). Be respectful and constructive. Report problems via our [Discord](https://discord.com/invite/qwQZ7rHzGb) moderators. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..116199f --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,14 @@ +# Contributing to FutureNewsAPI + +Thanks for helping! Full guide: https://chipadevteam.github.io/FutureNewsAPI/contributing/ + +```bash +python -m venv .venv && . .venv/bin/activate +pip install -e ".[dev,docs]" +pytest && ruff check . && ruff format --check . && mypy src +``` + +- Write the failing test first (`respx` mocks HTTP; never hit the network in normal tests). +- Never commit cookies, tokens or device ids. +- Keep docstrings and comments thorough; this repo is meant to be easy to join. +- Chat with us on [Discord](https://discord.com/invite/qwQZ7rHzGb). diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..b9022ee --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,3 @@ +# Security + +Report vulnerabilities privately through GitHub's "Report a vulnerability" button on this repository (Security tab). Never post cookies or tokens in issues. diff --git a/docs/quickstart.md b/docs/quickstart.md index 5eb2ca6..ad6d738 100644 --- a/docs/quickstart.md +++ b/docs/quickstart.md @@ -15,10 +15,12 @@ with FutureNews() as client: import asyncio from futurenews import AsyncFutureNews + async def main(): async with AsyncFutureNews() as client: print((await client.trending.list(limit=10)).items) + asyncio.run(main()) ``` From 50ebf5988c77817beef4a5c77bcbe723d728c7db Mon Sep 17 00:00:00 2001 From: Vigo Walker Date: Sun, 29 Nov 2026 15:23:33 +0100 Subject: [PATCH 10/11] fix: robust trending payload parsing, reject unknown request options Co-Authored-By: Claude Sonnet 5.5 --- src/futurenews/models.py | 49 ++++++++++++++++++++++++++++------------ tests/test_models.py | 20 ++++++++++++++++ 2 files changed, 55 insertions(+), 14 deletions(-) diff --git a/src/futurenews/models.py b/src/futurenews/models.py index bfccf78..621dfe3 100644 --- a/src/futurenews/models.py +++ b/src/futurenews/models.py @@ -12,7 +12,12 @@ class TrendingRequest(BaseModel): - """Body sent to ``POST /events/api/trending/list``.""" + """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" @@ -45,17 +50,33 @@ class TrendingResponse(BaseModel): def from_payload(cls, payload: Any) -> TrendingResponse: """Build from raw JSON, tolerating null/missing/odd shapes. - Accepts a top-level list, or a dict whose first list value - (preferring ``data``/``events``/``items``/``list``) holds the entries. + 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: Any = None - if isinstance(payload, list): - raw = payload - elif isinstance(payload, dict): - for key in ("data", "events", "items", "list"): - if isinstance(payload.get(key), list): - raw = payload[key] - break - else: - raw = next((v for v in payload.values() if isinstance(v, list)), None) - return cls(items=[TrendingItem.model_validate(i) for i in (raw or []) if isinstance(i, dict)]) + raw, extras = _find_items(payload) + items = [TrendingItem.model_validate(i) for i in (raw or []) if isinstance(i, dict)] + return cls(items=items, **extras) + + +_ITEM_KEYS = ("data", "events", "items", "list") + + +def _find_items(payload: Any, depth: int = 0) -> tuple[list[Any] | None, dict[str, Any]]: + """Return ``(entries, wrapper_fields)`` for a payload; depth-limited.""" + if isinstance(payload, list): + return payload, {} + if not isinstance(payload, dict) or depth > 3: + return None, {} + for key in _ITEM_KEYS: + value = payload.get(key) + if isinstance(value, list): + return value, {k: v for k, v in payload.items() if k != key and k != "items"} + if isinstance(value, dict): + found, inner = _find_items(value, depth + 1) + if found is not None: + 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"} diff --git a/tests/test_models.py b/tests/test_models.py index 7c5cfa6..47c6fa0 100644 --- a/tests/test_models.py +++ b/tests/test_models.py @@ -36,3 +36,23 @@ def test_response_null_items_is_empty(payload): def test_response_accepts_top_level_list(): assert len(TrendingResponse.from_payload([{"id": 1}, {"id": 2}]).items) == 2 + + +def test_nested_envelope_is_unwrapped(): + r = TrendingResponse.from_payload({"code": 0, "data": {"list": [{"id": 1}]}}) + assert len(r.items) == 1 + + +def test_unrelated_list_is_not_treated_as_items(): + r = TrendingResponse.from_payload({"code": 1, "errors": [{"msg": "bad"}]}) + assert r.items == [] + + +def test_wrapper_fields_preserved(): + r = TrendingResponse.from_payload({"code": 0, "msg": "ok", "data": [{"id": 1}]}) + assert r.model_dump()["code"] == 0 and r.model_dump()["msg"] == "ok" + + +def test_misspelled_option_rejected(): + with pytest.raises(ValueError): + TrendingRequest(limt=5) From caac5eb2e9a7ece2db1484676af37c4aaa4ca920 Mon Sep 17 00:00:00 2001 From: Vigo Walker Date: Sun, 29 Nov 2026 15:28:18 +0100 Subject: [PATCH 11/11] fix: address review minors (Cloudflare detection, Retry-After, strict limit, docs SEO/links) Co-Authored-By: Claude Sonnet 5.5 --- README.md | 1 - docs/chipa.md | 5 ++++ docs/contributing.md | 7 +++++ docs/endpoints/trending.md | 5 ++++ docs/errors.md | 7 +++++ docs/faq.md | 5 ++++ docs/installation.md | 5 ++++ docs/quickstart.md | 7 +++++ docs/robots.txt | 3 ++ examples/trending_async.py | 6 +++- pyproject.toml | 7 ++++- src/futurenews/_base.py | 32 +++++++++++++++++---- src/futurenews/models.py | 4 +-- tests/test_client.py | 57 ++++++++++++++++++++++++++++++++++++++ tests/test_models.py | 6 ++++ 15 files changed, 147 insertions(+), 10 deletions(-) create mode 100644 docs/robots.txt diff --git a/README.md b/README.md index 9dffe81..ec4ecfc 100644 --- a/README.md +++ b/README.md @@ -18,7 +18,6 @@ with FutureNews() as client: print(market) ``` -(Client API lands in the next commits; see the docs.) ## 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/chipa.md b/docs/chipa.md index c3d311e..8b7de21 100644 --- a/docs/chipa.md +++ b/docs/chipa.md @@ -1,3 +1,8 @@ +--- +title: Chipa dev team products +description: Bot development, ChipaX exchange, Chipa Editor and community links from Chipa dev team. +--- + # From Chipa dev team We build free tools and trading infrastructure. diff --git a/docs/contributing.md b/docs/contributing.md index b4a746f..42e239e 100644 --- a/docs/contributing.md +++ b/docs/contributing.md @@ -1,3 +1,8 @@ +--- +title: Contribute to futurenews +description: Set up the dev environment and add a new Future News API endpoint. +--- + # Contributing ```bash @@ -8,3 +13,5 @@ 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). + +Supporting the project is free: [sign up to Future News with our link](https://future.news/41L85FOV). diff --git a/docs/endpoints/trending.md b/docs/endpoints/trending.md index 08d77a6..f1c5cff 100644 --- a/docs/endpoints/trending.md +++ b/docs/endpoints/trending.md @@ -1,3 +1,8 @@ +--- +title: Future News trending markets API in Python +description: Use client.trending.list to fetch trending markets from Future News with typed Python models. +--- + # Future News trending markets API (`trending.list`) Wraps `POST https://future.news/events/api/trending/list`. diff --git a/docs/errors.md b/docs/errors.md index cd72708..8ab15c9 100644 --- a/docs/errors.md +++ b/docs/errors.md @@ -1,3 +1,8 @@ +--- +title: Future News API errors and Cloudflare 403 fix +description: How to handle Cloudflare 403, rate limits and network errors when using the Future News API from Python. +--- + # Errors and Cloudflare All errors inherit `FutureNewsError`. @@ -20,3 +25,5 @@ FutureNews(cookies={"cf_clearance": ""}, proxy="http://user:p 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). diff --git a/docs/faq.md b/docs/faq.md index f2120f8..21ccbce 100644 --- a/docs/faq.md +++ b/docs/faq.md @@ -1,3 +1,8 @@ +--- +title: Future News API Python FAQ +description: Is there an official Future News Python SDK? Is it free? Why 403? Answers from Chipa dev team. +--- + # FAQ **Is there an official Future News Python SDK?** Not that we know of; this is a community library by Chipa dev team. diff --git a/docs/installation.md b/docs/installation.md index b8fe646..217e85a 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -1,3 +1,8 @@ +--- +title: Install the Future News Python library +description: pip install future-news-api. Requires Python 3.9+. Free and open source. +--- + # Install the Future News Python library ```bash diff --git a/docs/quickstart.md b/docs/quickstart.md index ad6d738..1533b8c 100644 --- a/docs/quickstart.md +++ b/docs/quickstart.md @@ -1,3 +1,8 @@ +--- +title: Future News API Python quickstart (sync and async) +description: Call the Future News API from Python in a few lines with the free futurenews library by Chipa dev team. +--- + # Quickstart: call the Future News API from Python ## Sync @@ -28,3 +33,5 @@ Blocked by Cloudflare? See [Errors & Cloudflare](errors.md). !!! info "Automate it" Want a bot built on this data? [Chipa bot development](https://chipatrade.com/services/bot-development). + +New here? [Create your Future News account](https://future.news/41L85FOV) first. diff --git a/docs/robots.txt b/docs/robots.txt new file mode 100644 index 0000000..aab16e0 --- /dev/null +++ b/docs/robots.txt @@ -0,0 +1,3 @@ +User-agent: * +Allow: / +Sitemap: https://chipadevteam.github.io/FutureNewsAPI/sitemap.xml diff --git a/examples/trending_async.py b/examples/trending_async.py index 0cab24e..b644eeb 100644 --- a/examples/trending_async.py +++ b/examples/trending_async.py @@ -1,4 +1,8 @@ -"""List trending Future News markets (async). By Chipa dev team.""" +"""List trending Future News markets (async). + +Made by Chipa dev team - https://chipatrade.com/community +Sign up to Future News: https://future.news/41L85FOV +""" import asyncio diff --git a/pyproject.toml b/pyproject.toml index 3fff549..bc3debb 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -16,12 +16,17 @@ classifiers = [ "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", "Typing :: Typed", ] dependencies = ["httpx>=0.27", "pydantic>=2.5"] [project.optional-dependencies] -dev = ["pytest>=8", "pytest-asyncio>=0.23", "respx>=0.21", "ruff>=0.5", "mypy>=1.10"] +dev = ["pytest>=8", "pytest-asyncio>=0.24", "respx>=0.21", "ruff>=0.5", "mypy>=1.10"] docs = ["mkdocs-material>=9.5", "mkdocstrings[python]>=0.25"] [project.urls] diff --git a/src/futurenews/_base.py b/src/futurenews/_base.py index 99005f5..cead3f4 100644 --- a/src/futurenews/_base.py +++ b/src/futurenews/_base.py @@ -7,6 +7,8 @@ from __future__ import annotations import uuid +from datetime import datetime, timezone +from email.utils import parsedate_to_datetime from typing import Any import httpx @@ -53,21 +55,41 @@ def build_params(device_id: str) -> dict[str, str]: def _retry_after(resp: httpx.Response) -> float | None: + """Parse ``Retry-After`` (seconds or HTTP date); never negative.""" + raw = resp.headers.get("retry-after") + if raw is None: + return None + try: + return max(0.0, float(raw)) + except ValueError: + pass try: - return float(resp.headers["retry-after"]) - except (KeyError, ValueError): + when = parsedate_to_datetime(raw) + except (TypeError, ValueError): return None + if when.tzinfo is None: + when = when.replace(tzinfo=timezone.utc) + return max(0.0, (when - datetime.now(timezone.utc)).total_seconds()) + + +def _is_challenge(resp: httpx.Response) -> bool: + """True if this looks like a Cloudflare interstitial instead of API JSON.""" + if resp.headers.get("cf-mitigated"): + return True + return "text/html" in resp.headers.get("content-type", "") and resp.status_code in (200, 403, 503) def parse_response(resp: httpx.Response) -> Any: """Raise the right :mod:`futurenews.errors` exception or return JSON.""" - if resp.status_code == 403: - raise BlockedError(403, "blocked (Cloudflare challenge?) - pass fresh cookies or a proxy") + if resp.status_code == 403 or _is_challenge(resp): + raise BlockedError( + resp.status_code, "blocked (Cloudflare challenge?) - pass fresh cookies or a proxy" + ) if resp.status_code == 429: raise RateLimitError(429, "rate limited", retry_after=_retry_after(resp)) if resp.status_code >= 400: raise APIError(resp.status_code, resp.text[:200]) try: return resp.json() - except ValueError as exc: # HTML/empty body on a 200 + except ValueError as exc: # empty/non-JSON body on a 200 raise APIError(resp.status_code, "response was not valid JSON") from exc diff --git a/src/futurenews/models.py b/src/futurenews/models.py index 621dfe3..fc56bec 100644 --- a/src/futurenews/models.py +++ b/src/futurenews/models.py @@ -8,7 +8,7 @@ from typing import Any -from pydantic import BaseModel, ConfigDict, Field +from pydantic import BaseModel, ConfigDict, Field, StrictInt class TrendingRequest(BaseModel): @@ -26,7 +26,7 @@ class TrendingRequest(BaseModel): status: list[str] = Field(default_factory=lambda: ["active"]) market_status: str = "active" order_by: str = "volume24h" - limit: int = Field(default=100, ge=1, le=100) + 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.""" diff --git a/tests/test_client.py b/tests/test_client.py index e24d57b..6b2c77a 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -89,3 +89,60 @@ async def test_async_roundtrip_and_errors(): with pytest.raises(BlockedError): async with AsyncFutureNews() as c: await c.trending.list() + + +@respx.mock +def test_503_cloudflare_challenge_is_blocked(): + respx.post(URL).mock( + return_value=httpx.Response(503, headers={"cf-mitigated": "challenge"}, text="") + ) + with pytest.raises(BlockedError), FutureNews() as c: + c.trending.list() + + +@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" + ) + ) + with pytest.raises(BlockedError), FutureNews() as c: + c.trending.list() + + +@respx.mock +def test_retry_after_http_date_and_negative(): + respx.post(URL).mock(return_value=httpx.Response(429, headers={"retry-after": "-5"}, text="no")) + with pytest.raises(RateLimitError) as e, FutureNews() as c: + c.trending.list() + assert e.value.retry_after == 0.0 + respx.post(URL).mock( + return_value=httpx.Response(429, headers={"retry-after": "Wed, 21 Oct 2099 07:28:00 GMT"}, text="no") + ) + with pytest.raises(RateLimitError) as e2, FutureNews() as c: + c.trending.list() + assert e2.value.retry_after is not None and e2.value.retry_after > 0 + + +@respx.mock +def test_request_object_with_overrides(): + from futurenews import TrendingRequest + + route = respx.post(URL).mock(return_value=httpx.Response(200, json=OK)) + with FutureNews() as c: + c.trending.list(TrendingRequest(limit=7, order_by="x"), limit=3) + body = json.loads(route.calls[0].request.content) + assert body["limit"] == 3 and body["order_by"] == "x" + + +@respx.mock +async def test_async_429_and_connection_failure(): + respx.post(URL).mock(return_value=httpx.Response(429, headers={"retry-after": "2"}, text="x")) + async with AsyncFutureNews() as c: + with pytest.raises(RateLimitError): + await c.trending.list() + respx.post(URL).mock(side_effect=httpx.ConnectError("down")) + async with AsyncFutureNews() as c: + with pytest.raises(ConnectionFailure): + await c.trending.list() diff --git a/tests/test_models.py b/tests/test_models.py index 47c6fa0..7b2ceac 100644 --- a/tests/test_models.py +++ b/tests/test_models.py @@ -56,3 +56,9 @@ def test_wrapper_fields_preserved(): def test_misspelled_option_rejected(): with pytest.raises(ValueError): TrendingRequest(limt=5) + + +@pytest.mark.parametrize("limit", ["5", True, 5.0]) +def test_limit_must_be_a_real_int(limit): + with pytest.raises(ValueError): + TrendingRequest(limit=limit)