Metadata-Version: 2.4
Name: apitube-api
Version: 0.0.5
Summary: Python API to interact with APITube endpoints
License: BSD-3-Clause License
License-File: LICENSE
Author: Murabei Data Science
Author-email: a.baceti@murabei.com
Requires-Python: >=3.12
Classifier: Programming Language :: Python :: 3
Classifier: Operating System :: OS Independent
Requires-Dist: loguru
Requires-Dist: pandas (>=2.2.0,<3.0.0)
Requires-Dist: pydantic (>=2.10.0,<3.0.0)
Requires-Dist: requests (>=2.32.5,<3.0.0)
Requires-Dist: tenacity (>=9.1.4,<10.0.0)
Description-Content-Type: text/markdown

# apitube-api

Python client for the [APITube News API](https://docs.apitube.io/platform/news-api).
Murabei crawlers use it to suggest entities, topics, and industries, and to
search and page through news articles with one shared HTTP stack and error
types.

## Table of contents

1. [Objective and scope](#objective-and-scope) (includes [How it is
   used](#how-it-is-used))
2. [Requirements](#requirements)
3. [Install](#install)
4. [Authentication](#authentication)
5. [Client overview](#client-overview)
6. [Suggest endpoints](#suggest-endpoints)
7. [News search (`news_everything`)](#news-search-news_everything)
8. [Filter reference (common cases)](#filter-reference-common-cases)
9. [Pagination and return shape](#pagination-and-return-shape)
10. [Errors and validation](#errors-and-validation)
11. [Low-level HTTP (`get` / `post`)](#low-level-http-get--post)
12. [Configuration (environment)](#configuration-environment)
13. [Integration tests](#integration-tests)
14. [Development and release](#development-and-release)
15. [Further reading](#further-reading)
16. [License](#license)

---

## Objective and scope

This package is a Python client for APITube suggest and news HTTP
endpoints. Murabei crawlers use it to resolve filter ids and fetch
paginated article data with shared timeouts and errors.

### Why this package exists

Calling APITube from many workers with ad hoc `requests` code duplicates
timeouts, headers, and error handling. This library centralizes:

- Bearer authentication
- Request timeout
- Validation of news search bodies (Pydantic)
- Mapping of HTTP failures to `ApiTubeAPIRequestError`
- Optional multi-page fetch for `news_everything`

### How it is used

Install the wheel or source build, pass an APITube key to
`ApiTubeAPI`, call suggest helpers to discover entity or topic ids,
then `news_everything` for a `DataFrame` of articles. Queue workers
and crawlers own scheduling and storage; this library handles HTTP,
validation, and pagination only.

### What this package does not do

- Store or rotate API keys (you pass the key at construction)
- Schedule crawls or persist articles (caller's responsibility)
- Full-text search inside article bodies via the API (see
  [Filter reference](#filter-reference-common-cases))

---

## Requirements

- **Python** `>= 3.12` (see `pyproject_template.toml`)
- **APITube API key** from your APITube account
- **pandas** — required for `news_everything` (`DataFrame` results); also
  loaded when importing `ApiTubeAPI` because the news mixin is part of
  the client class.

Declared dependencies include `pandas`, `requests`, `pydantic`, `loguru`,
and `tenacity`.

---

## Install

### From a wheel

```bash
pip install dist/*.whl
```

### From source (Poetry)

```bash
pip install poetry
export VERSION=$(grep -E '^VERSION=' VERSION | cut -d'=' -f2-)
sed -e 's#{VERSION}#'"${VERSION}"'#g' pyproject_template.toml > pyproject.toml
poetry build
pip install dist/*.whl
```

### Import

```python
from apitube_api.data import ApiTubeAPI
```

`apitube_api` also re-exports `ApiTubeAPI` from the package root:

```python
from apitube_api import ApiTubeAPI
```

---

## Authentication

Pass your APITube key when you create the client. It is sent on every
request as an `Authorization: Bearer <key>` header.

```python
from apitube_api.data import ApiTubeAPI

api = ApiTubeAPI(api_key="YOUR_APITUBE_KEY")
```

Do not commit keys. In tests, use `test_parameters.secrets` (see
[Integration tests](#integration-tests)).

---

## Client overview

`ApiTubeAPI` combines three mixins:

| Area | Methods | APITube paths |
|------|---------|----------------|
| Suggest | `suggest_entities`, `suggest_categories`, `suggest_industries`,
  `suggest_topics` | `GET /v1/suggest/{kind}` |
| News | `news_everything` | `POST /v1/news/everything` (+ pagination `GET`) |
| HTTP | `get`, `post` | Any path under `https://api.apitube.io` |

Typical workflow:

1. **Suggest** names or ids (entity, topic, category, industry).
2. **Search** news with those ids or with title/query filters.
3. **Consume** a pandas `DataFrame` of articles (or call `get`/`post`
   directly for custom endpoints).

---

## Suggest endpoints

All suggest methods take a **`prefix`** string (required by APITube) and
return a **`list[dict]`**—one dict per suggestion, already validated.

### `suggest_entities(prefix)`

Find people, organizations, brands, and other entity types before using
`entity.id` in news search.

```python
rows = api.suggest_entities(prefix="Apple")
for row in rows:
    print(row["id"], row["type"], row["name"])
    print(row["links"]["self"])  # URL to news about this entity
```

Common keys per row:

| Key | Type | Meaning |
|-----|------|---------|
| `id` | `int` | Use in `entity.id` when searching news |
| `name` | `str` | Display name |
| `type` | `str` | e.g. `person`, `organization`, `brand` |
| `links` | `dict` | Includes `self` (news URL for this entity) |
| `metadata` | `dict` or `None` | Extra profile fields |

Docs: [Suggest entities](https://docs.apitube.io/platform/news-api/suggest/entities).

### `suggest_categories(prefix)`

IPTC-style category codes for `category.id` filters.

```python
rows = api.suggest_categories(prefix="sport")
# row["id"] might look like "medtop:15000000"
```

| Key | Notes |
|-----|--------|
| `id` | IPTC Media Topic code—pass unchanged to `category.id` |
| `taxonomy` | e.g. `iptc_mediatopics` |

### `suggest_industries(prefix)`

Numeric industry ids for `industry.id`.

```python
rows = api.suggest_industries(prefix="tech")
# row["id"] is int
```

### `suggest_topics(prefix)`

Topic ids for `topic.id` (subject tags, not free text).

```python
rows = api.suggest_topics(prefix="crypto")
# e.g. id "industry.crypto_news", name "Crypto Industry News"
```

Docs: [Filter by topic](https://support.apitube.io/en/articles/searching-and-filtering/by-attribute/filter-by-topic).

---

## News search (`news_everything`)

Search the news archive with the same filters as APITube's
[everything](https://docs.apitube.io/platform/news-api/everything)
endpoint. This client validates the body, posts JSON, follows
`next_page` links, and concatenates results into one table.

### Basic example

```python
news = api.news_everything(
    body={
        "title": "Bitcoin",
        "language.code": "en",
        "published_at.start": "NOW-7DAYS",
        "sort.by": "published_at",
        "sort.order": "desc",
    },
    per_page=10,
    max_pages=3,
)

df = news["results"]
print(news["n_pages"], news["had_reached_max_pages"])
print(df[["id", "title", "href", "published_at", "page"]].head())
```

### Parameters

| Parameter | Where | Description |
|-----------|--------|-------------|
| `body` | Method | JSON filters; keys match APITube (dots OK, e.g.
  `language.code`). `None` means no extra filters. |
| `per_page` | Method | Results per API page (1–250). Default:
  `APITUBE__NEWS_PER_PAGE` (25). **Overrides** any `per_page` in
  `body`. |
| `max_pages` | Method | Max pages to fetch. Default: `APITUBE__MAX_PAGES`
  (50). Stops early if the API has no `next_page`. |

### Field list (`fl`)

Optional body key **`fl`**: comma-separated APITube field names returned
per article. On the **first** `POST` page the client builds the
`DataFrame` with those column names (including when the API returns zero
rows). Each page also gets **`page`** and **`request_id`**.

```python
news = api.news_everything(
    body={
        "title": "Bitcoin",
        "fl": (
            "article_id,published_at,title,summary,body,href,"
            "language,source_domain"
        ),
    },
    per_page=10,
)
```

Follow-up **`GET`** pages use the field set from the API URL (they do not
re-read `fl` from your original body). Prefer one page or matching
`fl` in the query if you need consistent columns across pages.

The default `fl` on `ApiTubeNewsEverythingRequest` lists common fields
(`id`, `title`, `body`, `href`, …). See
`apitube_api.aux.news.contracts.ApiTubeNewsEverythingRequest`.

Plan limits on the APITube side still apply (for example Free tier often
caps `per_page` at 10—see APITube docs if you get `ER0171`).

### Request validation

Bodies are validated against `ApiTubeNewsEverythingRequest` before the
HTTP call. Unknown filter keys raise **Pydantic `ValidationError`**
locally (the client uses `extra="forbid"`).

Supported fields are defined in code:

```python
from apitube_api.aux.news import ApiTubeNewsEverythingRequest
```

The full list mirrors [News API filters](https://docs.apitube.io/platform/news-api/filters).

Use **dotted keys in the dict** exactly as in the API:

```python
body = {
    "entity.id": "1278268",
    "language.code": "en",
    "published_at.start": "NOW-7DAYS",
}
```

---

## Filter reference (common cases)

### Search in headlines

| Body key | Role |
|----------|------|
| `title` | Match words in the **title** (synonyms, AND logic for multiple words). |
| `query` | Boolean title search: `AND`, `OR`, `NOT`, parentheses. Example: `"bitcoin AND NOT (etf OR futures)"`. |
| `title_pattern` | Substring in title (not regex). |
| `search` | Highlight only—**does not filter** results. |

Title and `query` searches are limited to a **31-day** `published_at`
window. Without dates, APITube uses the last 31 days. Wider ranges return
`ER0110`.

There is **no** API filter to search only inside article **body** text.
Fields like `body`, `description`, or `keywords` inside `query` return
`ER0702` (unknown field). To match body text you must fetch articles (e.g.
by topic or title) and filter locally on `body` in the response—or use a
higher APITube plan feature such as `prompt` (not wrapped here).

### Entities, topics, and industries

| Body key | How to get valid values |
|----------|-------------------------|
| `entity.id` | `suggest_entities` → `id` (comma-separated, max 3) |
| `topic.id` | `suggest_topics` → `id` (e.g. `industry.crypto_news`) |
| `industry.id` | `suggest_industries` → `id` |
| `category.id` | `suggest_categories` → `id` |
| `organization.name` | Exact names; ambiguous names may return `ER0220` |

Example: crypto topic plus English and recent dates:

```python
news = api.news_everything(
    body={
        "topic.id": "industry.crypto_news",
        "language.code": "en",
        "published_at.start": "NOW-7DAYS",
        "sort.by": "published_at",
        "sort.order": "desc",
    },
    per_page=10,
    max_pages=5,
)
```

### Dates and language

| Body key | Examples |
|----------|----------|
| `published_at.start` | `NOW-7DAYS`, `2026-01-01` |
| `published_at.end` | End of range |
| `language.code` | `en`, `pt` (up to 3 comma-separated) |

### Sorting

| Body key | Values (examples) |
|----------|-------------------|
| `sort.by` | `published_at`, `relevance`, `sentiment.overall.score`, … |
| `sort.order` | `asc`, `desc` |

---

## Pagination and return shape

`news_everything` does not return the raw APITube envelope. It returns:

| Key | Type | Meaning |
|-----|------|---------|
| `results` | `pandas.DataFrame` | All rows from pages 1 … `n_pages` concatenated |
| `n_pages` | `int` | Number of pages actually retrieved |
| `had_reached_max_pages` | `bool` | `True` if stopping was because `max_pages` was hit while more pages might exist |

Pagination behavior:

1. First request: `POST /v1/news/everything` with your `body` and `per_page`.
2. While `has_next_pages` and `n_page <= max_pages`, the client `GET`s
   the absolute URL in `next_page` (auth header still applied).
3. Progress is logged with **loguru** (`Fetching page …`).

Columns depend on **`fl`** in the request (see above) or the contract
default. Nested API objects appear as dict/list cells in the
`DataFrame`. Rows always include **`page`** and **`request_id`** from
the envelope.

---

## Errors and validation

### HTTP / APITube errors

Non-success HTTP responses raise **`ApiTubeAPIRequestError`** (or a
subclass) with `message` and `payload` (includes `url` and error JSON).
When the body is not JSON (for example HTML from HTTP 520), the client
still maps the failure and puts `response.text` in the payload instead
of raising while parsing JSON.

Mapped codes:

| Exception | APITube code | Typical cause |
|-----------|--------------|----------------|
| `ApiTubeAPIMissingAPIKeyError` | `ER0201` | Missing API key |
| `ApiTubeAPIInvalidAPIKeyError` | `ER0202` | Invalid API key |
| `ApiTubeAPIRequestError` | (other) | Generic API or HTTP failure |

Example:

```python
from apitube_api.exceptions import ApiTubeAPIRequestError

try:
    api.news_everything(body={"title": "test"}, per_page=10)
except ApiTubeAPIRequestError as exc:
  print(exc.to_dict())
```

### Client-side validation

| Failure | Exception |
|---------|-----------|
| Invalid `body` keys or types | `pydantic.ValidationError` |
| `per_page` not in 1…250 | `ValueError` |
| `max_pages` below 1 | `ValueError` |
| `get`/`post` without `endpoint` or `url` | `ValueError` |

---

## Low-level HTTP (`get` / `post`)

Use when you need a path or a full URL (for example a bookmarked
`next_page` without going through `news_everything`).

```python
# Path under https://api.apitube.io
data = api.get(
    endpoint="/v1/suggest/entities",
    query_params={"prefix": "Apple"},
)

# Absolute URL (pagination)
data = api.get(url="https://api.apitube.io/v1/news/everything?...")
```

```python
data = api.post(
    endpoint="/v1/news/everything",
    data={"title": "Bitcoin", "per_page": 10},
)
```

Returns the parsed JSON **`dict`** (or list for bare suggest arrays—`get`
still returns whatever `response.json()` is; suggest methods wrap that).

Timeout: `APITUBE__REQUEST_TIMEOUT`.

---

## Configuration (environment)

Read at import time from the environment. Blank values keep defaults.
Values must be positive integers.

| Variable | Default | Used for |
|----------|---------|----------|
| `APITUBE__REQUEST_TIMEOUT` | `60` | Seconds per HTTP request |
| `APITUBE__NEWS_PER_PAGE` | `25` | Default `per_page` when the method argument is omitted |
| `APITUBE__MAX_PAGES` | `50` | Default `max_pages` when the method argument is omitted |

The API key is **not** read from the environment by this library—you pass
it to `ApiTubeAPI(api_key=...)`.

---

## Integration tests

Tests call the live APITube API (suggest endpoints and `news_everything`
pagination, `query` filter, and zero-hit results).

1. Copy `test_parameters.template` to `test_parameters.secrets`.
2. Set `APITUBE__KEY` to your test key (`test_parameters.secrets` is
   gitignored).
3. Run:

```bash
set -a && source test_parameters.secrets && set +a
python -m unittest discover -s tests -v
```

---

## Development and release

```bash
ruff check src/
```

Release build (increments patch in `VERSION`, renders `pyproject.toml`,
tags, pushes—see `build.sh`):

```bash
./build.sh
```

On `main`, CI builds from `VERSION` and `pyproject_template.toml` and may
publish to PyPI when `PYPI_API_TOKEN` is set.

---

## Further reading

- [Search articles — `/v1/news/everything`](https://docs.apitube.io/platform/news-api/everything)
- [News API filters](https://docs.apitube.io/platform/news-api/filters)
- [Query builder](https://docs.apitube.io/platform/news-api/query-builder)
- [HTTP response codes](https://docs.apitube.io/platform/news-api/http-response-codes)
- [Monitor cryptocurrency news (use case)](https://support.apitube.io/en/articles/use-cases/finance/monitor-crypto)

Package history: [CHANGELOG.md](CHANGELOG.md).

---

## License

BSD-3-Clause — see [LICENSE](LICENSE).
