ytapi-sdk 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
ytapi/__init__.py ADDED
@@ -0,0 +1,22 @@
1
+ """Python client for the YTAPI HTTP API. https://docs.ytapi.dev"""
2
+
3
+ from .client import YTAPI
4
+ from .errors import (
5
+ AuthError,
6
+ InsufficientCreditsError,
7
+ NotFoundError,
8
+ RateLimitedError,
9
+ ServerError,
10
+ YTAPIError,
11
+ )
12
+
13
+ __all__ = [
14
+ "AuthError",
15
+ "InsufficientCreditsError",
16
+ "NotFoundError",
17
+ "RateLimitedError",
18
+ "ServerError",
19
+ "YTAPI",
20
+ "YTAPIError",
21
+ ]
22
+ __version__ = "0.1.0"
ytapi/client.py ADDED
@@ -0,0 +1,421 @@
1
+ """Sync client for https://api.ytapi.dev."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import http.client
6
+ import json
7
+ import os
8
+ import time
9
+ import urllib.error
10
+ import urllib.parse
11
+ import urllib.request
12
+ from collections.abc import Callable, Iterator, Mapping, Sequence
13
+ from typing import Any
14
+
15
+ from .errors import (
16
+ AuthError,
17
+ InsufficientCreditsError,
18
+ NotFoundError,
19
+ RateLimitedError,
20
+ ServerError,
21
+ YTAPIError,
22
+ )
23
+ from .models import (
24
+ TEXT_FORMATS,
25
+ BatchJob,
26
+ BatchSubmit,
27
+ BatchTask,
28
+ Channel,
29
+ ChannelLatest,
30
+ ChannelPlaylistsPage,
31
+ ChannelPlaylist,
32
+ ChannelVideo,
33
+ ChannelVideosPage,
34
+ DurationFilter,
35
+ PlaylistPage,
36
+ PlaylistVideo,
37
+ SearchItem,
38
+ SearchPage,
39
+ SearchSort,
40
+ SearchType,
41
+ SortBy,
42
+ Suggestions,
43
+ TrackPolicy,
44
+ Transcript,
45
+ TranscriptFormat,
46
+ UploadDate,
47
+ VideoBasicInfo,
48
+ VideoInfo,
49
+ )
50
+
51
+ _USER_AGENT = "ytapi-python/0.1.0 (+https://docs.ytapi.dev)"
52
+ _ENV_KEYS = ("YTAPI_API_KEY", "YTAPI_KEY")
53
+ # A free account's daily limit answers 429 with Retry-After until 00:00 UTC.
54
+ # Waiting that long inside a call would hang the caller, so it is raised.
55
+ _DAILY_LIMIT_CODE = "daily_limit_exceeded"
56
+ _ERROR_TYPES: dict[int, type[YTAPIError]] = {
57
+ 401: AuthError,
58
+ 402: InsufficientCreditsError,
59
+ 404: NotFoundError,
60
+ 429: RateLimitedError,
61
+ }
62
+
63
+
64
+ class YTAPI:
65
+ """Synchronous YTAPI client.
66
+
67
+ ``api_key`` falls back to the ``YTAPI_API_KEY`` environment variable,
68
+ then ``YTAPI_KEY``.
69
+
70
+ ``max_retries`` is the number of extra attempts after the first. They are
71
+ used for HTTP 429, 5xx and network errors (timeouts, dropped connections),
72
+ unless the body sets ``retryable`` to false. A 429 whose ``Retry-After`` is
73
+ longer than ``max_retry_wait`` seconds, such as a free account's daily
74
+ limit, is raised at once instead of waited out. ``max_retries=0`` disables
75
+ retries. Creating a batch is never retried after a 5xx or a network error,
76
+ since the job may already exist.
77
+ """
78
+
79
+ def __init__(
80
+ self,
81
+ api_key: str | None = None,
82
+ *,
83
+ base_url: str = "https://api.ytapi.dev",
84
+ timeout: float = 30,
85
+ max_retries: int = 2,
86
+ backoff: float = 0.5,
87
+ backoff_cap: float = 8,
88
+ max_retry_wait: float = 60,
89
+ sleep: Callable[[float], None] = time.sleep,
90
+ monotonic: Callable[[], float] = time.monotonic,
91
+ ) -> None:
92
+ key = api_key
93
+ if key is None:
94
+ key = next((os.environ[name] for name in _ENV_KEYS if os.environ.get(name)), None)
95
+ if not key:
96
+ raise ValueError("Pass api_key or set the YTAPI_API_KEY environment variable.")
97
+ if max_retries < 0:
98
+ raise ValueError("max_retries must be >= 0.")
99
+ self.api_key = key
100
+ self.base_url = base_url.rstrip("/")
101
+ self.timeout = timeout
102
+ self.max_retries = max_retries
103
+ self.backoff = backoff
104
+ self.backoff_cap = backoff_cap
105
+ self.max_retry_wait = max_retry_wait
106
+ self._sleep = sleep
107
+ self._monotonic = monotonic
108
+
109
+ def get_transcript(
110
+ self,
111
+ video_id: str,
112
+ *,
113
+ format: TranscriptFormat | None = None,
114
+ word_level: bool | None = None,
115
+ languages: Sequence[str] | None = None,
116
+ track_policy: TrackPolicy | None = None,
117
+ ) -> Transcript | str:
118
+ """Captions for one video. Text formats return the document as a string."""
119
+ body: dict[str, Any] = {"video_id": video_id}
120
+ if format is not None:
121
+ body["format"] = format
122
+ if word_level is not None:
123
+ body["word_level"] = word_level
124
+ if languages is not None:
125
+ body["languages"] = list(languages)
126
+ if track_policy is not None:
127
+ body["track_policy"] = track_policy
128
+ as_text = format in TEXT_FORMATS
129
+ return self._request("POST", "/v1/transcripts", json_body=body, as_text=as_text)
130
+
131
+ def get_basic_info(self, video_id: str) -> VideoBasicInfo:
132
+ """Title, duration, channel and caption languages. Costs 0 credits."""
133
+ return self._request("GET", f"/v1/videos/{_seg(video_id)}/basic-info")
134
+
135
+ def get_video_info(self, video_id: str) -> VideoInfo:
136
+ """Full metadata, including description, counts and chapters. 1 credit."""
137
+ return self._request("GET", f"/v1/videos/{_seg(video_id)}/video-info")
138
+
139
+ def get_playlist(self, playlist_id: str, *, cursor: str | None = None) -> PlaylistPage:
140
+ """One page of a playlist. Later pages carry videos only. 1 credit per page."""
141
+ return self._request(
142
+ "GET", f"/v1/playlists/{_seg(playlist_id)}", query={"cursor": cursor}
143
+ )
144
+
145
+ def iter_playlist_videos(self, playlist_id: str) -> Iterator[PlaylistVideo]:
146
+ """Every video in a playlist, following ``next_cursor``."""
147
+ yield from _pages(
148
+ lambda cursor: self.get_playlist(playlist_id, cursor=cursor),
149
+ "videos",
150
+ )
151
+
152
+ def get_channel(self, channel_id: str) -> Channel:
153
+ """Channel profile. ``channel_id`` may be ``@handle`` or ``UC...``. 1 credit."""
154
+ return self._request("GET", f"/v1/channels/{_seg(channel_id)}")
155
+
156
+ def get_channel_latest(self, channel_id: str) -> ChannelLatest:
157
+ """The latest upload and a short list of recent videos. 1 credit."""
158
+ return self._request("GET", f"/v1/channels/{_seg(channel_id)}/latest")
159
+
160
+ def list_channel_videos(
161
+ self,
162
+ channel_id: str,
163
+ *,
164
+ cursor: str | None = None,
165
+ sort_by: SortBy | None = None,
166
+ ) -> ChannelVideosPage:
167
+ """One page of uploads. 1 credit per page."""
168
+ return self._request(
169
+ "GET",
170
+ f"/v1/channels/{_seg(channel_id)}/videos",
171
+ query={"cursor": cursor, "sort_by": sort_by},
172
+ )
173
+
174
+ def iter_channel_videos(
175
+ self, channel_id: str, *, sort_by: SortBy | None = None
176
+ ) -> Iterator[ChannelVideo]:
177
+ """Every upload, following ``next_cursor``. ``sort_by`` is sent on each page."""
178
+ yield from _pages(
179
+ lambda cursor: self.list_channel_videos(
180
+ channel_id, cursor=cursor, sort_by=sort_by
181
+ ),
182
+ "videos",
183
+ )
184
+
185
+ def list_channel_playlists(
186
+ self, channel_id: str, *, cursor: str | None = None
187
+ ) -> ChannelPlaylistsPage:
188
+ """One page of the channel's playlists. 1 credit per page."""
189
+ return self._request(
190
+ "GET",
191
+ f"/v1/channels/{_seg(channel_id)}/playlists",
192
+ query={"cursor": cursor},
193
+ )
194
+
195
+ def iter_channel_playlists(self, channel_id: str) -> Iterator[ChannelPlaylist]:
196
+ yield from _pages(
197
+ lambda cursor: self.list_channel_playlists(channel_id, cursor=cursor),
198
+ "playlists",
199
+ )
200
+
201
+ def search(
202
+ self,
203
+ query: str,
204
+ *,
205
+ type: SearchType | None = None,
206
+ limit: int | None = None,
207
+ cursor: str | None = None,
208
+ upload_date: UploadDate | None = None,
209
+ duration: DurationFilter | None = None,
210
+ sort_by: SearchSort | None = None,
211
+ ) -> SearchPage:
212
+ """One page of search results. 1 credit per page."""
213
+ return self._request(
214
+ "GET",
215
+ "/v1/search",
216
+ query={
217
+ "q": query,
218
+ "type": type,
219
+ "limit": limit,
220
+ "cursor": cursor,
221
+ "upload_date": upload_date,
222
+ "duration": duration,
223
+ "sort_by": sort_by,
224
+ },
225
+ )
226
+
227
+ def iter_search(
228
+ self,
229
+ query: str,
230
+ *,
231
+ type: SearchType | None = None,
232
+ limit: int | None = None,
233
+ upload_date: UploadDate | None = None,
234
+ duration: DurationFilter | None = None,
235
+ sort_by: SearchSort | None = None,
236
+ ) -> Iterator[SearchItem]:
237
+ """Every search hit, following ``next_cursor``."""
238
+
239
+ def page(cursor: str | None) -> SearchPage:
240
+ return self.search(
241
+ query,
242
+ type=type,
243
+ limit=limit,
244
+ cursor=cursor,
245
+ upload_date=upload_date,
246
+ duration=duration,
247
+ sort_by=sort_by,
248
+ )
249
+
250
+ yield from _pages(page, "items")
251
+
252
+ def get_suggestions(self, query: str) -> Suggestions:
253
+ """Autocomplete strings. Costs 0 credits."""
254
+ return self._request("GET", "/v1/search/suggestions", query={"q": query})
255
+
256
+ def create_batch(
257
+ self, tasks: Sequence[BatchTask], *, concurrency: int | None = None
258
+ ) -> BatchSubmit:
259
+ """Start a batch of up to 100 tasks. Returns the job id; poll it with ``poll_batch``."""
260
+ body: dict[str, Any] = {"tasks": [dict(task) for task in tasks]}
261
+ if concurrency is not None:
262
+ body["concurrency"] = concurrency
263
+ # A 5xx or a dropped connection can come after the job was created, so
264
+ # a retry could start a second batch. Only 429 (nothing was created)
265
+ # is retried here.
266
+ return self._request("POST", "/v1/batch", json_body=body, retry_server_errors=False)
267
+
268
+ def get_batch(self, job_id: str) -> BatchJob:
269
+ """Status of a batch job. Free."""
270
+ return self._request("GET", f"/v1/batch/{_seg(job_id)}")
271
+
272
+ def poll_batch(
273
+ self, job_id: str, *, interval: float = 1, timeout: float = 120
274
+ ) -> BatchJob:
275
+ """Poll until status is ``completed`` or ``failed``, or ``timeout`` seconds pass."""
276
+ deadline = self._monotonic() + timeout
277
+ while True:
278
+ job = self.get_batch(job_id)
279
+ if job.get("status") in ("completed", "failed"):
280
+ return job
281
+ if self._monotonic() >= deadline:
282
+ raise TimeoutError(
283
+ f"Batch {job_id} still {job.get('status')!r} after {timeout} seconds."
284
+ )
285
+ self._sleep(interval)
286
+
287
+ def _request(
288
+ self,
289
+ method: str,
290
+ path: str,
291
+ *,
292
+ query: Mapping[str, Any] | None = None,
293
+ json_body: Mapping[str, Any] | None = None,
294
+ as_text: bool = False,
295
+ retry_server_errors: bool = True,
296
+ ) -> Any:
297
+ url = self.base_url + path
298
+ if query:
299
+ pairs = [(key, value) for key, value in query.items() if value is not None]
300
+ if pairs:
301
+ url = url + "?" + urllib.parse.urlencode(pairs)
302
+ data = None if json_body is None else json.dumps(json_body).encode()
303
+ headers = {
304
+ "Authorization": f"Bearer {self.api_key}",
305
+ "Accept": "application/json, text/plain, text/vtt, text/markdown",
306
+ "User-Agent": _USER_AGENT,
307
+ }
308
+ if data is not None:
309
+ headers["Content-Type"] = "application/json"
310
+
311
+ attempt = 0
312
+ while True:
313
+ request = urllib.request.Request(url, data=data, headers=headers, method=method)
314
+ try:
315
+ with urllib.request.urlopen(request, timeout=self.timeout) as response:
316
+ status = response.status
317
+ raw = response.read()
318
+ header_map = {key.lower(): value for key, value in response.headers.items()}
319
+ except urllib.error.HTTPError as exc:
320
+ status = exc.code
321
+ raw = exc.read()
322
+ header_map = {key.lower(): value for key, value in exc.headers.items()}
323
+ except (urllib.error.URLError, TimeoutError, ConnectionError, http.client.HTTPException) as exc:
324
+ reason = exc.reason if isinstance(exc, urllib.error.URLError) else exc
325
+ error = YTAPIError(f"Request failed: {reason}", status=0, retryable=True)
326
+ if attempt >= self.max_retries or not retry_server_errors:
327
+ raise error from exc
328
+ self._sleep(self._backoff_delay(attempt))
329
+ attempt += 1
330
+ continue
331
+
332
+ if status in (200, 202):
333
+ if as_text:
334
+ return raw.decode("utf-8")
335
+ if not raw:
336
+ return {}
337
+ try:
338
+ return json.loads(raw)
339
+ except json.JSONDecodeError as exc:
340
+ raise YTAPIError(
341
+ f"Expected JSON from {method} {path}, got: {raw[:200]!r}",
342
+ status=status,
343
+ retryable=False,
344
+ ) from exc
345
+
346
+ error = _error_from(status, header_map, raw)
347
+ if attempt >= self.max_retries or not _should_retry(
348
+ error, retry_server_errors, self.max_retry_wait
349
+ ):
350
+ raise error
351
+ delay = self._backoff_delay(attempt)
352
+ if error.retry_after is not None:
353
+ delay = max(delay, error.retry_after)
354
+ self._sleep(delay)
355
+ attempt += 1
356
+
357
+ def _backoff_delay(self, attempt: int) -> float:
358
+ return min(self.backoff_cap, self.backoff * (2**attempt))
359
+
360
+
361
+ def _seg(value: str) -> str:
362
+ return urllib.parse.quote(value, safe="")
363
+
364
+
365
+ def _should_retry(
366
+ error: YTAPIError, retry_server_errors: bool = True, max_retry_wait: float = 60
367
+ ) -> bool:
368
+ if error.retryable is False:
369
+ return False
370
+ if error.status == 429:
371
+ if error.code == _DAILY_LIMIT_CODE:
372
+ return False
373
+ return error.retry_after is None or error.retry_after <= max_retry_wait
374
+ return retry_server_errors and error.status >= 500
375
+
376
+
377
+ def _error_from(status: int, headers: Mapping[str, str], raw: bytes) -> YTAPIError:
378
+ retry_after = _retry_after(headers.get("retry-after"))
379
+ message = raw.decode("utf-8", "replace")
380
+ code: str | None = None
381
+ retryable: bool | None = None
382
+ try:
383
+ payload = json.loads(raw) if raw else {}
384
+ except json.JSONDecodeError:
385
+ payload = None
386
+ if isinstance(payload, dict):
387
+ err = payload.get("error")
388
+ if isinstance(err, dict):
389
+ code = err.get("code") if isinstance(err.get("code"), str) else None
390
+ if isinstance(err.get("message"), str):
391
+ message = err["message"]
392
+ if isinstance(err.get("retryable"), bool):
393
+ retryable = err["retryable"]
394
+ kind = _ERROR_TYPES.get(status, ServerError if status >= 500 else YTAPIError)
395
+ return kind(
396
+ message, status=status, code=code, retryable=retryable, retry_after=retry_after
397
+ )
398
+
399
+
400
+ def _retry_after(value: str | None) -> float | None:
401
+ if value is None:
402
+ return None
403
+ try:
404
+ return float(value)
405
+ except ValueError:
406
+ return None
407
+
408
+
409
+ def _pages(fetch_page: Callable[[str | None], Mapping[str, Any]], key: str) -> Iterator[Any]:
410
+ cursor: str | None = None
411
+ seen: set[str] = set()
412
+ while True:
413
+ page = fetch_page(cursor)
414
+ items = page.get(key) or []
415
+ yield from items
416
+ next_cursor = page.get("next_cursor")
417
+ # Stop on a repeated cursor rather than loop forever.
418
+ if not page.get("has_more") or not next_cursor or next_cursor in seen:
419
+ return
420
+ seen.add(next_cursor)
421
+ cursor = next_cursor
ytapi/errors.py ADDED
@@ -0,0 +1,50 @@
1
+ """Errors raised by the YTAPI client.
2
+
3
+ The API returns ``{"error": {"code", "message", "retryable"}}``.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+
9
+ class YTAPIError(Exception):
10
+ """Base error. ``status`` is the HTTP status, or 0 for a network error."""
11
+
12
+ def __init__(
13
+ self,
14
+ message: str,
15
+ *,
16
+ status: int,
17
+ code: str | None = None,
18
+ retryable: bool | None = None,
19
+ retry_after: float | None = None,
20
+ ) -> None:
21
+ super().__init__(message)
22
+ self.status = status
23
+ self.code = code
24
+ self.retryable = retryable
25
+ self.retry_after = retry_after
26
+
27
+
28
+ class AuthError(YTAPIError):
29
+ """401. The API key is missing or rejected."""
30
+
31
+
32
+ class InsufficientCreditsError(YTAPIError):
33
+ """402. The credit balance cannot cover the call."""
34
+
35
+
36
+ class NotFoundError(YTAPIError):
37
+ """404. ``code`` is captions_disabled, language_not_found, video_unavailable, or another not-found code."""
38
+
39
+
40
+ class RateLimitedError(YTAPIError):
41
+ """429. ``retry_after`` is the wait the server asked for, in seconds.
42
+
43
+ ``code`` is ``rate_limited`` for a burst over the key's rate (retried
44
+ automatically) or ``daily_limit_exceeded`` when a free account used its
45
+ requests for the day (raised at once; it resets at 00:00 UTC).
46
+ """
47
+
48
+
49
+ class ServerError(YTAPIError):
50
+ """5xx. Retried when ``retryable`` is not explicitly false."""
ytapi/models.py ADDED
@@ -0,0 +1,263 @@
1
+ """Response shapes documented at https://docs.ytapi.dev.
2
+
3
+ Fields are optional in the type because pages after the first omit some of
4
+ them (a playlist page after the first carries videos only). The client
5
+ returns the JSON object as decoded; it does not drop unknown keys.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from typing import Any, Literal, TypedDict
11
+
12
+ TranscriptFormat = Literal[
13
+ "segments",
14
+ "word_timestamps",
15
+ "sentences",
16
+ "markdown",
17
+ "text",
18
+ "srt",
19
+ "vtt",
20
+ "json3",
21
+ ]
22
+ TrackPolicy = Literal["manual_first", "asr_first", "exact_only"]
23
+ SearchType = Literal["video", "channel", "playlist", "shorts", "movie"]
24
+ SortBy = Literal["newest", "popular", "oldest"]
25
+ UploadDate = Literal["hour", "today", "week", "month", "year"]
26
+ DurationFilter = Literal["short", "medium", "long"]
27
+ SearchSort = Literal["relevance", "rating", "upload_date", "view_count"]
28
+ BatchTaskType = Literal["transcript", "basic_info"]
29
+ BatchStatus = Literal["pending", "processing", "completed", "failed"]
30
+
31
+ JSON_FORMATS = frozenset({"segments", "word_timestamps", "sentences", "json3"})
32
+ TEXT_FORMATS = frozenset({"markdown", "text", "srt", "vtt"})
33
+
34
+
35
+ class Thumbnail(TypedDict, total=False):
36
+ url: str
37
+ width: int
38
+ height: int
39
+
40
+
41
+ class Word(TypedDict, total=False):
42
+ word: str
43
+ start: float
44
+ end: float
45
+
46
+
47
+ class Segment(TypedDict, total=False):
48
+ text: str
49
+ start: float
50
+ end: float
51
+ duration: float
52
+ words: list[Word]
53
+
54
+
55
+ class Transcript(TypedDict, total=False):
56
+ video_id: str
57
+ language: str
58
+ track_kind: Literal["manual", "asr"]
59
+ duration_seconds: float
60
+ has_word_level: bool
61
+ segments: list[Segment]
62
+
63
+
64
+ class CaptionLanguage(TypedDict, total=False):
65
+ code: str
66
+ name: str
67
+ kind: str
68
+
69
+
70
+ class BasicChannel(TypedDict, total=False):
71
+ id: str
72
+ title: str
73
+ url: str
74
+
75
+
76
+ class VideoBasicInfo(TypedDict, total=False):
77
+ video_id: str
78
+ title: str
79
+ length_seconds: float
80
+ channel: BasicChannel
81
+ available_languages: list[CaptionLanguage]
82
+
83
+
84
+ class VideoChannel(TypedDict, total=False):
85
+ id: str
86
+ title: str
87
+ url: str
88
+ subscribers: str
89
+ avatar_url: str
90
+
91
+
92
+ class Chapter(TypedDict, total=False):
93
+ title: str
94
+ start_time_seconds: float
95
+ time_description: str
96
+
97
+
98
+ class VideoInfo(TypedDict, total=False):
99
+ video_id: str
100
+ title: str
101
+ description: str
102
+ length_seconds: float
103
+ view_count: int
104
+ like_count: int
105
+ published: int
106
+ keywords: list[str]
107
+ channel: VideoChannel
108
+ thumbnails: list[Thumbnail]
109
+ available_languages: list[CaptionLanguage]
110
+ chapters: list[Chapter]
111
+
112
+
113
+ class PlaylistVideo(TypedDict, total=False):
114
+ video_id: str
115
+ title: str
116
+ index: int
117
+ length_seconds: float
118
+ length_text: str
119
+ author: str
120
+
121
+
122
+ class PlaylistPage(TypedDict, total=False):
123
+ playlist_id: str
124
+ title: str
125
+ video_count: int
126
+ view_count_text: str
127
+ author: str
128
+ thumbnails: list[Thumbnail]
129
+ videos: list[PlaylistVideo]
130
+ has_more: bool
131
+ next_cursor: str | None
132
+
133
+
134
+ class Channel(TypedDict, total=False):
135
+ channel_id: str
136
+ title: str
137
+ handle: str
138
+ description: str
139
+ subscriber_count: int
140
+ subscriber_count_text: str
141
+ custom_url: str
142
+ country: str
143
+ video_count: int
144
+ verified: bool
145
+ thumbnails: list[Thumbnail]
146
+ banners: list[Thumbnail]
147
+ links: list[str]
148
+ available_tabs: list[str]
149
+
150
+
151
+ class ChannelVideo(TypedDict, total=False):
152
+ video_id: str
153
+ title: str
154
+ length_text: str
155
+ view_count_text: str
156
+ published_text: str
157
+ thumbnails: list[Thumbnail]
158
+
159
+
160
+ class ChannelLatest(TypedDict, total=False):
161
+ channel_id: str
162
+ channel_title: str
163
+ latest_video: ChannelVideo
164
+ recent_videos: list[ChannelVideo]
165
+
166
+
167
+ class ChannelVideosPage(TypedDict, total=False):
168
+ channel_id: str
169
+ channel_title: str
170
+ has_more: bool
171
+ next_cursor: str | None
172
+ continuation: str | None
173
+ videos: list[ChannelVideo]
174
+
175
+
176
+ class ChannelPlaylist(TypedDict, total=False):
177
+ playlist_id: str
178
+ title: str
179
+ video_count: int
180
+ video_count_text: str
181
+ thumbnails: list[Thumbnail]
182
+
183
+
184
+ class ChannelPlaylistsPage(TypedDict, total=False):
185
+ playlists: list[ChannelPlaylist]
186
+ has_more: bool
187
+ next_cursor: str | None
188
+
189
+
190
+ class SearchItem(TypedDict, total=False):
191
+ id: str
192
+ type: str
193
+ title: str
194
+ description: str
195
+ author: str
196
+ channel_id: str
197
+ length_seconds: float
198
+ length_text: str
199
+ view_count_text: str
200
+ published_text: str
201
+ thumbnails: list[Thumbnail]
202
+ handle: str
203
+ subscriber_count_text: str
204
+ video_count_text: str
205
+ badges: list[str]
206
+
207
+
208
+ class SearchPage(TypedDict, total=False):
209
+ query: str
210
+ type: str
211
+ has_more: bool
212
+ next_cursor: str | None
213
+ items: list[SearchItem]
214
+
215
+
216
+ class Suggestions(TypedDict, total=False):
217
+ query: str
218
+ suggestions: list[str]
219
+
220
+
221
+ class BatchTask(TypedDict, total=False):
222
+ id: str
223
+ type: BatchTaskType
224
+ video_id: str
225
+ format: TranscriptFormat
226
+ languages: list[str]
227
+ track_policy: TrackPolicy
228
+ word_level: bool
229
+
230
+
231
+ class BatchSubmit(TypedDict, total=False):
232
+ id: str
233
+ status: str
234
+ total: int
235
+ estimated_credits: int
236
+ created_at: str
237
+
238
+
239
+ class BatchTaskError(TypedDict, total=False):
240
+ code: str
241
+ message: str
242
+
243
+
244
+ class BatchTaskResult(TypedDict, total=False):
245
+ id: str
246
+ type: str
247
+ video_id: str
248
+ status: int
249
+ data: Any
250
+ error: BatchTaskError
251
+
252
+
253
+ class BatchJob(TypedDict, total=False):
254
+ id: str
255
+ status: str
256
+ total: int
257
+ successful: int
258
+ failed: int
259
+ credits_deducted: int
260
+ duration_ms: int
261
+ results: list[BatchTaskResult]
262
+ created_at: str
263
+ completed_at: str | None
ytapi/py.typed ADDED
@@ -0,0 +1 @@
1
+ # Marker file for PEP 561. This package ships inline type hints.
@@ -0,0 +1,145 @@
1
+ Metadata-Version: 2.4
2
+ Name: ytapi-sdk
3
+ Version: 0.1.0
4
+ Summary: Python client for YTAPI: YouTube transcripts, video details, search, channels and playlists.
5
+ Author: YTAPI
6
+ License-Expression: MIT
7
+ Project-URL: Documentation, https://docs.ytapi.dev
8
+ Project-URL: Homepage, https://ytapi.dev
9
+ Project-URL: Repository, https://github.com/ytapi/ytapi-python
10
+ Project-URL: Issues, https://github.com/ytapi/ytapi-python/issues
11
+ Keywords: youtube,transcript,captions,subtitles,youtube-transcript,ytapi
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Typing :: Typed
15
+ Classifier: Topic :: Multimedia :: Video
16
+ Requires-Python: >=3.10
17
+ Description-Content-Type: text/markdown
18
+ License-File: LICENSE
19
+ Dynamic: license-file
20
+
21
+ # YTAPI Python client
22
+
23
+ Python client for [YTAPI](https://ytapi.dev?utm_source=github): YouTube transcripts, video details, search, channels and playlists over one HTTP API. It works from servers and cloud functions, where fetching YouTube directly tends to get blocked.
24
+
25
+ - No dependencies beyond the standard library. Python 3.10+.
26
+ - Typed responses (`TypedDict`), typed errors, automatic retries and pagination.
27
+ - Reference: [docs.ytapi.dev](https://docs.ytapi.dev).
28
+
29
+ ## Install
30
+
31
+ ```bash
32
+ pip install ytapi-sdk
33
+ ```
34
+
35
+ The package is `ytapi-sdk` on PyPI, and you import it as `ytapi`.
36
+
37
+ ## Quickstart
38
+
39
+ Get a key at [ytapi.dev](https://ytapi.dev/app/api-keys?utm_source=github). New accounts get 200 free credits, and no card is needed.
40
+
41
+ ```python
42
+ from ytapi import YTAPI
43
+
44
+ api = YTAPI() # reads YTAPI_API_KEY (or YTAPI_KEY) from the environment
45
+ transcript = api.get_transcript("dQw4w9WgXcQ")
46
+ for segment in transcript["segments"][:3]:
47
+ print(segment["start"], segment["text"])
48
+ ```
49
+
50
+ By default you get the captions in the video's own language, as timed segments. A successful request uses 1 credit, and errors are free.
51
+
52
+ ## Examples
53
+
54
+ ```python
55
+ # Other formats. markdown, text, srt and vtt come back as a string.
56
+ srt = api.get_transcript("dQw4w9WgXcQ", format="srt")
57
+ spanish = api.get_transcript("dQw4w9WgXcQ", format="text", languages=["es", "*"])
58
+ words = api.get_transcript("dQw4w9WgXcQ", format="word_timestamps", word_level=True)
59
+
60
+ # Free: title, length, channel and the caption languages a video has.
61
+ basic = api.get_basic_info("dQw4w9WgXcQ")
62
+ # 1 credit: description, counts, chapters and more.
63
+ info = api.get_video_info("dQw4w9WgXcQ")
64
+
65
+ # Channels take an @handle, a channel ID (UC...) or a URL.
66
+ channel = api.get_channel("@3blue1brown")
67
+ for video in api.iter_channel_videos("@3blue1brown", sort_by="popular"):
68
+ print(video["video_id"], video["title"])
69
+
70
+ # Playlists, page by page or as an iterator.
71
+ for video in api.iter_playlist_videos("PLZHQObOWTQDNU6R1_67000Dx_ZCJB-3pi"):
72
+ print(video["video_id"], video["length_text"])
73
+
74
+ # Search: type is video, channel, playlist, shorts or movie.
75
+ page = api.search("rust async", type="video", upload_date="month", limit=10)
76
+ for hit in page["items"]:
77
+ print(hit["title"])
78
+
79
+ # Search suggestions are free.
80
+ print(api.get_suggestions("nextjs")["suggestions"])
81
+
82
+ # Batch: up to 100 transcript or basic_info tasks per job.
83
+ job = api.create_batch(
84
+ [
85
+ {"id": "a", "type": "transcript", "video_id": "dQw4w9WgXcQ", "format": "text"},
86
+ {"id": "b", "type": "basic_info", "video_id": "jNQXAC9IVRw"},
87
+ ]
88
+ )
89
+ done = api.poll_batch(job["id"], timeout=120)
90
+ print(done["successful"], done["credits_deducted"])
91
+ ```
92
+
93
+ The iterators (`iter_playlist_videos`, `iter_channel_videos`, `iter_channel_playlists`, `iter_search`) follow `next_cursor` for you. Each page is a request and uses a credit. In a batch, each successful task uses 1 credit and failed tasks are free.
94
+
95
+ ## Errors
96
+
97
+ ```python
98
+ from ytapi import InsufficientCreditsError, NotFoundError, RateLimitedError, YTAPIError
99
+
100
+ try:
101
+ api.get_transcript("xxxxxxxxxxx")
102
+ except NotFoundError as exc:
103
+ print(exc.code) # captions_disabled, language_not_found, video_unavailable, ...
104
+ except RateLimitedError as exc:
105
+ print(exc.code, exc.retry_after) # rate_limited or daily_limit_exceeded
106
+ except InsufficientCreditsError:
107
+ print("Out of credits: https://ytapi.dev/#pricing")
108
+ except YTAPIError as exc:
109
+ print(exc.status, exc.code, exc) # status 0 means a network error
110
+ ```
111
+
112
+ | Status | Exception |
113
+ | --- | --- |
114
+ | 401 | `AuthError` |
115
+ | 402 | `InsufficientCreditsError` |
116
+ | 404 | `NotFoundError` |
117
+ | 429 | `RateLimitedError` |
118
+ | 5xx | `ServerError` |
119
+ | network error | `YTAPIError` with `status` 0 |
120
+ | other | `YTAPIError` |
121
+
122
+ ## Retries
123
+
124
+ The client retries a 429, a 5xx or a network error up to `max_retries` times (default 2). It backs off from 0.5 seconds, doubling up to 8, and waits longer when the server sends `Retry-After`. A few cases are not retried:
125
+
126
+ - **A 429 that asks for a long wait.** The cutoff is `max_retry_wait`, default 60 seconds. This includes a free account's daily limit (`daily_limit_exceeded`), which lasts until 00:00 UTC. The client raises these right away instead of hanging your program.
127
+ - **Creating a batch after a 5xx or a network error.** The job may already exist, so a retry could start a second one.
128
+
129
+ Use `YTAPI(max_retries=0)` to turn retries off.
130
+
131
+ ## Releases
132
+
133
+ Each GitHub release publishes the matching version to [PyPI](https://pypi.org/project/ytapi-sdk/) through trusted publishing. The release tag must match the version in `pyproject.toml`, such as `v0.1.0`.
134
+
135
+ ## Tests
136
+
137
+ ```bash
138
+ PYTHONPATH=src python3 -m unittest discover -s tests
139
+ ```
140
+
141
+ The tests mock HTTP and need no network or API key.
142
+
143
+ ## License
144
+
145
+ MIT
@@ -0,0 +1,10 @@
1
+ ytapi/__init__.py,sha256=6QS4chpaOTJxqIWBezXjM-f6VexoxBOakF9qJ_N16xw,418
2
+ ytapi/client.py,sha256=28DejOFQmHGSaoCeU01PUTHENISkmUyu2sOlbM2ldno,15118
3
+ ytapi/errors.py,sha256=afuYpEqwC64ZnwdwmRLTOonIcIKP_Almx3zBxwqyoaU,1402
4
+ ytapi/models.py,sha256=vVy6DP3IgF_wD04pNit63Z0WUCfBLv3mQq57fYwIdrs,5611
5
+ ytapi/py.typed,sha256=lgCyp9gZfAMplkwv75pxHXKdO1FqRCF61SzGRi14E-M,65
6
+ ytapi_sdk-0.1.0.dist-info/licenses/LICENSE,sha256=mz8MPcnKcM-hIdd8qsDd8DZKwF7X_WOvTGJlz7nOHjI,1062
7
+ ytapi_sdk-0.1.0.dist-info/METADATA,sha256=cVh0N6m5kvqRYw-oTXtOF1cY38zfodv6ekoqGP3Q1sU,5514
8
+ ytapi_sdk-0.1.0.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
9
+ ytapi_sdk-0.1.0.dist-info/top_level.txt,sha256=ZnFvZDGQEUJ-jRMFP36VnigUI7CYDGl-L_6WqBC0kkI,6
10
+ ytapi_sdk-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 YTAPI
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ ytapi