Skip to content

API List

Note

🟢 Indicates implemented, 🟡 Indicates in progress or being modified, 🟤 Indicates temporarily not implemented, 🔵 Indicates possible future implementation, 🔴 Indicates deprecation.

handler API List
CLI InterfaceMethod
Download a single videohandle_one_video
Download user postshandle_user_post
Download user likeshandle_user_like
Download user favoriteshandle_user_collect
Download user playlisthandle_user_mix
Download search videoshandle_search_video
Download user live streamhandle_user_live
Data & Function APIsMethodDeveloper API
User profilefetch_user_profile🟢
Create user record & folderget_or_add_user_data🟢
Create video download recordget_or_add_video_data🟢
Fetch single video datafetch_one_video🟢
Fetch user posts datafetch_user_post_videos🟢
Fetch user liked videosfetch_user_like_videos🟢
Fetch user favoritesfetch_user_collect_videos🟢
Fetch user playlistsfetch_play_list🟢
Fetch user playlist videosfetch_user_mix_videos🟢
Fetch search resultsfetch_search_videos🟢
Fetch user live streamfetch_user_live_videos🟢
Check live stream statusfetch_check_live_alive🟢
utils API List
Developer APIClass NameMethodStatus
Manage client configClientConfManager🟢
Generate real msTokenTokenManagergen_real_msToken🟢
Generate fake msTokenTokenManagergen_false_msToken🟢
Generate ttwidTokenManagergen_ttwid🟢
Generate odin_ttTokenManagergen_odin_tt🟢
Generate Xb params from URLXBogusManagerstr_2_endpoint🟢
Generate Xb params from modelXBogusManagermodel_2_endpoint🟢
Extract single user IDSecUserIdFetcherget_secuid🟢
Extract list of user IDsSecUserIdFetcherget_all_secuid🟢
Extract single unique user IDSecUserIdFetcherget_uniqueid🟢
Extract list of unique user IDsSecUserIdFetcherget_all_uniqueid🟢
Extract list of user IDsSecUserIdFetcherget_all_secUid🟢
Extract single video IDAwemeIdFetcherget_aweme_id🟢
Extract list of video IDsAwemeIdFetcherget_all_aweme_id🟢
Generate device IDDeviceIdManagergen_device_id🟢
Generate list of device IDsDeviceIdManagergen_device_ids🟢
Global file name formatting-format_file_name🟢
Create user folder-create_user_folder🟢
Rename user folder-rename_user_folder🟢
Create or rename user folder-create_or_rename_user_folder🟢
crawler API List
Crawler URL APIClass NameMethodStatus
User profile APITiktokCrawlerfetch_user_profile🟢
User posts APITiktokCrawlerfetch_user_post🟢
User likes APITiktokCrawlerfetch_user_like🟢
User favorites APITiktokCrawlerfetch_user_collect🟢
User playlist APITiktokCrawlerfetch_user_play_list🟢
Playlist videos APITiktokCrawlerfetch_user_mix🟢
Video details APITiktokCrawlerfetch_post_detail🟢
Video comments APITiktokCrawlerfetch_post_comment🟢
Homepage feed APITiktokCrawlerfetch_post_feed🟢
Search videos APITiktokCrawlerfetch_post_search🟢
User live stream APITiktokCrawlerfetch_user_live🟢
Check live stream status APITiktokCrawlerfetch_check_live_alive🟢
dl API List
Downloader APIClass NameMethodStatus
Save last downloaded video IDTiktokDownloadersave_last_aweme_id🟢
Filter videos by time rangeTiktokDownloaderfilter_aweme_datas_by_interval🟢
Create download taskTiktokDownloadercreate_download_task🟢
Handle download taskTiktokDownloaderhandle_download🟢
Create stream download taskTiktokDownloadercreate_stream_tasks🟢
Handle stream download taskTiktokDownloaderhandle_stream🟢

💡 Tip

  • Pagination parameters are included in the response from the previous request, making it easy to filter results using the built-in filter.
  • All APIs with pagination use asynchronous generators, requiring iteration with async for for automatic pagination handling.
  • If max_counts is set to None or omitted, all available video data will be fetched.
  • These APIs can be easily integrated into backend frameworks like FastAPI, Flask, and Django.
  • Using a logged-in cookie allows bypassing privacy restrictions, such as private videos, profile, likes, and favorites.

Handler Interface List

Single Video Data 🟢

Asynchronous method to retrieve a single video.

ParameterTypeDescription
aweme_idstrVideo ID
ReturnTypeDescription
video_datadictDictionary containing video data, including video ID, caption, author nickname, etc.
py
import asyncio
from f2.apps.tiktok.handler import TiktokHandler

