Metadata-Version: 2.5
Name: tubepull
Version: 0.1.0
Summary: Official Python SDK for the TubePull video download API: download YouTube, TikTok, Instagram, Reddit, X and Twitch videos as MP4 or MP3.
Project-URL: Homepage, https://tubepull.com/developers
Project-URL: Documentation, https://tubepull.com/developers/docs
Project-URL: API reference (OpenAPI), https://tubepull.com/developers/openapi.json
Project-URL: Source, https://github.com/miketwalker/tubepull-python
Project-URL: Issues, https://github.com/miketwalker/tubepull-python/issues
Project-URL: Changelog, https://github.com/miketwalker/tubepull-python/blob/main/CHANGELOG.md
Project-URL: Examples, https://github.com/miketwalker/tubepull-video-download-api
Author-email: Moondust Studios <mike@moonduststudios.com>
License-Expression: MIT
License-File: LICENSE
Keywords: instagram api,mp3,mp4,openapi,reddit video,sdk,tiktok api,tubepull,twitter video,video download api,youtube download api
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Internet :: WWW/HTTP
Classifier: Topic :: Multimedia :: Video
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Python: >=3.10
Requires-Dist: httpx<1,>=0.23
Provides-Extra: dev
Requires-Dist: build; extra == 'dev'
Requires-Dist: mypy>=1.8; extra == 'dev'
Requires-Dist: pytest-asyncio>=0.21; extra == 'dev'
Requires-Dist: pytest>=7; extra == 'dev'
Requires-Dist: respx>=0.20; extra == 'dev'
Requires-Dist: ruff>=0.5; extra == 'dev'
Requires-Dist: twine; extra == 'dev'
Description-Content-Type: text/markdown

# TubePull Python SDK

