TikTok-Api Python Wrapper
TikTok-Api is an unofficial, asynchronous Python 3 wrapper for interacting with the TikTok API. It leverages Playwright for headless browser automation to bypass bot detection and fetch data. Currently at version 7.3.3, it has a frequent release cadence, often with minor updates, but also introduces significant changes to handle TikTok's evolving anti-bot measures.
Common errors
-
ModuleNotFoundError: No module named 'playwright'
cause The `playwright` package, which is a core dependency, was not installed.fixRun `pip install playwright` to install the package. -
playwright._impl._api_types.Error: No browser was found at specified location
cause The Playwright package is installed, but the necessary browser binaries (e.g., Chromium) have not been downloaded.fixRun `playwright install` in your terminal to download the required browsers. -
RuntimeError: Event loop is closed
cause You are attempting to run asynchronous code outside of a properly managed `asyncio` event loop, or the loop has been prematurely closed.fixWrap your asynchronous `TikTokApi` calls within an `async def` function and execute it using `asyncio.run(your_async_function())`. -
TikTokApi.exceptions.TikTokException: Failed to create a session
cause TikTok's bot detection likely prevented the browser session from being established, or an invalid/expired `ms_token` was provided.fixEnsure you are using a valid, recent `ms_token`. Try `headless=False` for debugging. Consider using proxies and setting `num_sessions` to 1 initially for stability. Check your internet connection. -
Received empty lists or unexpected lack of data from API calls (e.g., `api.trending.videos()` returns nothing).
cause This is often a symptom of TikTok's bot detection or aggressive rate limiting.fixImplement robust anti-bot strategies: use a valid `ms_token`, integrate with `proxyproviders` (v7.2.0+), try different `browser_args`, and consider adding delays between requests. Reducing `count` in data fetching methods might also help.
Warnings
- breaking The return type of `user().info` changed from an `Iterator[dict]` to an `Iterator[Playlist]` object.
- gotcha TikTok actively employs bot detection mechanisms. You may receive empty results or encounter `TikTokException` if detected.
- gotcha The library is exclusively asynchronous, requiring `async/await` syntax and running within an `asyncio` event loop.
- gotcha After `pip install tiktokapi`, you must also install the necessary Playwright browser binaries.
- gotcha While the library can sometimes function without it, providing a valid `ms_token` significantly improves stability and success rates, especially for logged-in user data or to bypass frequent bot detection.
Install
-
pip install tiktokapi -
playwright install
Imports
- TikTokApi
from TikTokApi import TikTokApi
Quickstart
import asyncio
from TikTokApi import TikTokApi
import os
async def main():
# It is highly recommended to provide an ms_token for stability and to bypass some bot detections.
# You can get this from your browser's cookies when logged into TikTok.
ms_token = os.environ.get("TIKTOK_MS_TOKEN", "your_ms_token_here")
# For development/debugging, you might need to set headless=False to see the browser.
# You might also need to install Playwright browsers: `playwright install`.
async with TikTokApi(ms_token=ms_token, headless=True) as api:
# Create sessions. For more robust usage, consider num_sessions > 1 and proxy_providers.
await api.create_sessions(num_sessions=1, sleep_after_for_retry=False)
print("Fetching trending videos...")
async for video in api.trending.videos(count=5):
print(f"Video ID: {video.id}")
print(f"Author: {video.author.nickname} (@{video.author.unique_id})")
print(f"Description: {video.desc[:70]}...")
print(f"Play URL: {video.video.play_addr.uri}")
print("-" * 30)
if video.stats:
print(f" Likes: {video.stats.digg_count}, Comments: {video.stats.comment_count}")
if __name__ == "__main__":
asyncio.run(main())