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/.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/.gitignore b/.gitignore index 6ff7378..d7de296 100644 --- a/.gitignore +++ b/.gitignore @@ -221,3 +221,9 @@ __marimo__/ # Streamlit .streamlit/secrets.toml + +# futurenews +.superpowers/ +.venv/ +site/ +cookies*.json 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/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..ec4ecfc 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,32 @@ # 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) +``` + + +## 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/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/chipa.md b/docs/chipa.md new file mode 100644 index 0000000..8b7de21 --- /dev/null +++ b/docs/chipa.md @@ -0,0 +1,14 @@ +--- +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. + +- [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..42e239e --- /dev/null +++ b/docs/contributing.md @@ -0,0 +1,17 @@ +--- +title: Contribute to futurenews +description: Set up the dev environment and add a new Future News API endpoint. +--- + +# 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). + +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 new file mode 100644 index 0000000..f1c5cff --- /dev/null +++ b/docs/endpoints/trending.md @@ -0,0 +1,30 @@ +--- +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`. + +```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..8ab15c9 --- /dev/null +++ b/docs/errors.md @@ -0,0 +1,29 @@ +--- +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`. + +| 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 + +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 new file mode 100644 index 0000000..21ccbce --- /dev/null +++ b/docs/faq.md @@ -0,0 +1,16 @@ +--- +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. + +**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..217e85a --- /dev/null +++ b/docs/installation.md @@ -0,0 +1,15 @@ +--- +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 +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..1533b8c --- /dev/null +++ b/docs/quickstart.md @@ -0,0 +1,37 @@ +--- +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 +```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). + +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/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. diff --git a/examples/trending_async.py b/examples/trending_async.py new file mode 100644 index 0000000..b644eeb --- /dev/null +++ b/examples/trending_async.py @@ -0,0 +1,18 @@ +"""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 + +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/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 new file mode 100644 index 0000000..bc3debb --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,58 @@ +[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", + "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.24", "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://chipadevteam.github.io/FutureNewsAPI/" +Source = "https://github.com/ChipaDevTeam/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'" +asyncio_default_fixture_loop_scope = "function" + +[tool.ruff] +line-length = 110 +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..7cf577e --- /dev/null +++ b/src/futurenews/__init__.py @@ -0,0 +1,33 @@ +"""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 +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", + "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..cead3f4 --- /dev/null +++ b/src/futurenews/_base.py @@ -0,0 +1,95 @@ +"""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 datetime import datetime, timezone +from email.utils import parsedate_to_datetime +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: + """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: + 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 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: # empty/non-JSON body on a 200 + raise APIError(resp.status_code, "response was not valid JSON") from exc 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/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/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..fc56bec --- /dev/null +++ b/src/futurenews/models.py @@ -0,0 +1,82 @@ +"""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, StrictInt + + +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() + + +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. + + 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) + + +_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/src/futurenews/py.typed b/src/futurenews/py.typed new file mode 100644 index 0000000..e69de29 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..6b2c77a --- /dev/null +++ b/tests/test_client.py @@ -0,0 +1,148 @@ +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() + + +@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_errors.py b/tests/test_errors.py new file mode 100644 index 0000000..d3e2e6a --- /dev/null +++ b/tests/test_errors.py @@ -0,0 +1,16 @@ +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_links.py b/tests/test_links.py new file mode 100644 index 0000000..efb8884 --- /dev/null +++ b/tests/test_links.py @@ -0,0 +1,15 @@ +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()) 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 diff --git a/tests/test_models.py b/tests/test_models.py new file mode 100644 index 0000000..7b2ceac --- /dev/null +++ b/tests/test_models.py @@ -0,0 +1,64 @@ +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 + + +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) + + +@pytest.mark.parametrize("limit", ["5", True, 5.0]) +def test_limit_must_be_a_real_int(limit): + with pytest.raises(ValueError): + TrendingRequest(limit=limit)