kwargs = {
    "headers": {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36 Edg/130.0.0.0",
        "Referer": "https://www.tiktok.com/",
    },
    "proxies": {"http://": None, "https://": None},
    "cookie": "YOUR_COOKIE_HERE",
}


async def main():
    video = await TiktokHandler(kwargs).fetch_one_video(itemId="7095819783324601605")
    print("=================_to_raw================")
    print(video._to_raw())
    # print("=================_to_dict================")
    # print(video._to_dict())
    # print("=================_to_list================")
    # print(video._to_list())


if __name__ == "__main__":
    asyncio.run(main())

User Published Videos 🟢

Asynchronous method to retrieve a list of videos published by a user.

ParameterTypeDescription
secUidstrUser ID
cursorintPage number, default is 0
page_countsintNumber of pages, default is 20
max_countsintMaximum number of pages, default is None
ReturnTypeDescription
aweme_datadictDictionary containing video data, including video ID, caption, author nickname, page number, etc.
py
import asyncio
from f2.apps.tiktok.handler import TiktokHandler
from f2.apps.tiktok.utils import SecUserIdFetcher


kwargs = {
    "headers": {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36 Edg/130.0.0.0",
        "Referer": "https://www.tiktok.com/",
    },
    "proxies": {"http://": None, "https://": None},
    "timeout": 10,
    "cookie": "YOUR_COOKIE_HERE",
}


async def main():
    secUid = await SecUserIdFetcher.get_secuid("https://www.tiktok.com/@vantoan___")

    async for aweme_data_list in TiktokHandler(kwargs).fetch_user_post_videos(
        secUid, 0, 0, 10, 20
    ):
        print("=================_to_raw================")
        print(aweme_data_list._to_raw())
        # print("=================_to_dict===============")
        # print(aweme_data_list._to_dict())
        # print("=================_to_list===============")
        # print(aweme_data_list._to_list())


if __name__ == "__main__":
    asyncio.run(main())

User Liked Videos 🟢

Asynchronous method to retrieve a list of videos liked by a specified user. The like list must be public.

ParameterTypeDescription
secUidstrUser ID
cursorintPage number, default is 0
page_countsintNumber of pages, default is 20
max_countsintMaximum number of pages, default is None
ReturnTypeDescription
aweme_datadictDictionary containing video data, including video ID, caption, author nickname, page number, etc.
py
import asyncio
from f2.apps.tiktok.handler import TiktokHandler
from f2.apps.tiktok.utils import SecUserIdFetcher

kwargs = {
    "headers": {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36 Edg/130.0.0.0",
        "Referer": "https://www.tiktok.com/",
    },
    "proxies": {"http://": None, "https://": None},
    "timeout": 10,
    "cookie": "YOUR_COOKIE_HERE",
}


async def main():
    secUid = await SecUserIdFetcher.get_secuid(
        "YOUR_HOME_PAGE"
    )  # 替换开放喜欢列表的用户主页

    async for user_like_list in TiktokHandler(kwargs).fetch_user_like_videos(
        secUid, 0, 10, 20
    ):
        print("=================_to_raw================")
        print(user_like_list._to_raw())
        # print("=================_to_dict===============")
        # print(user_like_list._to_dict())
        # print("=================_to_list===============")
        # print(user_like_list._to_list())


if __name__ == "__main__":
    asyncio.run(main())

User Collected Videos 🟢

Asynchronous method to retrieve a list of videos collected by a specified user.

ParameterTypeDescription
secUidstrUser ID
cursorintPage number, default is 0
page_countsintNumber of pages, default is 20
max_countsintMaximum number of pages, default is None
ReturnTypeDescription
aweme_datadictDictionary containing video data, including video ID, caption, author nickname, page number, etc.
py
import asyncio
from f2.apps.tiktok.handler import TiktokHandler
from f2.apps.tiktok.utils import SecUserIdFetcher

kwargs = {
    "headers": {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36 Edg/130.0.0.0",
        "Referer": "https://www.tiktok.com/",
    },
    "proxies": {"http://": None, "https://": None},
    "timeout": 10,
    "cookie": "YOUR_COOKIE_HERE",
}


async def main():
    secUid = await SecUserIdFetcher.get_secuid(
        "YOUR_HOME_PAGE"
    )  # 替换开放收藏列表的用户主页

    async for collect_list in TiktokHandler(kwargs).fetch_user_collect_videos(
        secUid, 0, 10, 20
    ):
        print("=================_to_raw================")
        print(collect_list._to_raw())
        # print("=================_to_dict===============")
        # print(collect_list._to_dict())
        # print("=================_to_list===============")
        # print(collect_list._to_list())


if __name__ == "__main__":
    asyncio.run(main())

