Skip to main content

apitube-api

Python client for the APITube 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 (includes How it is used)
  2. Requirements
  3. Install
  4. Authentication
  5. Client overview
  6. Suggest endpoints
  7. News search (news_everything)
  8. Filter reference (common cases)
  9. Pagination and return shape
  10. Errors and validation
  11. Low-level HTTP (get / post)
  12. Configuration (environment)
  13. Integration tests
  14. Development and release
  15. Further reading
  16. 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)

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

pip install dist/*.whl

From source (Poetry)

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

from apitube_api.data import ApiTubeAPI

apitube_api also re-exports ApiTubeAPI from the package root:

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.

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).


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.

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.

suggest_categories(prefix)

IPTC-style category codes for category.id filters.

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.

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

suggest_topics(prefix)

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

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

Docs: Filter by topic.


News search (news_everything)

Search the news archive with the same filters as APITube's everything endpoint. This client validates the body, posts JSON, follows next_page links, and concatenates results into one table.

Basic example

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.

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:

from apitube_api.aux.news import ApiTubeNewsEverythingRequest

The full list mirrors News API filters.

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

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:

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 GETs the absolute URL in next_page (auth header still applied).
  3. Progress is logged with loguru (Fetching page …).

Each page's rows are normalized to a fixed set of columns (missing fields appear as empty). The DataFrame includes page and request_id from the envelope. Expected columns include:

id, title, href, published_at, source, author, content, image, video, audio, and several source_* authority fields (see NEWS_RESULTS_COLUMNS in apitube_api.aux.news.news).

Rows may contain more data in the underlying API JSON than fits those columns; this client keeps the tabular projection above for downstream pandas workflows.


Errors and validation

HTTP / APITube errors

Non-success HTTP responses raise ApiTubeAPIRequestError (or a subclass) with message and payload (includes url and error 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:

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).

# 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?...")
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.

  1. Copy test_parameters.template to test_parameters.secrets.
  2. Set APITUBE__KEY to your test key (test_parameters.secrets is gitignored).
  3. Run:
set -a && source test_parameters.secrets && set +a
python -m unittest discover -s tests -v

Development and release

ruff check src/

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

./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

Package history: CHANGELOG.md.


License

BSD-3-Clause — see LICENSE.

Metadata

Release files for apitube-api 0.0.3

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for apitube-api 0.0.3
File Size Uploaded Provenance Actions
apitube_api-0.0.3.tar.gz 23.1 kB Without provenance Details for apitube_api-0.0.3.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for apitube-api 0.0.3
File Interpreter ABI Platform Actions
apitube_api-0.0.3-py3-none-any.whl Python 3 none any Details for apitube_api-0.0.3-py3-none-any.whl

Total release size: 44.8 kB

Release files / apitube_api-0.0.3.tar.gz

Download URL apitube_api-0.0.3.tar.gz
Size 23.1 kB
Tags Source
SHA-256 checksum
How to use checksums
b16bd6234ec17b07e305697da67ca5eb8496963a655f0a09da86ef983902acb2
BLAKE2b-256 checksum
How to use checksums
498db8ae48adf0521fad529cbd836b4a829b29031f9e4f1166cd6e84433cf473
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/2.5.2 CPython/3.12.16 Linux/7.0.0-1020-azure

Release files / apitube_api-0.0.3-py3-none-any.whl

Download URL apitube_api-0.0.3-py3-none-any.whl
Size 21.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
4e77d5de9c3e40ac5f0d4e56a403e0756fd985e35f12fc2a01d5b203c33dd8b8
BLAKE2b-256 checksum
How to use checksums
3b6104b65166804377545ee5a5a38f4621735d631b0c6f11f964b37b61d181f0
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/2.5.2 CPython/3.12.16 Linux/7.0.0-1020-azure

Security for apitube-api 0.0.3

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.0.3 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page