[![PyPI](https://img.shields.io/pypi/v/tubepull.svg)](https://pypi.org/project/tubepull/)
[![CI](https://github.com/miketwalker/tubepull-python/actions/workflows/ci.yml/badge.svg)](https://github.com/miketwalker/tubepull-python/actions/workflows/ci.yml)
[![Python](https://img.shields.io/pypi/pyversions/tubepull.svg)](https://pypi.org/project/tubepull/)

**`tubepull` is the official Python SDK for the [TubePull video download API](https://tubepull.com/developers).** Give it a public YouTube, TikTok, Instagram, Reddit, X (Twitter), Twitch, Facebook or Vimeo URL and it returns a finished MP4 or MP3 file on a signed download link. TubePull does the fetching, merging and transcoding. Your code takes three calls: `download()`, `wait()`, `save()`.

```python
from tubepull import TubePull

with TubePull() as tp:  # reads TUBEPULL_API_KEY
    job = tp.download("https://www.tiktok.com/@scout2015/video/6718335390845095173")
    job = tp.wait(job)
    print(tp.save(job, "downloads/"))  # downloads/<request_token>.mp4
```

- Sync `TubePull` and async `AsyncTubePull` clients with the same methods
- Typed dataclasses for every response, plus a typed exception for every API error
- Polling with backoff, `Retry-After` handling on 429s, and file saving that streams to disk and checks the size
- One dependency: [`httpx`](https://www.python-httpx.org/). Python 3.10+

## Install

```bash
pip install tubepull
```

Get an API key from the [TubePull Developer portal](https://tubepull.com/developers) and export it:

```bash
export TUBEPULL_API_KEY="tp_live_your_api_key_here"
```

The key is a Bearer token, so keep it in an environment variable or a secrets manager, not in source code. You can also pass it directly: `TubePull(api_key="tp_live_...")`.

## Quickstart

### Download a video as MP4

```python
from tubepull import TubePull

tp = TubePull()

job = tp.download("https://www.youtube.com/watch?v=dQw4w9WgXcQ", quality="1080")
print(job.request_token, job.status)  # 9f8c...  queued

job = tp.wait(job, timeout=900)  # polls GET /video/status with backoff
print(job.download_url, job.expires_in, job.file_size_bytes, job.file_mime)

path = tp.save(job, "downloads/")  # streams the signed file to disk
```

`format` is `"video"` (MP4) or `"audio"` (MP3). `quality` is a maximum height (`"2160"`, `"1440"`, `"1080"`, `"720"`, `"480"`, `"360"`) or `"best"`, which is the default.

### Extract audio as MP3

```python
job = tp.wait(tp.download("https://soundcloud.com/artist/track", format="audio"))
tp.save(job, "podcast.mp3")
```

### Check a link before spending a download credit

```python
meta = tp.metadata("https://www.instagram.com/reel/REEL_ID/")
print(meta.platform, meta.title, meta.duration, meta.content_kind)
for option in meta.quality_selector.options:
    print(option.value, option.label)
```

`metadata()` uses your metadata allowance, not a download credit, and no file is fetched.

### Check your credits and rate limit

```python
credits = tp.credits()  # free to call
print(credits.plan, credits.downloads.remaining, credits.metadata.remaining)

print(tp.rate_limit)  # from the last response's headers
# RateLimit(limit=..., remaining=..., reset=..., credits_remaining=...)
```

The SDK doesn't hardcode plan limits. `tp.rate_limit` reflects the `X-RateLimit-*` and `X-Credits-Remaining` headers on the most recent response.

### Async

```python
import asyncio
from tubepull import AsyncTubePull


async def main() -> None:
    async with AsyncTubePull() as tp:
        jobs = [await tp.download(u) for u in URLS]
        done = await asyncio.gather(*(tp.wait(j) for j in jobs))
        for job in done:
            await tp.save(job, "downloads/")


asyncio.run(main())
```

## API

| Method | Endpoint | Returns |
|---|---|---|
| `download(url, format="video", quality="best")` | `POST /video/download` | `Job` (`status="queued"`) |
| `status(job_or_token)` | `GET /video/status` | `Job` |
| `wait(job_or_token, timeout=900, *, poll_interval=5, max_interval=60, backoff=2)` | polls `GET /video/status` | `Job` (`status="done"`) |
| `metadata(url)` | `GET /video/metadata` | `Metadata` |
| `credits()` | `GET /credits` | `Credits` |
| `create_key(label=None)` | `POST /auth/key` | `ApiKey` |
| `save(job, path=".", *, chunk_size=1 MiB)` | signed `download_url` | `pathlib.Path` |

Downloads run asynchronously. A job moves through `queued`, `claimed` and `running` to `done` or `failed`. When it is `done`, `download_url` is a signed link valid for `expires_in` seconds (one hour). If the link expires, call `status()` again with the same token for a fresh one.

`save()` takes a file path or a directory. In a directory, or with a path ending in `/`, the file is named `<request_token>.<ext>` from `file_mime`. It writes to a `.part` file and renames it only when the size matches `file_size_bytes`. The signed link is fetched without your API key.

Client options: `TubePull(api_key=None, *, base_url=None, timeout=30, max_retries=2, max_retry_wait=60, http_client=None)`. `base_url` defaults to `$TUBEPULL_API_BASE` or `https://tubepull.com/api/v1`.

Every model keeps the full response dict in `.raw`, so a field added on the server is never lost.

## Supported platforms

Each platform page covers the URL formats it accepts and its quirks:

- [YouTube download API](https://tubepull.com/developers/youtube-download-api): `youtube.com`, `youtu.be` and `music.youtube.com`, up to 4K
- [TikTok download API](https://tubepull.com/developers/tiktok-download-api): full and short links, watermark-free MP4
- [Instagram download API](https://tubepull.com/developers/instagram-download-api): public Reels, posts and carousels. Stories and highlights need a one-time account link
- [Reddit video download API](https://tubepull.com/developers/reddit-video-download-api): `v.redd.it` video and audio merged into one MP4. Needs a one-time Reddit account link
- [X (Twitter) video download API](https://tubepull.com/developers/twitter-video-download-api): `x.com`, `twitter.com` and `t.co` links
- [Twitch download API](https://tubepull.com/developers/twitch-download-api): clips and VODs
- [Facebook video download API](https://tubepull.com/developers/facebook-video-download-api): public videos and reels
- [Audio extraction API](https://tubepull.com/developers/audio-extraction-api): turn a video URL into an MP3, for example for transcription

Vimeo, Dailymotion, SoundCloud, Bandcamp, Mixcloud, Pinterest and Streamable are supported too. The [API reference](https://tubepull.com/developers/docs) has the current list.

## Error handling

Every API error raises a subclass of `tubepull.TubePullError`. Errors from the API itself (`APIError` and its subclasses) carry `status_code`, `code`, `message`, `details` and `headers`.

| Exception | HTTP | `code` | What to do |
|---|---|---|---|
| `InvalidRequestError` | 400 | `invalid_request` | Fix the request (missing URL or bad token) |
| `UnsupportedPlatformError` | 400 | `unsupported_platform` | Skip the link. No credit was spent |
| `AuthError` | 401 | `unauthorized` | Check the API key. Also raised by the constructor when no key is set |
| `QuotaExceededError` | 402 | `download_quota_exceeded`, `metadata_quota_exceeded`, `hard_cap_reached` | Stop the batch. Upgrade or raise your overage cap |
| `NotFoundError` | 404 | `not_found` | Unknown token, or a token from another account |
| `RateLimitError` | 429 | `rate_limited` | Wait `err.retry_after` seconds |
| `ContentBlockedError` | 451 | `content_blocked_dmca` | Don't retry. See `reference_id` and `counter_notice_url` |
| `ServerError` | 5xx | `enqueue_failed`, `metadata_unavailable`, `delivery_failed`, `key_create_failed` | Retry later. For `delivery_failed`, queue a new download |
| `JobFailedError` | n/a | `err.error` bucket | Raised by `wait()` when a job ends `failed`. Final for that URL |
| `WaitTimeoutError` | n/a | n/a | `wait()` ran out of time. Also a `TimeoutError` |
| `DownloadError` | n/a | n/a | `save()` failed, the link expired or the size didn't match |
| `APIConnectionError` | n/a | n/a | Network problem. No HTTP response |

```python
from tubepull import QuotaExceededError, RateLimitError, TubePull, TubePullError

tp = TubePull()
for url in urls:
    try:
        tp.save(tp.wait(tp.download(url)), "downloads/")
    except QuotaExceededError:
        break  # out of credits or at the overage cap
    except RateLimitError as err:
        print(f"rate limited, retry in {err.retry_after}s")
        break
    except TubePullError as err:
        print(f"skipped {url}: {err}")
```

Retries: the client retries `429 rate_limited` on its own, up to `max_retries` times, when `Retry-After` is no longer than `max_retry_wait` seconds. Longer waits raise `RateLimitError` straight away so you can decide what to do. Other errors aren't retried, because a failed download request may already have spent a credit. During `wait()`, a 429 sleeps for `Retry-After` when that still fits inside `timeout`.

## Links

- [Developer portal and API keys](https://tubepull.com/developers)
- [API reference](https://tubepull.com/developers/docs)
- [OpenAPI 3.1 spec](https://tubepull.com/developers/openapi.json)
- [Examples: cURL, Python, Node.js](https://github.com/miketwalker/tubepull-video-download-api)
- [Node.js / TypeScript SDK (`tubepull-api` on npm)](https://github.com/miketwalker/tubepull-node)
- [Python tutorial: download TikTok, Instagram, Reddit and X videos](https://tubepull.com/blog/download-social-videos-python-rest-api)

## Acceptable use

Only download content you own, have permission or a licence to use, or that is in the public domain, and follow each platform's terms. Use of the API is governed by [Section 8 (Developer API) of the TubePull Terms](https://tubepull.com/legal/terms#developer-api). URLs blocked under a copyright takedown return `451` (`ContentBlockedError`).

## License

[MIT](LICENSE) © Moondust Studios