User Playlist Videos 🟢

Asynchronous method to retrieve a list of videos from a specified user's playlist.

ParameterTypeDescription
secUidstrCollection ID
cursorintPage number, default is 0
page_countsintNumber of pages, default is 20
ReturnTypeDescription
aweme_datadictDictionary containing video data, including video ID, caption, author nickname, page number, etc.
py
import asyncio
from f2.apps.tiktok.handler import TiktokHandler
from f2.apps.tiktok.utils import SecUserIdFetcher


kwargs = {
    "headers": {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36 Edg/130.0.0.0",
        "Referer": "https://www.tiktok.com/",
    },
    "proxies": {"http://": None, "https://": None},
    "cookie": "YOUR_COOKIE_HERE",
}


async def main():
    secUid = await SecUserIdFetcher.get_secuid("https://www.tiktok.com/@vantoan___")
    playlist = await TiktokHandler(kwargs).fetch_play_list(secUid, 0, 30)
    print("=================_to_raw================")
    print(playlist._to_raw())
    # print("=================_to_dict===============")
    # print(aweme_data_list._to_dict())


if __name__ == "__main__":
    asyncio.run(main())

User Collection Videos 🟢

Asynchronous method to retrieve a list of videos from a specified user collection. The mix_id for all collection videos remains the same and can be retrieved from the single video data interface.

ParameterTypeDescription
mixIdstrCollection ID
cursorintPage number, default is 0
page_countsintNumber of pages, default is 20
max_countsintMaximum number of pages, default is None
ReturnTypeDescription
aweme_datadictDictionary containing video data, including video ID, caption, author nickname, page number, etc.
py
import asyncio
from f2.apps.tiktok.handler import TiktokHandler
from f2.apps.tiktok.utils import SecUserIdFetcher


kwargs = {
    "headers": {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36 Edg/130.0.0.0",
        "Referer": "https://www.tiktok.com/",
    },
    "proxies": {"http://": None, "https://": None},
    "timeout": 10,
    "cookie": "YOUR_COOKIE_HERE",
}


async def main():
    secUid = await SecUserIdFetcher.get_secuid("https://www.tiktok.com/@vantoan___")
    playlist = await TiktokHandler(kwargs).fetch_play_list(
        secUid,
        cursor=0,
        page_counts=20,
    )

    for mixId in playlist._to_dict().get("mixId", []):
        async for user_mix_list in TiktokHandler(kwargs).fetch_user_mix_videos(
            mixId,
            cursor=0,
            page_counts=20,
            max_counts=20,
        ):
            print("=================_to_raw================")
            print(user_mix_list._to_raw())
            # print("=================_to_dict===============")
            # print(user_mix_list._to_dict())
            # print("=================_to_list===============")
            # print(user_mix_list._to_list())


if __name__ == "__main__":
    asyncio.run(main())

Note

Multiple playlists may contain multiple mix_id values. Use the select_playlist method to return the index of the user-selected collection.

py
import asyncio
from f2.apps.tiktok.handler import TiktokHandler


kwargs = {
    "headers": {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36 Edg/130.0.0.0",
        "Referer": "https://www.tiktok.com/",
    },
    "proxies": {"http://": None, "https://": None},
    "timeout": 10,
    "cookie": "YOUR_COOKIE_HERE",
}


async def main():
    secUid = await SecUserIdFetcher.get_secuid("https://www.tiktok.com/@vantoan___")
    playlist = await TiktokHandler(kwargs).fetch_play_list(secUid)

    selected_index = await TiktokHandler(kwargs).select_playlist(
        playlist
    )  
    if selected_index != 0:  
        mixId = playlist.get("mixId", [])[selected_index - 1]  

        async for aweme_data_list in TiktokHandler(kwargs).fetch_user_mix_videos(mixId):
            print(aweme_data_list._to_raw())
            # print("=================_to_dict===============")
            # print(aweme_data_list._to_dict())
            # print("=================_to_list===============")
            # print(aweme_data_list._to_list())


if __name__ == "__main__":
    asyncio.run(main())

User Profile 🟢

Asynchronous method to retrieve a specified user's profile information. The data from Filter cannot be parsed directly; use custom _to_dict or _to_list methods.

ParameterTypeDescription
secUidstrUser ID
uniqueIdstrUser ID
ReturnTypeDescription
UserProfileFiltermodelCustom interface data filter
py
import asyncio
from f2.apps.tiktok.handler import TiktokHandler


kwargs = {
    "headers": {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36 Edg/130.0.0.0",
        "Referer": "https://www.tiktok.com/",
    },
    "proxies": {"http://": None, "https://": None},
    "cookie": "YOUR_COOKIE_HERE",
}


