### Run Example Script from Repository Source: https://github.com/davidteather/tiktok-api/blob/main/README.md Execute example scripts directly from the repository root using the python -m command. This is a convenient way to test specific functionalities. ```sh python -m examples.trending_example ``` -------------------------------- ### Install TikTokApi and Playwright Source: https://github.com/davidteather/tiktok-api/blob/main/README.md Use pip to install the TikTokApi package and then run the Playwright command to install necessary browser binaries. Ensure you have Python 3.9+ installed. ```sh pip install TikTokApi python -m playwright install ``` -------------------------------- ### TikTokApi Session Initialization Source: https://context7.com/davidteather/tiktok-api/llms.txt Demonstrates how to initialize TikTokApi sessions, including single and multi-session setups with various configuration options. ```APIDOC ## TikTokApi.create_sessions() ### Description Initializes one or more Playwright browser sessions for interacting with TikTok. This involves navigating to TikTok, obtaining or injecting an `msToken` cookie, and registering each browser context as a session. All subsequent API calls will be routed through these established sessions. ### Method `await api.create_sessions()` ### Parameters - `num_sessions` (int) - The number of sessions to create. - `ms_tokens` (list[str]) - A list of `msToken` values harvested from TikTok.com browser cookies. - `sleep_after` (int, optional) - Seconds to wait for `msToken` generation. Defaults to 3. - `headless` (bool, optional) - Whether to run browsers in headless mode. Defaults to True. - `browser` (str, optional) - The browser to use ('chromium', 'firefox', or 'webkit'). Defaults to 'chromium'. - `allow_partial_sessions` (bool, optional) - If True, the operation will not fail if some sessions encounter errors. - `min_sessions` (int, optional) - The minimum number of healthy sessions required. - `enable_session_recovery` (bool, optional) - Enables automatic recovery of dead sessions. - `suppress_resource_load_types` (list[str], optional) - Resource types to suppress during loading (e.g., 'image', 'media', 'font') for faster loading. - `timeout` (int, optional) - Timeout in milliseconds for session creation. ### Request Example ```python from TikTokApi import TikTokApi import asyncio import os ms_token = os.environ.get("ms_token") # from tiktok.com browser cookies async def main(): async with TikTokApi() as api: # Basic single session await api.create_sessions( num_sessions=1, ms_tokens=[ms_token], sleep_after=3, headless=True, browser="chromium", ) # Multi-session with partial-failure tolerance await api.create_sessions( num_sessions=5, ms_tokens=[ms_token], allow_partial_sessions=True, min_sessions=2, enable_session_recovery=True, suppress_resource_load_types=["image", "media", "font"], timeout=30000, ) stats = api.get_resource_stats() print(stats) health = await api.health_check() print(health) asyncio.run(main()) ``` ### Response #### Success Response `api.get_resource_stats()` returns a dictionary with session statistics. `await api.health_check()` returns per-session validity details. ``` -------------------------------- ### Docker Installation for TikTokApi Source: https://github.com/davidteather/tiktok-api/blob/main/README.md Steps to build and run a Docker image for TikTokApi. This involves pulling a Playwright image, building your Dockerfile, and running a script within the container. ```sh docker pull mcr.microsoft.com/playwright:focal docker build . -t tiktokapi:latest docker run -v TikTokApi --rm tiktokapi:latest python3 your_script.py ``` -------------------------------- ### Get User Profile Info Source: https://context7.com/davidteather/tiktok-api/llms.txt Fetches a user's full profile metadata. Requires ms_tokens for session creation. The User object is populated after calling .info(). ```python from TikTokApi import TikTokApi import asyncio, os async def get_user_info(): async with TikTokApi() as api: await api.create_sessions(ms_tokens=[os.environ.get("ms_token")], num_sessions=1, sleep_after=3) user = api.user(username="therock") user_data = await user.info() # After .info(), the User object is populated: print(user.user_id) # e.g. "6955468384719831046" print(user.sec_uid) # long sec_uid string print(user.username) # "therock" # Raw response contains follower counts, bio, avatar, etc. info = user_data.get("userInfo", {}) print(f"Followers: {info['stats']['followerCount']}") print(f"Bio: {info['user']['signature']}") asyncio.run(get_user_info()) ``` -------------------------------- ### Get User Playlists Source: https://context7.com/davidteather/tiktok-api/llms.txt Yields Playlist objects representing public playlists created by the user. Requires ms_tokens for session creation. Specify the number of playlists to retrieve with the 'count' parameter. ```python from TikTokApi import TikTokApi import asyncio, os async def get_user_playlists(): async with TikTokApi() as api: await api.create_sessions(ms_tokens=[os.environ.get("ms_token")], num_sessions=1, sleep_after=3) user = api.user("therock") async for playlist in user.playlists(count=5): print(f"Playlist: {playlist.name}, Videos: {playlist.video_count}") print(f"Cover URL: {playlist.cover_url}") asyncio.run(get_user_playlists()) ``` -------------------------------- ### Get User Videos Source: https://context7.com/davidteather/tiktok-api/llms.txt An async generator yielding Video objects from a user's public post feed. Requires ms_tokens for session creation. Specify the number of videos to retrieve with the 'count' parameter. ```python from TikTokApi import TikTokApi import asyncio, os async def get_user_videos(): async with TikTokApi() as api: await api.create_sessions(ms_tokens=[os.environ.get("ms_token")], num_sessions=1, sleep_after=3) async for video in api.user(username="davidteathercodes").videos(count=30): print(f"Video ID: {video.id}") print(f"Created: {video.create_time}") print(f"Stats: {video.stats}") # {"playCount": ..., "commentCount": ...} print(f"Hashtags: {[h.name for h in video.hashtags]}") asyncio.run(get_user_videos()) ``` -------------------------------- ### Low-Level Request API Source: https://context7.com/davidteather/tiktok-api/llms.txt `api.make_request()` allows sending signed, session-authenticated GET requests to any TikTok internal API endpoint. It automatically merges session parameters and `msToken`, and signs the URL with `X-Bogus`. The example demonstrates making a user detail request. ```APIDOC ## Low-Level Request API `api.make_request()` sends a signed, session-authenticated GET request to any TikTok internal API endpoint. Session params and `msToken` are merged automatically; the URL is signed with `X-Bogus`. ```python from TikTokApi import TikTokApi import asyncio, os async def raw_request(): async with TikTokApi() as api: await api.create_sessions(ms_tokens=[os.environ.get("ms_token")], num_sessions=1, sleep_after=3) # Manually call any TikTok internal endpoint resp = await api.make_request( url="https://www.tiktok.com/api/user/detail/", params={"uniqueId": "tiktok", "secUid": ""}, retries=3, exponential_backoff=True, # waits 2^n seconds between retries ) print(resp.get("userInfo", {}).get("user", {}).get("uniqueId")) asyncio.run(raw_request()) ``` ``` -------------------------------- ### Get Sound Info and Videos - TikTok API Source: https://context7.com/davidteather/tiktok-api/llms.txt Retrieves sound metadata using `.info()` and yields videos that use the sound using `.videos()`. Requires the sound ID. ```python from TikTokApi import TikTokApi import asyncio, os async def sound_example(): async with TikTokApi() as api: await api.create_sessions(ms_tokens=[os.environ.get("ms_token")], num_sessions=1, sleep_after=3) sound = api.sound(id="7016547803243022337") sound_data = await sound.info() print(f"Title: {sound.title}") print(f"Duration: {sound.duration}s") print(f"Original: {sound.original}") print(f"Author: {sound.author}") async for video in sound.videos(count=30): print(f"Uses this sound: {video.id}") asyncio.run(sound_example()) ``` -------------------------------- ### Exception Handling Source: https://context7.com/davidteather/tiktok-api/llms.txt All exceptions in the TikTokApi library inherit from `TikTokException` and provide `.error_code`, `.raw_response`, and `.message` attributes. The example shows how to catch specific exceptions like `EmptyResponseException`, `NotFoundException`, `InvalidResponseException`, and `CaptchaException`. ```APIDOC ## Exception Handling All exceptions inherit from `TikTokException` and carry `.error_code`, `.raw_response`, and `.message` attributes. ```python from TikTokApi import TikTokApi from TikTokApi.exceptions import ( EmptyResponseException, # TikTok detected a bot; try proxy or headless=False InvalidResponseException, # unexpected response structure InvalidJSONException, # response could not be parsed as JSON NotFoundException, # resource does not exist CaptchaException, # TikTok is showing a CAPTCHA ) import asyncio, os async def with_error_handling(): async with TikTokApi() as api: await api.create_sessions(ms_tokens=[os.environ.get("ms_token")], num_sessions=1, sleep_after=3) try: user_data = await api.user(username="nonexistent_user_xyz123").info() except EmptyResponseException as e: print(f"Bot detected: {e.message} — consider using a proxy") except NotFoundException as e: print(f"User not found: {e}") except InvalidResponseException as e: print(f"Unexpected TikTok response (code {e.error_code}): {e.message}") except CaptchaException as e: print(f"CAPTCHA encountered: {e}") asyncio.run(with_error_handling()) ``` ``` -------------------------------- ### Initialize TikTokApi Sessions Source: https://context7.com/davidteather/tiktok-api/llms.txt Initializes one or more Playwright browser sessions for the TikTokApi. Requires an msToken harvested from browser cookies. Supports various configurations for session management, including multi-session setups with partial failure tolerance and session recovery. ```python from TikTokApi import TikTokApi import asyncio import os ms_token = os.environ.get("ms_token") # from tiktok.com browser cookies async def main(): async with TikTokApi() as api: # Basic single session await api.create_sessions( num_sessions=1, ms_tokens=[ms_token], sleep_after=3, # seconds to wait for msToken generation headless=True, browser="chromium", # "chromium" | "firefox" | "webkit" ) # Multi-session with partial-failure tolerance await api.create_sessions( num_sessions=5, ms_tokens=[ms_token], allow_partial_sessions=True, # don't fail if some sessions error min_sessions=2, # require at least 2 healthy sessions enable_session_recovery=True, # auto-recover dead sessions suppress_resource_load_types=["image", "media", "font"], # faster loading timeout=30000, ) stats = api.get_resource_stats() # { # "total_sessions": 5, "valid_sessions": 5, "invalid_sessions": 0, # "has_browser": True, "has_playwright": True, "cleanup_called": False, # "auto_cleanup_enabled": True, "recovery_enabled": True # } print(stats) health = await api.health_check() # Actively validates each session; returns per-session validity details print(health) asyncio.run(main()) ``` -------------------------------- ### Get Hashtag Info and Videos - TikTok API Source: https://context7.com/davidteather/tiktok-api/llms.txt Fetches hashtag metadata using `.info()` and yields videos tagged with the hashtag using `.videos()`. Requires the hashtag name. ```python from TikTokApi import TikTokApi import asyncio, os async def hashtag_example(): async with TikTokApi() as api: await api.create_sessions(ms_tokens=[os.environ.get("ms_token")], num_sessions=1, sleep_after=3) tag = api.hashtag(name="funny") tag_data = await tag.info() print(f"Hashtag ID: {tag.id}") print(f"Stats: {tag.stats}") # {"videoCount": ..., "viewCount": ...} async for video in tag.videos(count=30): print(f"Video: {video.id}, Author: @{video.author.username}") print(f"Hashtags in video: {[h.name for h in video.hashtags]}") asyncio.run(hashtag_example()) ``` -------------------------------- ### Get Playlist Info and Videos - TikTok API Source: https://context7.com/davidteather/tiktok-api/llms.txt Fetches playlist metadata using `.info()` and yields `Video` objects within the playlist using `.videos()`. Requires the playlist ID. ```python from TikTokApi import TikTokApi import asyncio, os async def playlist_example(): async with TikTokApi() as api: await api.create_sessions(ms_tokens=[os.environ.get("ms_token")], num_sessions=1, sleep_after=3) playlist = api.playlist(id="7426714779919797038") await playlist.info() print(f"Name: {playlist.name}") print(f"Video count: {playlist.video_count}") print(f"Creator: {playlist.creator}") print(f"Cover: {playlist.cover_url}") async for video in playlist.videos(count=10): print(f" Video: {video.id}") asyncio.run(playlist_example()) ``` -------------------------------- ### Get Related Videos - TikTok API Source: https://context7.com/davidteather/tiktok-api/llms.txt Retrieves videos algorithmically related to a given video ID. This function yields `Video` objects. ```python from TikTokApi import TikTokApi import asyncio, os async def get_related(): async with TikTokApi() as api: await api.create_sessions(ms_tokens=[os.environ.get("ms_token")], num_sessions=1, sleep_after=3) video = api.video(url="https://www.tiktok.com/@davidteathercodes/video/7074717081563942186") async for related in video.related_videos(count=10): print(f"Related: {related.id} by @{related.author.username}") asyncio.run(get_related()) ``` -------------------------------- ### Make Low-Level Signed Request to TikTok API Source: https://context7.com/davidteather/tiktok-api/llms.txt Use `api.make_request` for signed, session-authenticated GET requests to internal TikTok endpoints. The URL is signed with X-Bogus, and session parameters/msToken are merged automatically. Configure retries and exponential backoff for robustness. ```python from TikTokApi import TikTokApi import asyncio, os async def raw_request(): async with TikTokApi() as api: await api.create_sessions(ms_tokens=[os.environ.get("ms_token")], num_sessions=1, sleep_after=3) # Manually call any TikTok internal endpoint resp = await api.make_request( url="https://www.tiktok.com/api/user/detail/", params={"uniqueId": "tiktok", "secUid": ""}, retries=3, exponential_backoff=True, # waits 2^n seconds between retries ) print(resp.get("userInfo", {}).get("user", {}).get("uniqueId")) asyncio.run(raw_request()) ``` -------------------------------- ### Get User Liked Videos Source: https://context7.com/davidteather/tiktok-api/llms.txt Yields videos a user has publicly liked. Raises InvalidResponseException if the user's likes are private. Requires ms_tokens for session creation. Specify the number of liked videos to retrieve with the 'count' parameter. ```python from TikTokApi import TikTokApi from TikTokApi.exceptions import InvalidResponseException import asyncio, os async def get_liked_videos(): async with TikTokApi() as api: await api.create_sessions(ms_tokens=[os.environ.get("ms_token")], num_sessions=1, sleep_after=3) try: async for video in api.user(username="davidteathercodes").liked(count=20): print(video.id) except InvalidResponseException as e: print(f"Likes are private or unavailable: {e}") asyncio.run(get_liked_videos()) ``` -------------------------------- ### Get Video Info Source: https://context7.com/davidteather/tiktok-api/llms.txt Retrieves full video metadata by parsing TikTok's HTML page. This method is slower than API calls and should be used sparingly. Accepts either a direct URL or a numeric ID. Requires ms_tokens for session creation. ```python from TikTokApi import TikTokApi import asyncio, os async def get_video_info(): async with TikTokApi() as api: await api.create_sessions(ms_tokens=[os.environ.get("ms_token")], num_sessions=1, sleep_after=3) # Initialize by URL (auto-extracts ID) video = api.video(url="https://www.tiktok.com/@davidteathercodes/video/7106686413101468970") info = await video.info() # HTTP request to TikTok page — use sparingly print(f"ID: {video.id}") print(f"Author: {video.author.username}") print(f"Stats: {video.stats}") print(f"Sound: {video.sound.title}") # Initialize directly by ID (no HTTP request needed for .bytes()) video2 = api.video(id="7041997751718137094") asyncio.run(get_video_info()) ``` -------------------------------- ### Proxy Support with Custom Algorithm Source: https://context7.com/davidteather/tiktok-api/llms.txt Demonstrates using a `ProxyProvider` with a custom selection algorithm (`USPreferredAlgorithm`) for session creation. Ensures proxies are rotated automatically. ```python from TikTokApi import TikTokApi from proxyproviders import Webshare from proxyproviders.algorithms import RoundRobin, Random from proxyproviders.models.proxy import Proxy from typing import List import asyncio, os class USPreferredAlgorithm: def select(self, proxies: List[Proxy]) -> Proxy: us_proxies = [p for p in proxies if p.country_code == "US"] return us_proxies[0] if us_proxies else proxies[0] async def with_proxies(): provider = Webshare(api_key=os.environ.get("WEBSHARE_API_KEY")) async with TikTokApi() as api: await api.create_sessions( num_sessions=5, proxy_provider=provider, proxy_algorithm=USPreferredAlgorithm(), # custom selection ms_tokens=[os.environ.get("ms_token")], allow_partial_sessions=True, min_sessions=2, ) async for video in api.trending.videos(count=10): print(video.id) asyncio.run(with_proxies()) ``` -------------------------------- ### Sound Info and Videos Source: https://context7.com/davidteather/tiktok-api/llms.txt `api.sound(id=...).info()` retrieves music/sound metadata; `.videos()` yields videos that use that sound. ```APIDOC ## Sound — Info and Videos `api.sound(id=...).info()` retrieves music/sound metadata; `.videos()` yields videos that use that sound. ```python from TikTokApi import TikTokApi import asyncio, os async def sound_example(): async with TikTokApi() as api: await api.create_sessions(ms_tokens=[os.environ.get("ms_token")], num_sessions=1, sleep_after=3) sound = api.sound(id="7016547803243022337") sound_data = await sound.info() print(f"Title: {sound.title}") print(f"Duration: {sound.duration}s") print(f"Original: {sound.original}") print(f"Author: {sound.author}") async for video in sound.videos(count=30): print(f"Uses this sound: {video.id}") asyncio.run(sound_example()) ``` ``` -------------------------------- ### Custom Browser/Page Factories Source: https://context7.com/davidteather/tiktok-api/llms.txt Illustrates using `browser_context_factory` and `page_factory` to gain full control over browser launch, enabling actions like injecting cookies or solving CAPTCHAs before session establishment. ```python from TikTokApi import TikTokApi from playwright.async_api import async_playwright import asyncio, os async def custom_context_factory(playwright): browser = await playwright.chromium.launch(headless=True) context = await browser.new_context() # inject cookies, solve captcha, perform login, etc. await context.add_cookies([{"name": "sessionid", "value": "...", "domain": ".tiktok.com", "path": "/"}]) return context async def custom_page_factory(context): page = await context.new_page() await page.goto("https://www.tiktok.com") # perform any pre-session actions here return page async def main(): async with TikTokApi() as api: await api.create_sessions( num_sessions=1, ms_tokens=[os.environ.get("ms_token")], browser_context_factory=custom_context_factory, page_factory=custom_page_factory, ) async for video in api.trending.videos(count=5): print(video.id) asyncio.run(main()) ``` -------------------------------- ### Hashtag Info and Videos Source: https://context7.com/davidteather/tiktok-api/llms.txt `api.hashtag(name=...).info()` fetches challenge/hashtag metadata; `.videos()` yields videos tagged with that hashtag. ```APIDOC ## Hashtag — Info and Videos `api.hashtag(name=...).info()` fetches challenge/hashtag metadata; `.videos()` yields videos tagged with that hashtag. ```python from TikTokApi import TikTokApi import asyncio, os async def hashtag_example(): async with TikTokApi() as api: await api.create_sessions(ms_tokens=[os.environ.get("ms_token")], num_sessions=1, sleep_after=3) tag = api.hashtag(name="funny") tag_data = await tag.info() print(f"Hashtag ID: {tag.id}") print(f"Stats: {tag.stats}") # {"videoCount": ..., "viewCount": ...} async for video in tag.videos(count=30): print(f"Video: {video.id}, Author: @{video.author.username}") print(f"Hashtags in video: {[h.name for h in video.hashtags]}") asyncio.run(hashtag_example()) ``` ``` -------------------------------- ### Playlist Info and Videos Source: https://context7.com/davidteather/tiktok-api/llms.txt `api.playlist(id=...).info()` fetches playlist metadata; `.videos()` yields `Video` objects in the playlist. ```APIDOC ## Playlist — Info and Videos `api.playlist(id=...).info()` fetches playlist metadata; `.videos()` yields `Video` objects in the playlist. ```python from TikTokApi import TikTokApi import asyncio, os async def playlist_example(): async with TikTokApi() as api: await api.create_sessions(ms_tokens=[os.environ.get("ms_token")], num_sessions=1, sleep_after=3) playlist = api.playlist(id="7426714779919797038") await playlist.info() print(f"Name: {playlist.name}") print(f"Video count: {playlist.video_count}") print(f"Creator: {playlist.creator}") print(f"Cover: {playlist.cover_url}") async for video in playlist.videos(count=10): print(f" Video: {video.id}") asyncio.run(playlist_example()) ``` ``` -------------------------------- ### User Videos Source: https://context7.com/davidteather/tiktok-api/llms.txt `api.user(username).videos()` is an async generator yielding `Video` objects from a user's public post feed. ```APIDOC ## User — Videos `api.user(username).videos()` is an async generator yielding `Video` objects from a user's public post feed. ### Description Retrieves a list of videos posted by a specific TikTok user. ### Method `api.user(username).videos(count)` ### Parameters - **username** (string) - Required - The username of the TikTok user. - **count** (integer) - Optional - The number of videos to retrieve. Defaults to a reasonable amount if not specified. ### Response Example Yields `Video` objects, each containing: ```json { "id": "video_id_string", "create_time": "timestamp", "stats": { "playCount": 1000000, "commentCount": 1000, "shareCount": 100, "diggCount": 5000 }, "hashtags": [ {"name": "hashtag1"}, {"name": "hashtag2"} ] } ``` ``` -------------------------------- ### Video Bytes Download Source: https://context7.com/davidteather/tiktok-api/llms.txt `video.bytes()` downloads raw video bytes. Pass `stream=True` to receive an async iterator of chunks instead of loading the whole file into memory. ```APIDOC ## Video — Download Bytes `video.bytes()` downloads raw video bytes. Pass `stream=True` to receive an async iterator of chunks instead of loading the whole file into memory. ```python from TikTokApi import TikTokApi import asyncio, os async def download_video(): async with TikTokApi() as api: await api.create_sessions(ms_tokens=[os.environ.get("ms_token")], num_sessions=1, sleep_after=3) video = api.video(url="https://www.tiktok.com/@davidteathercodes/video/7074717081563942186") await video.info() # must call info() first to populate downloadAddr # Download full file data = await video.bytes() with open("video.mp4", "wb") as f: f.write(data) # Streaming download async for chunk in await video.bytes(stream=True): # process or forward chunk pass asyncio.run(download_video()) ``` ``` -------------------------------- ### User Playlists Source: https://context7.com/davidteather/tiktok-api/llms.txt `api.user(username).playlists()` yields `Playlist` objects representing public playlists created by the user. ```APIDOC ## User — Playlists `api.user(username).playlists()` yields `Playlist` objects representing public playlists created by the user. ### Description Retrieves a list of public playlists created by a specific TikTok user. ### Method `api.user(username).playlists(count)` ### Parameters - **username** (string) - Required - The username of the TikTok user. - **count** (integer) - Optional - The number of playlists to retrieve. Defaults to a reasonable amount if not specified. ### Response Example Yields `Playlist` objects, each containing: ```json { "name": "Playlist Name", "video_count": 10, "cover_url": "url_to_playlist_cover" } ``` ``` -------------------------------- ### Fetch Trending TikTok Videos Source: https://github.com/davidteather/tiktok-api/blob/main/README.md An asynchronous Python script to fetch and print trending TikTok videos. It requires an ms_token environment variable and uses asyncio for execution. The video data can be accessed as a dictionary using .as_dict. ```python from TikTokApi import TikTokApi import asyncio import os ms_token = os.environ.get("ms_token", None) # get your own ms_token from your cookies on tiktok.com async def trending_videos(): async with TikTokApi() as api: await api.create_sessions(ms_tokens=[ms_token], num_sessions=1, sleep_after=3, browser=os.getenv("TIKTOK_BROWSER", "chromium")) async for video in api.trending.videos(count=30): print(video) print(video.as_dict) if __name__ == "__main__": asyncio.run(trending_videos()) ``` -------------------------------- ### Search TikTok Videos (Raw Request) Source: https://context7.com/davidteather/tiktok-api/llms.txt Performs a raw API request to search for videos using the /api/search/item/full/ endpoint. Useful when high-level search wrappers are insufficient. Handles pagination with cursor. ```python from TikTokApi import TikTokApi import asyncio, os async def search_videos(): async with TikTokApi() as api: await api.create_sessions(ms_tokens=[os.environ.get("ms_token")], num_sessions=1, sleep_after=3) keyword = "funny cats" cursor = 0 collected = 0 while collected < 30: response = await api.make_request( url="https://www.tiktok.com/api/search/item/full/", params={"keyword": keyword, "count": 10, "cursor": cursor, "source": "search_video"}, ) for video in response.get("item_list", []): print(f"@{video['author']['uniqueId']}: {video['desc']}") print(f" ID: {video['id']}") collected += 1 cursor = response.get("cursor", 0) if not response.get("has_more", False): break asyncio.run(search_videos()) ``` -------------------------------- ### Video Info Source: https://context7.com/davidteather/tiktok-api/llms.txt `api.video(url=...).info()` retrieves full video metadata by parsing TikTok's HTML page (slower than API calls; avoid calling repeatedly). Accepts either a direct URL or a numeric ID. ```APIDOC ## Video — Info `api.video(url=...).info()` retrieves full video metadata by parsing TikTok's HTML page (slower than API calls; avoid calling repeatedly). Accepts either a direct URL or a numeric ID. ### Description Retrieves detailed metadata for a specific TikTok video using its URL or ID. This method involves parsing the HTML page and should be used sparingly. ### Method `api.video(url=url_or_id).info()` ### Parameters - **url_or_id** (string) - Required - The URL or the numeric ID of the TikTok video. ### Response Example Returns a dictionary containing video metadata: ```json { "id": "video_id_string", "author": { "username": "author_username" }, "stats": { "playCount": 1000000, "commentCount": 1000, "shareCount": 100, "diggCount": 5000 }, "sound": { "title": "Sound Title" } } ``` ``` -------------------------------- ### User Profile Info Source: https://context7.com/davidteather/tiktok-api/llms.txt `api.user(username).info()` fetches a user's full profile metadata by calling TikTok's `/api/user/detail/` endpoint. ```APIDOC ## User — Profile Info `api.user(username).info()` fetches a user's full profile metadata by calling TikTok's `/api/user/detail/` endpoint. ### Description Fetches the full profile metadata for a given TikTok user. ### Method `api.user(username).info()` ### Parameters - **username** (string) - Required - The username of the TikTok user. ### Response Example ```json { "userInfo": { "user": { "id": "6955468384719831046", "secUid": "long sec_uid string", "username": "therock", "signature": "User bio or signature" }, "stats": { "followerCount": 123456789, "followingCount": 123, "heartCount": 1234567890, "videoCount": 1234 } } } ``` ``` -------------------------------- ### Download Video Bytes - TikTok API Source: https://context7.com/davidteather/tiktok-api/llms.txt Downloads raw video bytes. Use `stream=True` for an async iterator of chunks to avoid loading the entire file into memory. ```python from TikTokApi import TikTokApi import asyncio, os async def download_video(): async with TikTokApi() as api: await api.create_sessions(ms_tokens=[os.environ.get("ms_token")], num_sessions=1, sleep_after=3) video = api.video(url="https://www.tiktok.com/@davidteathercodes/video/7074717081563942186") await video.info() # must call info() first to populate downloadAddr # Download full file data = await video.bytes() with open("video.mp4", "wb") as f: f.write(data) # Streaming download async for chunk in await video.bytes(stream=True): # process or forward chunk pass asyncio.run(download_video()) ``` -------------------------------- ### Video Related Videos Source: https://context7.com/davidteather/tiktok-api/llms.txt `video.related_videos()` yields videos algorithmically related to a given video ID. ```APIDOC ## Video — Related Videos `video.related_videos()` yields videos algorithmically related to a given video ID. ```python from TikTokApi import TikTokApi import asyncio, os async def get_related(): async with TikTokApi() as api: await api.create_sessions(ms_tokens=[os.environ.get("ms_token")], num_sessions=1, sleep_after=3) video = api.video(url="https://www.tiktok.com/@davidteathercodes/video/7074717081563942186") async for related in video.related_videos(count=10): print(f"Related: {related.id} by @{related.author.username}") asyncio.run(get_related()) ``` ``` -------------------------------- ### Video Comments Source: https://context7.com/davidteather/tiktok-api/llms.txt `video.comments()` is an async generator yielding `Comment` objects from a video's comment section. Each comment exposes `.text`, `.likes_count`, and `.author`. ```APIDOC ## Video — Comments `video.comments()` is an async generator yielding `Comment` objects from a video's comment section. Each comment exposes `.text`, `.likes_count`, and `.author`. ```python from TikTokApi import TikTokApi import asyncio, os async def get_comments(): async with TikTokApi() as api: await api.create_sessions(ms_tokens=[os.environ.get("ms_token")], num_sessions=1, sleep_after=3) video = api.video(id=7248300636498890011) async for comment in video.comments(count=30): print(f"@{comment.author.username}: {comment.text}") print(f"Likes: {comment.likes_count}") # Fetch replies to this comment async for reply in comment.replies(count=5): print(f" └ @{reply.author.username}: {reply.text}") asyncio.run(get_comments()) ``` ``` -------------------------------- ### User Liked Videos Source: https://context7.com/davidteather/tiktok-api/llms.txt `api.user(username).liked()` yields videos a user has publicly liked. Raises `InvalidResponseException` if the user's likes are private. ```APIDOC ## User — Liked Videos `api.user(username).liked()` yields videos a user has publicly liked. Raises `InvalidResponseException` if the user's likes are private. ### Description Retrieves a list of videos that a specific TikTok user has publicly liked. ### Method `api.user(username).liked(count)` ### Parameters - **username** (string) - Required - The username of the TikTok user. - **count** (integer) - Optional - The number of liked videos to retrieve. Defaults to a reasonable amount if not specified. ### Response Example Yields `Video` objects for liked videos. If likes are private, an `InvalidResponseException` is raised. ```json { "id": "video_id_string", "description": "Video description" } ``` ``` -------------------------------- ### Retrieve Trending TikTok Videos Source: https://context7.com/davidteather/tiktok-api/llms.txt Fetches trending videos from TikTok's For You Page using an async generator. It yields Video objects, providing access to video ID, author, sound, hashtags, stats, and creation time. The raw JSON payload is available via the `.as_dict` property. ```python from TikTokApi import TikTokApi import asyncio, os async def get_trending(): async with TikTokApi() as api: await api.create_sessions(ms_tokens=[os.environ.get("ms_token")], num_sessions=1, sleep_after=3) async for video in api.trending.videos(count=30): print(f"ID: {video.id}") print(f"Author: {video.author}") # TikTokApi.user object print(f"Sound: {video.sound}") # TikTokApi.sound object print(f"Hashtags: {video.hashtags}") # list of TikTokApi.hashtag print(f"Stats: {video.stats}") # {"playCount": ..., "likeCount": ...} print(f"Created: {video.create_time}") # datetime object # Full raw TikTok payload: print(video.as_dict) asyncio.run(get_trending()) ``` -------------------------------- ### Trending Videos Source: https://context7.com/davidteather/tiktok-api/llms.txt Retrieves trending videos from TikTok's For You Page using an async generator. ```APIDOC ## api.trending.videos() ### Description An async generator that yields `Video` objects from TikTok's For You Page recommendation feed. Each `Video` object provides access to its ID, author, sound, hashtags, statistics, creation time, and the raw JSON payload. ### Method `async for video in api.trending.videos(count=N)` ### Parameters - `count` (int) - The number of videos to retrieve. ### Request Example ```python from TikTokApi import TikTokApi import asyncio, os async def get_trending(): async with TikTokApi() as api: await api.create_sessions(ms_tokens=[os.environ.get("ms_token")], num_sessions=1, sleep_after=3) async for video in api.trending.videos(count=30): print(f"ID: {video.id}") print(f"Author: {video.author}") print(f"Sound: {video.sound}") print(f"Hashtags: {video.hashtags}") print(f"Stats: {video.stats}") print(f"Created: {video.create_time}") print(video.as_dict) asyncio.run(get_trending()) ``` ### Response #### Success Response Yields `Video` objects, each containing: - `id` (str) - `author` (TikTokApi.user object) - `sound` (TikTokApi.sound object) - `hashtags` (list of TikTokApi.hashtag objects) - `stats` (dict, e.g., `{"playCount": ..., "likeCount": ...}`) - `create_time` (datetime object) - `as_dict` (dict - raw TikTok payload) ``` -------------------------------- ### Fetch Video Comments and Replies - TikTok API Source: https://context7.com/davidteather/tiktok-api/llms.txt Fetches comments from a video's comment section, yielding `Comment` objects. Each comment has `.text`, `.likes_count`, and `.author` attributes. Replies to comments can also be fetched. ```python from TikTokApi import TikTokApi import asyncio, os async def get_comments(): async with TikTokApi() as api: await api.create_sessions(ms_tokens=[os.environ.get("ms_token")], num_sessions=1, sleep_after=3) video = api.video(id=7248300636498890011) async for comment in video.comments(count=30): print(f"@{comment.author.username}: {comment.text}") print(f"Likes: {comment.likes_count}") # Fetch replies to this comment async for reply in comment.replies(count=5): print(f" └ @{reply.author.username}: {reply.text}") asyncio.run(get_comments()) ``` -------------------------------- ### Handle TikTok API Exceptions Source: https://context7.com/davidteather/tiktok-api/llms.txt Catch specific TikTok exceptions like `EmptyResponseException` (bot detection), `NotFoundException` (resource not found), `InvalidResponseException` (unexpected structure), and `CaptchaException`. All exceptions inherit from `TikTokException` and provide `.error_code`, `.raw_response`, and `.message`. ```python from TikTokApi import TikTokApi from TikTokApi.exceptions import ( EmptyResponseException, # TikTok detected a bot; try proxy or headless=False InvalidResponseException, # unexpected response structure InvalidJSONException, # response could not be parsed as JSON NotFoundException, # resource does not exist CaptchaException, # TikTok is showing a CAPTCHA ) import asyncio, os async def with_error_handling(): async with TikTokApi() as api: await api.create_sessions(ms_tokens=[os.environ.get("ms_token")], num_sessions=1, sleep_after=3) try: user_data = await api.user(username="nonexistent_user_xyz123").info() except EmptyResponseException as e: print(f"Bot detected: {e.message} — consider using a proxy") except NotFoundException as e: print(f"User not found: {e}") except InvalidResponseException as e: print(f"Unexpected TikTok response (code {e.error_code}): {e.message}") except CaptchaException as e: print(f"CAPTCHA encountered: {e}") asyncio.run(with_error_handling()) ``` -------------------------------- ### Search TikTok Users Source: https://context7.com/davidteather/tiktok-api/llms.txt Searches for TikTok users by name. Requires a previously used ms_token for session creation. ```python from TikTokApi import TikTokApi import asyncio, os async def search_users(): async with TikTokApi() as api: await api.create_sessions(ms_tokens=[os.environ.get("ms_token")], num_sessions=1, sleep_after=3) async for user in api.search.users("david teather", count=10): print(f"Username: {user.username}") print(f"User ID: {user.user_id}") print(f"Sec UID: {user.sec_uid}") asyncio.run(search_users()) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.