TikTokApi package
Subpackages
TikTokApi Main Class
This is the main TikTokApi module. It contains the TikTokApi class which is the main class of the package.
- class TikTokApi.tiktok.TikTokApi(logging_level: int = 30, logger_name: str = None)[source]
Bases:
object
The main TikTokApi class that contains all the endpoints.
- Import With:
from TikTokApi import TikTokApi api = TikTokApi()
- async close_sessions()[source]
Close all the sessions. Should be called when you’re done with the TikTokApi object
This is called automatically when using the TikTokApi with “with”
- async create_sessions(num_sessions: int = 5, headless: bool = True, ms_tokens: list[str] | None = None, proxies: list[dict[str, Any] | ProxySettings] | None = None, proxy_provider: ProxyProvider | None = None, proxy_algorithm: Algorithm | None = None, sleep_after: int = 1, starting_url: str = 'https://www.tiktok.com', context_options: dict[str, Any] = {}, override_browser_args: list[str] | None = None, cookies: list[dict[str, Any]] | None = None, suppress_resource_load_types: list[str] | None = None, browser: str = 'chromium', executable_path: str | None = None, page_factory: Callable[[BrowserContext], Awaitable[Page]] | None = None, browser_context_factory: Callable[[Playwright], Awaitable[BrowserContext]] | None = None, timeout: int = 30000, enable_session_recovery: bool = True, allow_partial_sessions: bool = False, min_sessions: int | None = None)[source]
Create sessions for use within the TikTokApi class.
These sessions are what will carry out requesting your data from TikTok.
- Parameters:
num_sessions (int) – The amount of sessions you want to create.
headless (bool) – Whether or not you want the browser to be headless.
ms_tokens (list[str]) – A list of msTokens to use for the sessions, you can get these from your cookies after visiting TikTok. If you don’t provide any, the sessions will try to get them themselves, but this is not guaranteed to work.
proxies (list) – DEPRECATED - Use proxy_provider instead. A list of proxies to use for the sessions. This parameter is maintained for backwards compatibility but will be removed in a future version.
proxy_provider (ProxyProvider | None) – A ProxyProvider instance for smart proxy rotation. See examples/proxy_provider_example.py for usage examples. Full documentation: https://davidteather.github.io/proxyproviders/
proxy_algorithm (Algorithm | None) – Algorithm for proxy selection (RoundRobin, Random, First, or custom) per session. Only used with proxy_provider. Defaults to RoundRobin if not specified.
sleep_after (int) – The amount of time to sleep after creating a session, this is to allow the msToken to be generated.
starting_url (str) – The url to start the sessions on, this is usually https://www.tiktok.com.
context_options (dict) – Options to pass to the playwright context.
override_browser_args (list[dict]) – A list of dictionaries containing arguments to pass to the browser.
cookies (list[dict]) – A list of cookies to use for the sessions, you can get these from your cookies after visiting TikTok.
suppress_resource_load_types (list[str]) – Types of resources to suppress playwright from loading, excluding more types will make playwright faster.. Types: document, stylesheet, image, media, font, script, textrack, xhr, fetch, eventsource, websocket, manifest, other.
browser (str) – firefox, chromium, or webkit; default is chromium
executable_path (str) – Path to the browser executable
page_factory (Callable[[BrowserContext], Awaitable[Page]]) – Optional async function for instantiating pages.
browser_context_factory (Callable[[Playwright], Awaitable[BrowserContext]]) – Optional async function for creating browser contexts. When provided, you can choose any browser (chromium/firefox/webkit) inside the factory, and the ‘browser’ parameter is ignored.
timeout (int) – The timeout in milliseconds for page navigation
enable_session_recovery (bool) – Enable automatic session recovery on failures (default: True)
allow_partial_sessions (bool) – If True, succeed even if some sessions fail to create. If False (default), fail if any session fails
min_sessions (int | None) – Minimum number of sessions required. Only used if allow_partial_sessions=True. If None, defaults to 1.
- Example Usage:
from TikTokApi import TikTokApi async with TikTokApi() as api: await api.create_sessions(num_sessions=5, ms_tokens=['msToken1', 'msToken2'])
- Proxy Provider Usage:
For proxy provider examples with different algorithms and configurations, see examples/proxy_provider_example.py
- Custom Launchers:
To implement custom functionality, such as login or captcha solving, when the session is being created, you may use the keyword arguments browser_context_factory and page_factory. These arguments are callable functions that TikTok-Api will use to launch your browser and pages, and allow you to perform custom actions on the page before the session is created. You can find examples in the test file: tests/test_custom_launchers.py
- generate_js_fetch(method: str, url: str, headers: dict) str [source]
Generate a javascript fetch function for use in playwright
- get_resource_stats() dict [source]
Get statistics about current resource usage.
Useful for monitoring and detecting potential memory leaks.
- Returns:
Statistics including session count, browser status, etc.
- Return type:
dict
- async get_session_cookies(session)[source]
Get the cookies for a session
- Parameters:
session (TikTokPlaywrightSession) – The session to get the cookies for.
- Returns:
The cookies for the session.
- Return type:
dict
- async health_check() dict [source]
Perform a health check on all resources.
This actively validates all sessions and returns detailed health info. Useful for monitoring and debugging.
- Returns:
Health check results
- Return type:
dict
- async make_request(url: str, headers: dict = None, params: dict = None, retries: int = 3, exponential_backoff: bool = True, **kwargs)[source]
Makes a request to TikTok through a session.
- Parameters:
url (str) – The url to make the request to.
headers (dict) – The headers to use for the request.
params (dict) – The params to use for the request.
retries (int) – The amount of times to retry the request if it fails.
exponential_backoff (bool) – Whether or not to use exponential backoff when retrying the request.
session_index (int) – The index of the session you want to use, if not provided a random session will be used.
- Returns:
The json response from TikTok.
- Return type:
dict
- Raises:
Exception – If the request fails.
- playlist
alias of
Playlist
- async run_fetch_script(url: str, headers: dict, **kwargs)[source]
Execute a javascript fetch function in a session
- Parameters:
url (str) – The url to fetch.
headers (dict) – The headers to use for the fetch.
- Returns:
The result of the fetch. Seems to be a string or dict
- Return type:
any
- async set_session_cookies(session, cookies)[source]
Set the cookies for a session
- Parameters:
session (TikTokPlaywrightSession) – The session to set the cookies for.
cookies (dict) – The cookies to set for the session.
- class TikTokApi.tiktok.TikTokPlaywrightSession(context: Any, page: Any, proxy: str = None, params: dict = None, headers: dict = None, ms_token: str = None, base_url: str = 'https://www.tiktok.com', is_valid: bool = True)[source]
Bases:
object
A TikTok session using Playwright
- base_url: str = 'https://www.tiktok.com'
- context: Any
- headers: dict = None
- is_valid: bool = True
- ms_token: str = None
- page: Any
- params: dict = None
- proxy: str = None
TikTokApi.exceptions module
- exception TikTokApi.exceptions.CaptchaException(raw_response, message, error_code=None)[source]
Bases:
TikTokException
TikTok is showing captcha
- exception TikTokApi.exceptions.EmptyResponseException(raw_response, message, error_code=None)[source]
Bases:
TikTokException
TikTok sent back an empty response.
- exception TikTokApi.exceptions.InvalidJSONException(raw_response, message, error_code=None)[source]
Bases:
TikTokException
TikTok returned invalid JSON.
- exception TikTokApi.exceptions.InvalidResponseException(raw_response, message, error_code=None)[source]
Bases:
TikTokException
The response from TikTok was invalid.
- exception TikTokApi.exceptions.NotFoundException(raw_response, message, error_code=None)[source]
Bases:
TikTokException
TikTok indicated that this object does not exist.
- exception TikTokApi.exceptions.SoundRemovedException(raw_response, message, error_code=None)[source]
Bases:
TikTokException
This TikTok sound has no id from being removed by TikTok.