async def main():
    secUid = (
        "MS4wLjABAAAAQhcYf_TjRKUku-aF8oqngAfzrYksgGLRz8CKMciBFdfR54HQu3qGs-WoJ-KO7hO8"
    )
    uniqueId = "vantoan___"
    user = await TiktokHandler(kwargs).fetch_user_profile(secUid=secUid)
    print("=================_to_raw================")
    print(user._to_raw())
    # print("=================_to_dict===============")
    # print(user._to_dict())

    user = await TiktokHandler(kwargs).fetch_user_profile(uniqueId=uniqueId)
    print("=================_to_raw================")
    print(user._to_raw())
    # print("=================_to_dict===============")
    # print(user._to_dict())


if __name__ == "__main__":
    asyncio.run(main())

💡 Hint

TikTok's user interface supports both secUid and uniqueId as user IDs.

Create User Record and Directory 🟢

Asynchronous method to fetch or create user data while creating a user directory.

ParameterTypeDescription
kwargsdictcli dictionary data, requires the path parameter
secUidstrUser ID
dbAsyncUserDBUser database
ReturnTypeDescription
user_pathPathUser directory path object
py
import asyncio
from f2.apps.tiktok.handler import TiktokHandler
from f2.apps.tiktok.db import AsyncUserDB

kwargs = {
    "headers": {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36 Edg/130.0.0.0",
        "Referer": "https://www.tiktok.com/",
    },
    "proxies": {"http://": None, "https://": None},
    "cookie": "YOUR_COOKIE_HERE",
    "path": "Download",
}


async def main():
    async with AsyncUserDB("tiktok_users.db") as audb:
        secUid = "MS4wLjABAAAAQhcYf_TjRKUku-aF8oqngAfzrYksgGLRz8CKMciBFdfR54HQu3qGs-WoJ-KO7hO8"
        print(
            await TiktokHandler(kwargs).get_or_add_user_data(
                kwargs=kwargs, secUid=secUid, db=audb
            )
        )


if __name__ == "__main__":
    asyncio.run(main())

💡 Hint

This is an interface for cli mode. Developers can define their own functions to create user directories.

Create Video Download Record 🟢

Asynchronous method to fetch or create video data while creating a video directory.

ParameterTypeDescription
aweme_datadictVideo data dictionary
dbAsyncVideoDBVideo database
ignore_fieldslistList of fields to ignore
ReturnTypeDescription
NoneNoneNone
py
import asyncio
from f2.apps.tiktok.handler import TiktokHandler
from f2.apps.tiktok.db import AsyncVideoDB


# 需要忽略的字段(需过滤掉有时效性的字段)
ignore_fields = ["video_play_addr", "images", "video_bit_rate", "cover"]

kwargs = {
    "headers": {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36 Edg/130.0.0.0",
        "Referer": "https://www.tiktok.com/",
    },
    "proxies": {"http://": None, "https://": None},
    "cookie": "YOUR_COOKIE_HERE",
}


async def main():
    aweme_data = await TiktokHandler(kwargs).fetch_one_video(
        itemId="7095819783324601605"
    )
    async with AsyncVideoDB("tiktok_videos.db") as avdb:
        await TiktokHandler(kwargs).get_or_add_video_data(
            aweme_data._to_dict(), avdb, ignore_fields
        )


if __name__ == "__main__":
    asyncio.run(main())

Utils Interface List

Manage Client Configuration 🟢

Class method to manage client configuration.

ParameterTypeDescription
NoneNoneNone
ReturnTypeDescription
Config ValueAnyConfiguration file value
py
from f2.apps.tiktok.utils import ClientConfManager

if __name__ == "__main__":
    print("Client Configuration:")
    print(ClientConfManager.client())

    print("Client Configuration version:")
    print(ClientConfManager.conf_version())

    print("Client Configuration user-agent:")
    print(ClientConfManager.user_agent())

Generate Real msToken 🟢

Class method to generate a real msToken. Returns a fake value in case of errors.

ParameterTypeDescription
NoneNoneNone
ReturnTypeDescription
msTokenstrReal msToken
py
from f2.apps.tiktok.utils import TokenManager

if __name__ == "__main__":
    print("tiktok real msToken:", TokenManager.gen_real_msToken())

Generate Fake msToken 🟢

Class method to generate a randomly faked msToken. The length of msToken varies across endpoints.

ParameterTypeDescription
NoneNoneNone
ReturnTypeDescription
msTokenstrFake msToken
py
from f2.apps.tiktok.utils import TokenManager

if __name__ == "__main__":
    print("tiktok fake msToken:", TokenManager.gen_false_msToken())

💡 Hint

