### Get Session Content Source: https://davidteather.github.io/TikTok-Api/TikTokApi.html#tiktok-api-main/index Fetches the content of a given URL within the context of a TikTok API session. This is an asynchronous function that allows retrieval of web page data. It takes the URL as a parameter and accepts additional keyword arguments. ```python async def _get_session_content(_url : str_, _** kwargs_) -> Any: """ Get the content of a url """ ``` -------------------------------- ### Get Resource Statistics Source: https://davidteather.github.io/TikTok-Api/TikTokApi.html#tiktok-api-main/index Retrieves statistics about the current resource usage of the TikTok API client. This function is valuable for monitoring the application's performance, tracking session counts, browser status, and detecting potential memory leaks. It returns a dictionary containing these statistics. ```python def get_resource_stats() -> dict: """ 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 """ ``` -------------------------------- ### Get Session Cookies Source: https://davidteather.github.io/TikTok-Api/TikTokApi.html#tiktok-api-main/index Retrieves the cookies associated with a specific TikTok Playwright session. This asynchronous function requires a TikTokPlaywrightSession object as input and returns a dictionary containing the session's cookies. This is useful for maintaining user sessions or replicating browser states. ```python async def _get_session_cookies(_session_: TikTokPlaywrightSession) -> dict: """ 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 """ ``` -------------------------------- ### TikTokApi Class Initialization Source: https://davidteather.github.io/TikTok-Api/TikTokApi.html#tiktok-api-main/index Demonstrates how to import and initialize the main TikTokApi class. ```APIDOC ## TikTokApi Class ### Description The main TikTokApi class that contains all the endpoints. ### Method __init__ ### Parameters - **logging_level** (int) - Optional - The logging level for the API. - **logger_name** (str) - Optional - The name of the logger. ### Request Example ```python from TikTokApi import TikTokApi api = TikTokApi() ``` ``` -------------------------------- ### Initialize TikTokApi Source: https://davidteather.github.io/TikTok-Api/TikTokApi.html#tiktok-api-main/index Demonstrates how to import and initialize the main TikTokApi class. This is the entry point for interacting with the TikTok API. No specific dependencies are mentioned beyond the package itself. ```python from TikTokApi import TikTokApi api = TikTokApi() ``` -------------------------------- ### Create TikTokApi Sessions Source: https://davidteather.github.io/TikTok-Api/TikTokApi.html#tiktok-api-main/index Shows how to create multiple browser sessions for making requests to TikTok. It supports headless browsing, custom MSTokens, proxy configurations, and various browser options. Sessions are essential for data retrieval. ```python from TikTokApi import TikTokApi async with TikTokApi() as api: await api.create_sessions(num_sessions=5, ms_tokens=['msToken1', 'msToken2']) ``` -------------------------------- ### Session Management API Source: https://davidteather.github.io/TikTok-Api/TikTokApi.html#tiktok-api-main/index Documentation for methods related to creating and closing API sessions. ```APIDOC ## Close Sessions API ### Description 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'. ### Method _async _close_sessions ### Endpoint Not Applicable (Internal Method) ### Parameters None ### Request Example ```python from TikTokApi import TikTokApi async with TikTokApi() as api: # Use the API pass # Sessions are automatically closed upon exiting the 'with' block ``` ## Create Sessions API ### Description Create sessions for use within the TikTokApi class. These sessions are what will carry out requesting your data from TikTok. ### Method _async _create_sessions ### Endpoint Not Applicable (Internal Method) ### 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] | None) - A list of msTokens to use for the sessions. If not provided, sessions will try to get them themselves. - **proxies** (list[dict[str, Any] | ProxySettings] | None) - DEPRECATED - Use proxy_provider instead. A list of proxies to use for the sessions. - **proxy_provider** (ProxyProvider | None) - A ProxyProvider instance for smart proxy rotation. - **proxy_algorithm** (Algorithm | None) - Algorithm for proxy selection per session. Only used with proxy_provider. - **sleep_after** (int) - The amount of time to sleep after creating a session. - **starting_url** (str) - The url to start the sessions on. - **context_options** (dict) - Options to pass to the playwright context. - **override_browser_args** (list[str] | None) - A list of dictionaries containing arguments to pass to the browser. - **cookies** (list[dict[str, Any]] | None) - A list of cookies to use for the sessions. - **suppress_resource_load_types** (list[str] | None) - Types of resources to suppress playwright from loading. - **browser** (str) - firefox, chromium, or webkit; default is chromium. - **executable_path** (str | None) - Path to the browser executable. - **page_factory** (Callable[[BrowserContext], Awaitable[Page]] | None) - Optional async function for instantiating pages. - **browser_context_factory** (Callable[[Playwright], Awaitable[BrowserContext]] | None) - Optional async function for creating browser contexts. - **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. ### Request Example ```python from TikTokApi import TikTokApi async with TikTokApi() as api: await api.create_sessions(num_sessions=5, ms_tokens=['msToken1', 'msToken2']) ``` ### Proxy Provider Usage Example ```python # For proxy provider examples with different algorithms and configurations, see examples/proxy_provider_example.py ``` ``` -------------------------------- ### make_request Source: https://davidteather.github.io/TikTok-Api/TikTokApi.html#tiktok-api-main/index Makes a request to TikTok through a session. ```APIDOC ## POST /make_request ### Description Makes a request to TikTok through a session. ### Method POST ### Endpoint /make_request ### Parameters #### Request Body - **url** (str) - Required - The URL to make the request to. - **headers** (dict) - Optional - The headers to use for the request. - **params** (dict) - Optional - The query parameters to use for the request. - **retries** (int) - Optional - The amount of times to retry the request if it fails. Defaults to 3. - **exponential_backoff** (bool) - Optional - Whether or not to use exponential backoff when retrying the request. Defaults to True. - **session_index** (int) - Optional - The index of the session to use. If not provided, a random session will be used. ### Request Example ```json { "url": "https://www.tiktok.com/api/challenge/item_list/?challenge_id=12345", "headers": { "X-Bogus": "OGNhY2VlYTI4ZGY4MGE5YTFmNzAxMjM4OWJmOTg2ZGI=" }, "params": { "count": 10, "cursor": 0 }, "session_index": 1 } ``` ### Response #### Success Response (200) - **response_data** (dict) - The JSON response from TikTok. #### Response Example ```json { "response_data": { "items": [...], "has_more": true } } ``` #### Error Response (e.g., 400, 500) - **error** (dict) - An error object detailing the failure. #### Error Example ```json { "error": { "code": "REQUEST_FAILED", "message": "The request to TikTok failed after multiple retries." } } ``` ``` -------------------------------- ### run_fetch_script Source: https://davidteather.github.io/TikTok-Api/TikTokApi.html#tiktok-api-main/index Executes a javascript fetch function in a Playwright session. ```APIDOC ## POST /run_fetch_script ### Description Execute a javascript fetch function in a session. ### Method POST ### Endpoint /run_fetch_script ### Parameters #### Request Body - **url** (str) - Required - The URL to fetch. - **headers** (dict) - Required - The headers to use for the fetch. - **kwargs** (dict) - Optional - Additional keyword arguments for the fetch. ### Request Example ```json { "url": "https://example.com/data", "headers": { "Content-Type": "application/json" } } ``` ### Response #### Success Response (200) - **result** (any) - The result of the fetch operation. Can be a string or a dictionary. #### Response Example ```json { "result": { "data": "some data" } } ``` ``` -------------------------------- ### generate_x_bogus Source: https://davidteather.github.io/TikTok-Api/TikTokApi.html#tiktok-api-main/index Generates the X-Bogus header for a given URL. ```APIDOC ## POST /generate_x_bogus ### Description Generates the X-Bogus header required for TikTok API requests. ### Method POST ### Endpoint /generate_x_bogus ### Parameters #### Request Body - **_url** (str) - Required - The URL for which to generate the X-Bogus header. - **_kwargs** (dict) - Optional - Additional keyword arguments to influence header generation. ### Request Example ```json { "_url": "https://www.tiktok.com/api/item_list/?{} " } ``` ### Response #### Success Response (200) - **x_bogus** (str) - The generated X-Bogus header value. #### Response Example ```json { "x_bogus": "OGNhY2VlYTI4ZGY4MGE5YTFmNzAxMjM4OWJmOTg2ZGI=" } ``` ``` -------------------------------- ### get_resource_stats Source: https://davidteather.github.io/TikTok-Api/TikTokApi.html#tiktok-api-main/index Retrieves statistics about current resource usage. ```APIDOC ## GET /resource_stats ### Description Get statistics about current resource usage. Useful for monitoring and detecting potential memory leaks. ### Method GET ### Endpoint /resource_stats ### Parameters None ### Response #### Success Response (200) - **session_count** (int) - The number of active sessions. - **browser_status** (str) - The status of the browser (e.g., 'running', 'closed'). - **memory_usage** (dict) - Memory usage details. #### Response Example ```json { "session_count": 5, "browser_status": "running", "memory_usage": { "rss": 1024, "heapTotal": 512, "heapUsed": 256 } } ``` ``` -------------------------------- ### generate_js_fetch Source: https://davidteather.github.io/TikTok-Api/TikTokApi.html#tiktok-api-main/index Generates a javascript fetch function for use in Playwright. ```APIDOC ## POST /generate_js_fetch ### Description Generates a javascript fetch function for use in Playwright. ### Method POST ### Endpoint /generate_js_fetch ### Parameters #### Request Body - **_method** (str) - Required - The HTTP method to use for the fetch request. - **_url** (str) - Required - The URL to fetch. - **_headers** (dict) - Required - The headers to include in the fetch request. ### Request Example ```json { "_method": "POST", "_url": "https://example.com", "_headers": { "Content-Type": "application/json" } } ``` ### Response #### Success Response (200) - **fetch_function** (str) - The generated javascript fetch function. #### Response Example ```json { "fetch_function": "async (url, headers) => {\n const response = await fetch(url, {\n method: 'POST',\n headers: headers,\n body: JSON.stringify(data)\n });\n return response.json();\n}" } ``` ``` -------------------------------- ### Run JavaScript Fetch Script Source: https://davidteather.github.io/TikTok-Api/TikTokApi.html#tiktok-api-main/index Executes a provided JavaScript fetch script within a specific TikTok API session. This asynchronous function allows for complex client-side interactions and data fetching. It takes the URL and headers for the fetch operation, returning the result which can be a string or dictionary. ```python async def _run_fetch_script(_url : str_, _headers : dict_, _** kwargs_) -> Any: """ 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 """ ``` -------------------------------- ### sign_url Source: https://davidteather.github.io/TikTok-Api/TikTokApi.html#tiktok-api-main/index Signs a given URL, likely for authentication or tracking purposes. ```APIDOC ## POST /sign_url ### Description Sign a url. ### Method POST ### Endpoint /sign_url ### Parameters #### Request Body - **_url** (str) - Required - The URL to sign. - **_kwargs** (dict) - Optional - Additional keyword arguments to influence signing. ### Request Example ```json { "_url": "https://example.com/resource" } ``` ### Response #### Success Response (200) - **signed_url** (str) - The signed URL. #### Response Example ```json { "signed_url": "https://example.com/resource?signature=xyzabc" } ``` ``` -------------------------------- ### TikTokPlaywrightSession Class Source: https://davidteather.github.io/TikTok-Api/TikTokApi.html#tiktok-api-main/index Represents a session managed by Playwright for interacting with TikTok. This class encapsulates browser context, page, proxy settings, headers, and other parameters necessary for making requests. It includes attributes for base URL, validity status, and MS token. ```python class TikTokPlaywrightSession: """ 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 def __init__(self, _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): pass ``` -------------------------------- ### get_session_content Source: https://davidteather.github.io/TikTok-Api/TikTokApi.html#tiktok-api-main/index Retrieves the content of a specified URL within a TikTok session. ```APIDOC ## POST /get_session_content ### Description Get the content of a url within a TikTok session. ### Method POST ### Endpoint /get_session_content ### Parameters #### Request Body - **_url** (str) - Required - The URL to retrieve content from. - **_kwargs** (dict) - Optional - Additional keyword arguments for the request. ### Request Example ```json { "_url": "https://www.tiktok.com/foryou" } ``` ### Response #### Success Response (200) - **content** (str) - The HTML content of the URL. #### Response Example ```json { "content": "..." } ``` ``` -------------------------------- ### Generate X-Bogus Header Source: https://davidteather.github.io/TikTok-Api/TikTokApi.html#tiktok-api-main/index Generates the 'X-Bogus' header required for many TikTok API requests. This header is dynamically generated based on the URL and other optional parameters, and is crucial for authenticating and authorizing requests. It is an asynchronous function. ```python async def _generate_x_bogus(_url : str_, _** kwargs_) -> str: """ Generate the X-Bogus header for a url """ ``` -------------------------------- ### Make TikTok Request Source: https://davidteather.github.io/TikTok-Api/TikTokApi.html#tiktok-api-main/index Makes an HTTP request to the TikTok API using an active session. This asynchronous function handles request details such as URL, headers, parameters, retries, and exponential backoff. It returns the JSON response from TikTok or raises an exception if the request fails. ```python async def _make_request(_url : str_, _headers : dict = None_, _params : dict = None_, _retries : int = 3_, _exponential_backoff : bool = True_, _** kwargs_) -> dict: """ 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. """ ``` -------------------------------- ### get_session_cookies Source: https://davidteather.github.io/TikTok-Api/TikTokApi.html#tiktok-api-main/index Retrieves cookies for a given TikTok Playwright session. ```APIDOC ## POST /get_session_cookies ### Description Get the cookies for a given TikTok Playwright session. ### Method POST ### Endpoint /get_session_cookies ### Parameters #### Request Body - **session** (TikTokPlaywrightSession) - Required - The session object to get cookies from. ### Request Example ```json { "session": "" } ``` ### Response #### Success Response (200) - **cookies** (dict) - A dictionary containing the cookies for the session. #### Response Example ```json { "cookies": { "name": "sessionid", "value": "abcdef12345", "domain": "www.tiktok.com" } } ``` ``` -------------------------------- ### set_session_cookies Source: https://davidteather.github.io/TikTok-Api/TikTokApi.html#tiktok-api-main/index Sets cookies for a given TikTok Playwright session. ```APIDOC ## POST /set_session_cookies ### Description Set the cookies for a TikTok Playwright session. ### Method POST ### Endpoint /set_session_cookies ### Parameters #### Request Body - **session** (TikTokPlaywrightSession) - Required - The session object to set the cookies for. - **cookies** (dict) - Required - The cookies to set for the session. ### Request Example ```json { "session": "", "cookies": { "name": "sessionid", "value": "abcdef12345", "domain": "www.tiktok.com" } } ``` ### Response #### Success Response (200) - **status** (str) - A message indicating the success of the operation (e.g., 'Cookies set successfully'). #### Response Example ```json { "status": "Cookies set successfully." } ``` ``` -------------------------------- ### Generate JavaScript Fetch Function Source: https://davidteather.github.io/TikTok-Api/TikTokApi.html#tiktok-api-main/index Generates a JavaScript fetch function string that can be executed within a Playwright browser context. This is useful for making API requests directly from the browser environment managed by Playwright. It takes the HTTP method, URL, and headers as input. ```python def generate_js_fetch(_method : str_, _url : str_, _headers : dict_) -> str: """ Generate a javascript fetch function for use in playwright """ ``` -------------------------------- ### Sign URL Source: https://davidteather.github.io/TikTok-Api/TikTokApi.html#tiktok-api-main/index Signs a given URL, likely for authentication or to ensure request integrity within the TikTok API ecosystem. This asynchronous function takes the URL as input and may accept additional keyword arguments for the signing process. The exact return type is not specified but implies a modified or signed URL. ```python async def _sign_url(_url : str_, _** kwargs_) -> Any: """ Sign a url """ ``` -------------------------------- ### stop_playwright Source: https://davidteather.github.io/TikTok-Api/TikTokApi.html#tiktok-api-main/index Stops the Playwright browser instance. ```APIDOC ## POST /stop_playwright ### Description Stop the playwright browser. Note: It’s better to use close_sessions() which calls this automatically. ### Method POST ### Endpoint /stop_playwright ### Parameters None ### Response #### Success Response (200) - **status** (str) - A message indicating the Playwright browser has been stopped. #### Response Example ```json { "status": "Playwright browser stopped." } ``` ``` -------------------------------- ### Define TikTok API Custom Exceptions Source: https://davidteather.github.io/TikTok-Api/TikTokApi.html#tiktok-api-main/index This section defines custom exceptions that are raised when specific errors occur during TikTok API interactions. These include issues like Captcha requirements, empty or invalid responses, and not found errors. They all inherit from a base TikTokException. ```python class TikTokException(Exception): """Generic exception that all other TikTok errors are children of.""" def __init__(self, _raw_response_, _message_, _error_code=None): self._raw_response_ = _raw_response_ self._message_ = _message_ self._error_code = _error_code class CaptchaException(TikTokException): """TikTok is showing captcha""" pass class EmptyResponseException(TikTokException): """TikTok sent back an empty response.""" pass class InvalidJSONException(TikTokException): """TikTok returned invalid JSON.""" pass class InvalidResponseException(TikTokException): """The response from TikTok was invalid.""" pass class NotFoundException(TikTokException): """TikTok indicated that this object does not exist.""" pass class SoundRemovedException(TikTokException): """This TikTok sound has no id from being removed by TikTok.""" pass ``` -------------------------------- ### health_check Source: https://davidteather.github.io/TikTok-Api/TikTokApi.html#tiktok-api-main/index Performs a health check on all TikTok API resources. ```APIDOC ## GET /health_check ### Description Perform a health check on all resources. This actively validates all sessions and returns detailed health info. Useful for monitoring and debugging. ### Method GET ### Endpoint /health_check ### Parameters None ### Response #### Success Response (200) - **health_info** (dict) - Detailed health check results for all resources. #### Response Example ```json { "health_info": { "sessions": [ {"id": 1, "status": "ok"}, {"id": 2, "status": "ok"} ], "browser": "ok" } } ``` ``` -------------------------------- ### Helper Function: Convert Request Cookie to Playwright Cookie Source: https://davidteather.github.io/TikTok-Api/TikTokApi.html#tiktok-api-main/index This utility function converts a cookie object from the `requests` library format to the format expected by Playwright. This is helpful when migrating session information between these two libraries. ```python def requests_cookie_to_playwright_cookie(_req_c_): """Converts a requests cookie to a Playwright cookie.""" # Implementation details for conversion would go here pass ``` -------------------------------- ### Helper Function: Random Choice from List Source: https://davidteather.github.io/TikTok-Api/TikTokApi.html#tiktok-api-main/index A utility function that selects a random element from a given list. If the provided list is empty, it returns None. This is useful for scenarios where a random selection from a set of options is needed. ```python def random_choice(_choices : list_): """Return a random choice from a list, or None if the list is empty""" import random if not _choices: return None return random.choice(_choices) ``` -------------------------------- ### Set Session Cookies Source: https://davidteather.github.io/TikTok-Api/TikTokApi.html#tiktok-api-main/index Sets the cookies for a given TikTok Playwright session. This asynchronous function takes a session object and a dictionary of cookies as parameters, allowing for the manipulation of session state or the simulation of logged-in users. It does not return a value. ```python async def _set_session_cookies(_session_: TikTokPlaywrightSession, _cookies_: dict) -> None: """ 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. """ ``` -------------------------------- ### Helper Function: Extract Video ID from URL Source: https://davidteather.github.io/TikTok-Api/TikTokApi.html#tiktok-api-main/index This function is designed to extract the unique video ID from a TikTok URL. It can optionally accept custom headers and proxy configurations for the request. The exact implementation details for parsing the URL are not shown here. ```python def extract_video_id_from_url(_url_ , _headers ={}_, _proxy =None_): """Extracts the video ID from a TikTok URL.""" # Implementation details for URL parsing would go here pass ``` -------------------------------- ### Stop Playwright Browser Source: https://davidteather.github.io/TikTok-Api/TikTokApi.html#tiktok-api-main/index Stops the Playwright browser instance managed by the TikTok API. While this function exists, it's recommended to use `close_sessions()`, which handles stopping the browser automatically as part of its cleanup process. This function does not take any parameters and returns None. ```python async def _stop_playwright() -> None: """ Stop the playwright browser. Note: It’s better to use close_sessions() which calls this automatically. """ ``` -------------------------------- ### Perform Health Check Source: https://davidteather.github.io/TikTok-Api/TikTokApi.html#tiktok-api-main/index Conducts a health check on all active resources, including validating sessions and providing detailed health information. This asynchronous function is essential for monitoring and debugging the API client, returning a dictionary with the health check results. ```python async def _health_check() -> dict: """ 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 """ ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.