The default length is 126 characters. You can also call from f2.utils.utils import gen_random_str to generate a fake msToken of a different length.

Generate ttwid 🟢

Class method to generate ttwid, which is required for certain requests.

ParameterTypeDescription
NoneNoneNone
ReturnTypeDescription
ttwidstrttwid parameter
py
from f2.apps.tiktok.utils import TokenManager

if __name__ == "__main__":
    print("tiktok ttwid:", TokenManager.gen_ttwid())

⚠️ Warning

The ttwid value in the configuration file is a new ttwid cookie. If it expires, replace it with a new ttwid value.

Generate odin_tt 🟢

Class method for generating odin_tt, required for some requests.

ParameterTypeDescription
NoneNoneNone
ReturnTypeDescription
odin_ttstrThe odin_tt parameter
py
from f2.apps.tiktok.utils import TokenManager

if __name__ == "__main__":
    print("tiktok odin_tt:", TokenManager.gen_odin_tt())

⚠️ Note

The odin_tt parameter in the configuration file is fixed and cannot be changed.

Generate Xb Parameter Using API Endpoint 🟢

Class method for directly generating the Xbogus parameter using an API endpoint. Some APIs do not require validation.

ParameterTypeDescription
endpointstrAPI endpoint
ReturnTypeDescription
final_endpointstrThe complete API URL with Xbogus parameter
py
# 使用接口地址直接生成请求链接
from f2.apps.tiktok.utils import XBogusManager


def main():
    user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36 Edg/130.0.0.0"
    test_endpoint = "aid=1988&app_language=zh-Hans&app_name=tiktok_web&browser_platform=Win32&browser_version=5.0%20%28Windows%20NT%2010.0%3B%20Win64%3B%20x64%29%20AppleWebKit%2F537.36%20%28KHTML%2C%20like%20Gecko%29%20Chrome%2F120.0.0.0%20Safari%2F537.36&channel=tiktok_web&cookie_enabled=true&count=16&coverFormat=2&device_id=7306060721837852167&device_platform=web_pc&itemID=7294298719665622305"
    return XBogusManager.str_2_endpoint(user_agent, test_endpoint)


if __name__ == "__main__":
    print(main())

Generate Xb Parameter Using API Model 🟢

Class method for generating the Xbogus parameter using different API data models. Some APIs do not require validation.

ParameterTypeDescription
endpointstrAPI endpoint
paramsdictRequest parameters
ReturnTypeDescription
final_endpointstrThe complete API URL with Xbogus parameter

To generate an endpoint using a model, create a model object and call the model_2_endpoint method.

py
# 使用用户信息模型生成请求链接
import asyncio
from f2.apps.tiktok.api import TiktokAPIEndpoints as tkendpoint
from f2.apps.tiktok.model import UserProfile
from f2.apps.tiktok.utils import XBogusManager


async def gen_user_profile(params: UserProfile):
    return XBogusManager.model_2_endpoint(tkendpoint.USER_DETAIL, params.model_dump())


async def main():
    secUid = (
        "MS4wLjABAAAAQhcYf_TjRKUku-aF8oqngAfzrYksgGLRz8CKMciBFdfR54HQu3qGs-WoJ-KO7hO8"
    )
    params = UserProfile(secUid=secUid)
    return await gen_user_profile(params)


if __name__ == "__main__":
    print(asyncio.run(main()))

Data collection is also possible using a crawler engine with a filter.

py
# 使用用户信息模型生成请求链接,请求接口并使用自定义过滤器输出所需接口数据
import asyncio
from f2.apps.tiktok.api import TiktokAPIEndpoints as tkendpoint
from f2.apps.tiktok.crawler import TiktokCrawler
from f2.apps.tiktok.model import UserProfile
from f2.apps.tiktok.filter import UserProfileFilter
from f2.apps.tiktok.utils import XBogusManager

kwargs = {
    "headers": {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36 Edg/130.0.0.0",
        "Referer": "https://www.tiktok.com/",
    },
    "proxies": {"http://": None, "https://": None},
    "cookie": "YOUR_COOKIE_HERE",
}


async def main():
    async with TiktokCrawler(kwargs) as crawler:
        secUid = "MS4wLjABAAAAQhcYf_TjRKUku-aF8oqngAfzrYksgGLRz8CKMciBFdfR54HQu3qGs-WoJ-KO7hO8"
        params = UserProfile(secUid=secUid)
        response = await crawler.fetch_user_profile(params)
        user = UserProfileFilter(response)
        # return user # user为UserProfileFilter对象,需要调用_to_dict()方法转为字典格式
        return user._to_dict()


if __name__ == "__main__":
    print(asyncio.run(main()))

For more advanced use cases, call fetch_user_profile from the handler interface.

Extract Single User ID 🟢

Class method to extract a single user ID.

ParameterTypeDescription
urlstrUser profile URL
ReturnTypeDescription
sec_uidstrUser ID
py
import asyncio
from f2.apps.tiktok.utils import SecUserIdFetcher


async def main():
    raw_url = "https://www.tiktok.com/@vantoan___"
    # 对于单个URL
    return await SecUserIdFetcher.get_secuid(raw_url)


if __name__ == "__main__":
    print(asyncio.run(main()))

Extract Multiple User IDs 🟢

Class method to extract multiple user IDs.

ParameterTypeDescription
urlslistList of user profile URLs
ReturnTypeDescription
secuidslistList of user IDs
py
import asyncio
from f2.apps.tiktok.utils import SecUserIdFetcher
from f2.utils.utils import extract_valid_urls


async def main():
    raw_urls = [
        "https://www.tiktok.com/@vantoan___/",
        "https://www.tiktok.com/@vantoan___?is_from_webapp=1&sender_device=pc",
        # "https://vt.tiktok.com/xxxxxxxxxx/"
    ]

    # 提取有效URL
    urls = extract_valid_urls(raw_urls)

    # 对于URL列表
    return await SecUserIdFetcher.get_all_secuid(urls)


if __name__ == "__main__":
    print(asyncio.run(main()))

Extract Single Unique User ID 🟢

Class method to extract a single unique user ID.

ParameterTypeDescription
urlstrUser profile URL
ReturnTypeDescription
unique_idstrUnique user ID
py
import asyncio
from f2.apps.tiktok.utils import SecUserIdFetcher


async def main():
    raw_url = "https://www.tiktok.com/@vantoan___"
    # 对于单个URL
    return await SecUserIdFetcher.get_uniqueid(raw_url)


if __name__ == "__main__":
    print(asyncio.run(main()))

Extract Multiple Unique User IDs 🟢

Class method to extract multiple unique user IDs.

ParameterTypeDescription
urlslistList of user profile URLs
ReturnTypeDescription
unique_idslistList of unique user IDs
py
import asyncio
from f2.apps.tiktok.utils import SecUserIdFetcher
from f2.utils.utils import extract_valid_urls


async def main():
    raw_urls = [
        "https://www.tiktok.com/@vantoan___/",
        "https://www.tiktok.com/@vantoan___?is_from_webapp=1&sender_device=pc",
        # "https://vt.tiktok.com/xxxxxxxxxx/"
    ]

    # 提取有效URL
    urls = extract_valid_urls(raw_urls)

    # 对于URL列表
    return await SecUserIdFetcher.get_all_uniqueid(urls)


if __name__ == "__main__":
    print(asyncio.run(main()))

Extract Single Video ID 🟢

Class method to extract a single video ID.

ParameterTypeDescription
urlstrVideo URL
ReturnTypeDescription
aweme_idstrVideo ID
py
import asyncio
from f2.apps.tiktok.utils import AwemeIdFetcher


async def main():
    raw_url = "https://www.tiktok.com/@vantoan___/video/7283528426256911649"
    # 支持短链解析但其具有时效性,故不举例
    return await AwemeIdFetcher.get_aweme_id(raw_url)


if __name__ == "__main__":
    print(asyncio.run(main()))

Extract Multiple Video IDs 🟢

Class method to extract multiple video IDs.

ParameterTypeDescription
urlslistList of video URLs
ReturnTypeDescription
aweme_idslistList of video IDs
py
import asyncio
from f2.apps.tiktok.utils import AwemeIdFetcher
from f2.utils.utils import extract_valid_urls


async def main():
    raw_urls = [
        "https://www.tiktok.com/@vantoan___/video/7316948869764484384",
        "https://www.tiktok.com/@vantoan___/video/7316948869764484384?is_from_webapp=1&sender_device=pc&web_id=7306060721837852167",
        # 支持短链解析但其具有时效性,故不举例
    ]

    # 提取有效URL
    urls = extract_valid_urls(raw_urls)

    # 对于URL列表
    return await AwemeIdFetcher.get_all_aweme_id(urls)


if __name__ == "__main__":
    print(asyncio.run(main()))

💡 Tip

Both web and app-shared links are valid.

Generate Device ID 🟢

Class method to generate deviceId and tt_chain_token.

ParameterTypeDescription
full_cookieboolWhether to return the full cookie
ReturnTypeDescription
device_iddictDictionary containing device ID and cookie
py
import asyncio
from f2.apps.tiktok.utils import DeviceIdManager


async def main():
    device_id = await DeviceIdManager.gen_device_id()
    print("device_id:", device_id.get("deviceId"), "cookie:", device_id.get("cookie"))
    device_id = await DeviceIdManager.gen_device_id(full_cookie=True)
    print("device_id:", device_id.get("deviceId"), "cookie:", device_id.get("cookie"))


if __name__ == "__main__":
    asyncio.run(main())

Generate Multiple Device IDs 🟢

Class method to generate multiple deviceId and tt_chain_token values.

ParameterTypeDescription
countintNumber of device IDs
full_cookieboolWhether to return the full cookie
ReturnTypeDescription
device_idsdictDictionary containing multiple device IDs and cookies
py
import asyncio
from f2.apps.tiktok.utils import DeviceIdManager


async def main():
    device_ids = await DeviceIdManager.gen_device_ids(3)
    print(
        "device_ids:", device_ids.get("deviceId"), "cookies:", device_ids.get("cookie")
    )
    device_ids = await DeviceIdManager.gen_device_ids(3, full_cookie=True)
    print(
        "device_ids:", device_ids.get("deviceId"), "cookies:", device_ids.get("cookie")
    )


if __name__ == "__main__":
    asyncio.run(main())

💡 Tip

deviceId and tt_chain_token parameters are bound to the configuration file and affect video access. A 403 error usually indicates an issue with these parameters.

Global Filename Formatting 🟢

Formats filenames globally based on the configuration file.

📄 Filename Formatting Rules
  • Windows: Filename length is limited to 255 characters (or 32,767 with long filename support).
  • Unix: Filename length is limited to 255 characters.
  • Truncates to 20 characters, plus suffix, to stay within the 255 limit.
  • Developers can customize custom_fields to define their own filenames.
ParameterTypeDescription
naming_templatestrFilename template
aweme_datadictVideo metadata
custom_fieldsdictCustom fields for replacing default values
ReturnTypeDescription
file_namestrFormatted filename
py
import asyncio
from f2.apps.tiktok.handler import TiktokHandler
from f2.apps.tiktok.utils import format_file_name

kwargs = {
    "headers": {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36 Edg/130.0.0.0",
        "Referer": "https://www.tiktok.com/",
    },
    "proxies": {"http://": None, "https://": None},
    "cookie": "YOUR_COOKIE_HERE",
    "naming": "{create}_{desc}_{aweme_id}",
}


async def main():
    # 单作品的数据
    aweme_data = await TiktokHandler(kwargs).fetch_one_video("7316948869764484384")
    # 格式化后的文件名
    print(format_file_name(kwargs.get("naming"), aweme_data._to_dict()) + "_video")

    # 文件名模板
    kwargs = {
        # ...
        "naming": "{create}_{desc}_{aweme_id}_{location}",
        # ...
    }
    # 用户自定义字段
    custom_fields = {"location": "New York"}
    # 格式化后的自定义文件名
    print(
        format_file_name(kwargs.get("naming"), aweme_data._to_dict(), custom_fields)
        + "_video"
    )


if __name__ == "__main__":
    asyncio.run(main())

Create User Directory 🟢

Creates a user directory if it does not already exist.

📂 User Directory Structure

If no path is specified in the configuration file, the default is Download. Both absolute and relative paths are supported.

bash
├── Download
   ├── tiktok
   ├── post
   ├── user_nickname
   ├── 2023-12-31_23-59-59_desc
   ├── 2023-12-31_23-59-59_desc-video.mp4
   ├── 2023-12-31_23-59-59_desc-desc.txt
   └── ......
   ├── like
   ├── ...
ParameterTypeDescription
kwargsdictcli configuration file
nicknameUnion[str, int]User nickname
ReturnTypeDescription
user_pathPathUser directory path object
py
from f2.apps.tiktok.utils import create_user_folder


kwargs = {
    "headers": {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36 Edg/130.0.0.0",
        "Referer": "https://www.tiktok.com/",
    },
    "proxies": {"http://": None, "https://": None},
    "cookie": "YOUR_COOKIE_HERE",
    "path": "Download",
    "mode": "post",
}


if __name__ == "__main__":
    current_nickname = "New Nickname"
    print(create_user_folder(kwargs, current_nickname))
    # X:\......\Download\tiktok\post\New Nickname

Rename User Directory 🟢

Used to rename a user directory.

ParameterTypeDescription
old_pathPathOld user directory path object
new_nicknamestrNew user nickname
ReturnTypeDescription
new_pathPathNew user directory path object
py
import asyncio
from f2.apps.tiktok.db import AsyncUserDB
from f2.apps.tiktok.utils import rename_user_folder
from f2.apps.tiktok.handler import TiktokHandler


kwargs = {
    "headers": {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36 Edg/130.0.0.0",
        "Referer": "https://www.tiktok.com/",
    },
    "proxies": {"http://": None, "https://": None},
    "cookie": "YOUR_COOKIE_HERE",
    "path": "Download",
    "mode": "post",
}


async def main():
    sec_user_id = (
        "MS4wLjABAAAAQhcYf_TjRKUku-aF8oqngAfzrYksgGLRz8CKMciBFdfR54HQu3qGs-WoJ-KO7hO8"
    )
    async with AsyncUserDB("tiktok_users.db") as audb:
        local_user_path = await TiktokHandler(kwargs).get_or_add_user_data(
            sec_user_id, audb
        )
    print(local_user_path)
    # X:\......\Download\tiktok\post\vantoan___

    current_nickname = "New Nickname"
    new_user_path = rename_user_folder(local_user_path, current_nickname)
    print(new_user_path)
    # X:\......\Download\tiktok\post\New Nickname


if __name__ == "__main__":
    asyncio.run(main())

💡 Note

If the directory does not exist, it will be created before renaming.

Create or Rename User Directory 🟢

Used to create or rename a user directory. This is a combination of the two interfaces above.

ParameterTypeDescription
kwargsdictcli configuration file
local_user_datadictLocal user data
current_nicknamestrCurrent user nickname
ReturnTypeDescription
user_pathPathUser directory path object

💡 Note

This interface effectively resolves the issue of duplicate downloads when a user changes their nickname. It is integrated into the get_or_add_user_data method in the handler interface, so developers can call the handler’s data interface directly without worrying about this issue.

crawler Interface

User Profile API Endpoint 🟢

API endpoint for retrieving user profile information.

ParameterTypeDescription
UserProfilemodelUser profile API model
ReturnTypeDescription
_fetch_get_jsondictMethod to fetch user profile information

User Posts API Endpoint 🟢

API endpoint for retrieving a user's posted videos.

ParameterTypeDescription
UserPostmodelUser post API model
ReturnTypeDescription
_fetch_get_jsondictMethod to fetch user posts

Liked Posts API Endpoint 🟢

API endpoint for retrieving a user's liked videos.

ParameterTypeDescription
UserLikemodelUser liked posts API model
ReturnTypeDescription
_fetch_get_jsondictMethod to fetch liked posts

Collected Posts API Endpoint 🟢

API endpoint for retrieving a user's collected videos.

ParameterTypeDescription
UserCollectmodelUser collected posts API model
ReturnTypeDescription
_fetch_get_jsondictMethod to fetch collected posts

Playlist API Endpoint 🟢

API endpoint for retrieving a user's playlist.

ParameterTypeDescription
UserPlayListmodelUser playlist API model
ReturnTypeDescription
_fetch_get_jsondictMethod to fetch user playlists

Playlist Videos API Endpoint 🟢

API endpoint for retrieving videos in a user's playlist.

ParameterTypeDescription
UserMixmodelUser playlist videos API model
ReturnTypeDescription
_fetch_get_jsondictMethod to fetch playlist videos

Post Detail API Endpoint 🟢

API endpoint for retrieving post details.

ParameterTypeDescription
PostDetailmodelPost detail API model
ReturnTypeDescription
_fetch_get_jsondictMethod to fetch post details

Post Comments API Endpoint 🟢

API endpoint for retrieving post comments.

ParameterTypeDescription
PostCommentmodelPost comments API model
ReturnTypeDescription
_fetch_get_jsondictMethod to fetch post comments

API endpoint for retrieving recommended posts.

ParameterTypeDescription
PostDetailmodelRecommended posts API model
ReturnTypeDescription
_fetch_get_jsondictMethod to fetch recommended posts

Search Posts API Endpoint 🟢

API endpoint for retrieving search results for posts.

ParameterTypeDescription
PostSearchmodelSearch posts API model
ReturnTypeDescription
_fetch_get_jsondictMethod to fetch search results

User Live API Endpoint 🟢

API endpoint for retrieving a user's live stream.

ParameterTypeDescription
UserLivemodelUser live API model
ReturnTypeDescription
_fetch_get_jsondictMethod to fetch user live streams

Check Live Status API Endpoint 🟢

API endpoint for checking if a user is live.

ParameterTypeDescription
CheckLiveAlivemodelCheck live status API model
ReturnTypeDescription
_fetch_get_jsondictMethod to check live status

Live Danmaku Initialization API Endpoint 🟢

API endpoint for initializing live chat messages (danmaku).

ParameterTypeDescription
LiveImFetchmodelLive chat initialization API model
ReturnTypeDescription
payload_packagedictData package for live chat initialization

💡 Note

  • If no filter is needed, you can call the crawler API directly, which will return the data dictionary.

dl Interface

Released under the Apache-2.0 license.