TikTok API : How to Post and Get Analytics Using the TikTok API
It is impossible to ignore the impact of TikTok. It has over 1.5 billion monthly active users. Each of those users spends over 6 hours per week on the platform watching the videos.
This platform has expanded far beyond its origins in dance videos, now encompassing a diverse range of content across various subjects. Its support for multiple video formats – vertical, horizontal, and square – underscores its adaptability and broad appeal.
For businesses and content creators, TikTok represents an untapped opportunity for growth and audience engagement. Utilizing TikTok’s Application Programming Interface (API) for video distribution is a smartc move for those already producing video content. This article provides a comprehensive guide on leveraging the TikTok API to maximize your content’s reach and impact on this influential platform.
Why TikTok is Important for Your Business
Recent surveys have shown TikTok reaches over 50% of the internet users in the United States above age 18. Those numbers are even higher for other countries. Those users are spending money on the platform too, as TikTok has just become the first non-gaming app to surpass $10 billion in consumer spending.
Those spending numbers are only going to increase because TikTok is now becoming an e-commerce site with the launch of TikTok Shops. This launch allows brands to reach customers right on the TikTok platform, complete with product pages, a shopping cart and a check-out experience. The TikTok Shop works for both digital and physical products.
Introduction to the TikTok API Landscape
TikTok includes a number of APIs, including: login, display, commercial content, research, and content posting – videos and photos. This blog post will focus on the video content posting API. TikTok published a Software Development Kit (SDK) for both Android and iOS.
The content posting TikTok API enables web and mobile applications to use the TikTok platform. The content posting API has 2 offerings:
- Direct Post – The method allows you to directly post to TikTok from your app. That includes the video, caption and hashtags.
- Upload – Other times, a user may only want to upload the video to TikTok and then finalize the posting of the video from within the TikTok app. Once the video is uploaded via the API, you will get a notification via the TikTok app that you have a new video to review and post.
Getting Ready to use the TikTok API
- Register and Create an App
- Sign in or Sign up to the TikTok for Developers Portal.
- Navigate to the “Manage Apps” section of your profile.
- Click “Connect an app” and enter the details:
- Click Confirm.
- Configure Settings
- Fill in all the desired details for the app including: icon, name, category, description, ToS URL, and Privacy Policy URL.
- Select which platform you are building. You can select Web and enter your URL.
- Click “Save changes”.
- Submit for review
- Click the “Submit for review” button.
- Enter a reason for submission.
- Click Submit.
- Status is now “Under review”, Wait for the response.
Your submission undergo an audit to verify compliance with the TikTok Terms of Service. This may take a few days to a few weeks and require further submissions such as a video of your app.
Get Permission From Your Users
Your app must request your users to let it operate their TikTok accounts. This is done using the OAuth 2.0 authorization code flow. After user authentication with TikTok and authorization of the app, it produces an access token per user that lets your application make API calls to operate user accounts on their behalf.
Since the authentication and authorization API documentation is comprehensive and accurate, we won’t repeat the steps here. But one thing to keep in mind:
- Access tokens expire every 24 hours but can be refreshed without user consent. Treat them like passwords and store them securely in your user database. See the TikTok Access Token documentation.
Upload Your First Video with the TikTok API
To Upload a video to share use the TikTok POST endpoint:
POST https://open.tiktokapis.com/v2/post/publish/inbox/video/init
The request body is a JSON object:
{
"source_info": {
"source": "PULL_FROM_URL",
"video_url": "https://url-to-your-video"
}
}
source
: There are 2 options for the source. UsePULL_FROM_URL
when the source video is located at a URL location. For local files useFILE_UPLOAD
with a video_size, chunk_size, and total_chunk_count need to be specified. See the TikTok API file upload docs for specifics.video_url:
the source URL of the video to be posted
Always add these two request headers:
Authorization: Bearer {access_token}
Content-Type: application/json
If the request succeeds, you get a 200 (OK) HTTP response and JSON:
{
"data": {
"publish_id": "v_inbox_url~v2.123456789"
},
"error": {
"code": "ok",
"message": "",
"log_id": "202312192248442CB9319E1FB30C1073F4"
}
}
The code using server-side Node.js with JavaScript:
const accessToken = USER-ACCESS-TOKEN;
const headers = {
'Authorization': `Bearer ${accessToken}`,
'Content-Type': 'application/json'
};
const params = {
"source_info": {
"source": "PULL_FROM_URL",
"video_url": "https://url-to-your-video"
}
};
const postResp = await fetch(
'https://open.tiktokapis.com/v2/post/publish/inbox/video/init', {
method: 'POST',
headers: headers,
body: JSON.stringify(params)
});
console.log(postResp.status);
if (postResp.ok) {
const publishId = postResp.json().data.publish_id;
console.log(publishId);
}
TikTok Pull URL Authorization
TikTok recently enhanced their security by requiring all pull URLs domains to be verified. This means you will need to register your domain with TikTok and verify ownership by adding a signature string to the domain’s DNS records.
As an alternative, you can directly upload a file to TikTok, which doesn’t require proof of ownership.
Getting the TIkTok Video Post Status
Even if you’ve successfully uploaded the video, it doesn’t mean the video was successfully published on TikTok – also where is the actual URL to the video?
You’ll need to make one more call in the process to get the video post status and other metadata. Taking the publish_id returned from the post call:
curl --location 'https://open.tiktokapis.com/v2/post/publish/status/fetch/' \
--header 'Authorization: Bearer act.example12345Example12345Example' \
--header 'Content-Type: application/json; charset=UTF-8' \
--data '{
"publish_id": "v_pub_url~v2.123456789"
}'
When the video has completed processing, a PUBLISH_COMPLETE
will be returned from TikTok post video status endpoint:
{
"data": {
"status": "PUBLISH_COMPLETE",
"publicaly_available_post_id": ["2392k292932dkew93"],
"uploaded_bytes": 10000
}
}
Using the publicaly_available_post_id field
, construct a URL to the actual TikTok video, such as:
`https://www.tiktok.com/@${username}/video/${publicaly_available_post_id}`
TikTok videos take between 30 seconds and 2 minutes to complete processing, so you’ll likely need to make several calls. If the video is still processing you’ll receive a status of PROCESSING_UPLOAD
and if the post failed the status will be FAILED
.
Get Analytics for a Post with the TikTok API
TikTok reports analytics for posts by using the Query Videos endpoint of the Display API. It returns video details and can even be used to refresh a video’s cover image.
POST https://open.tiktokapis.com/v2/video/query/?fields=id,title,like_count,comment_count,share_count,view_count
fields
: a query parameter to specify what video details are being requested
The body of the request must include a list of video_ids
. A video_id
can be obtained from a Direct Post as opposed to an Upload Post. The post body looks like the following with up to 20 video_ids:
{
"filters": {
"video_ids": [
"1234123412345678567",
"1010102020203030303"
]
}
}
The data in the response will look like this:
{
"data":{
"videos":[
{
"title":"Video 1",
"id":"1234123412345678567",
"like_count":23,
"comment_count":3,
"share_count":1,
"view_count":356
},
{
"title":"Video 2",
"id":"1010102020203030303",
"like_count":23,
"comment_count":3,
"share_count":1,
"view_count":356
}
]
},
"error": {
"code":"ok",
"message":"",
"log_id":"20231299194722CBE87ED59D524E727021"
}
}
An Alternative Social Media API for TikTok
As an alternative to integrating the TikTok API directly and seeking approval, you can use Ayrshare’s social media API to publish posts, get advanced analytics, and manage TikTok comments.
Set Up Ayrshare
Get started with Ayrshare API in just three steps:
- Sign up on the Ayrshare platform.
- Get your API key in the dashboard under the API Key page.
- Decide where to post. For posting to your TikTok account, follow our account linking guide and connect TikTok.
You’re all set to use our APIs as shown in the examples below.
Post Your Videos on TikTok Using Python
Do you wish to automatically post on your TikTok page? For example, whenever your marketing folks upload a useful product demonstration video, you may want to share a short video clip promoting the demonstration.
To do so, just call the Ayrshare /post endpoint with your video in the mediaUrls parameter.
Note: You need a Premium or Business plan to post videos, but text posts and single-image posts are available for all plans.
import os
import requests
# Add the API key to your application’s environment.
# export AYRSHARE_API_KEY=YOUR-AYRSHARE-API-KEY
params = {
'post': 'The latest product demonstration video’,
'mediaUrls': ['https://TRAINING-VIDEO-LINK'],
'platforms': ['tiktok']
}
headers = {
'Authorization': f'Bearer {os.environ["AYRSHARE_API_KEY"]}',
'Content-Type': 'application/json'
}
r = requests.post('https://app.ayrshare.com/api/post',
json=params, headers=headers)
ret = r.json()
You’ll receive a JSON response:
{
"status": "success",
"errors": [],
"postIds": [{
"status": "success",
"platform": "tiktok",
"idShare": "video.678746453423652.nzLqBNMwp",
"id": "pending"
}],
“id": "JsuoeTwnUSncp",
“refId”: “34a87acb33af0909f416ac“,
"post": "The latest product demonstration video"
}
You can also use the Social API PyPi package to make the calls simpler, or one of our other social media SDK packages.
Get Analytics for Your Posts with Ayrshare
Using the /analytics endpoint, you can get insights on how a post is performing and present them to your users:
POST https://app.ayrshare.com/api/analytics/post
Ayrshare contains a lot of insights for TikTok Analytics of a post, some that are exclusive to Ayrshare such as demographic information:
...
"tiktok": {
"id": "7034682002927550598", // TikTok Social ID
"postUrl": "https://www.tiktok.com/@borneild/video/7034682002927550598?utm_campaign=tt4d_open_api&utm_source=awawnhyictaos7o",
"analytics": {
"audienceCountries": [ // Available 24-48 hours after posting
{
"country": "BM",
"percentage": 0.0036
},
{
"country": "MX",
"percentage": 0.0072
},
{
"country": "PH",
"percentage": 0.0036
},
{
"country": "US",
"percentage": 0.9819
},
{
"country": "VN",
"percentage": 0.0036
}
],
"averageTimeWatched": 5.6679, // Available 24-48 hours after posting.
"caption": "Scramble up ur name & I’ll try to guess it😍❤️ #foryoupage #petsoftiktok #aesthetic",
"comments": 23,
"created": "2022-08-09T15:08:22Z",
"embedUrl": "https://www.tiktok.com/embed/v2/7129893524253756713",
"fullVideoWatchedRate": 0.0866, // Percentage of views that completed watching the full video. Available 24-48 hours after posting.
"impressionSources": [ // Different sources for the impressions, ranked from the largest contribution to the smallest. Available 24-48 hours after posting.
{
"impression_source": "Search",
"percentage": 0.0217
},
{
"impression_source": "Sound",
"percentage": 0
},
{
"impression_source": "Follow",
"percentage": 0
},
{
"impression_source": "For You",
"percentage": 0.917
},
{
"impression_source": "Hashtag",
"percentage": 0
},
{
"impression_source": "Personal Profile",
"percentage": 0
}
],
"likes": 22,
"mediaType": "video",
"musicTitle": "♬ original sound - tiff", // If available
"musicUrl": "https://www.tiktok.com/music/original-sound-6689804660171082501?refer=embed", // if available
"name": "Mackly",
"postUrl": "https://www.tiktok.com/@tiktoktime/video/7129893524253756713?utm_campaign=tt4d_open_api&utm_source=awawnhyictaos7o7",
"reach": 252, // Total number of unique users who viewed the video. Available 24-48 hours after posting.
"shares": 0,
"shareUrl": "https://www.tiktok.com/@tiktoktime/video/7129893524253756713?utm_campaign=tt4d_open_api&utm_source=awawnhyictaos7o7", // Deprecated, user postUrl
"tags": [ // Tags included in the description
{
"tag": "#foryoupage",
"url": "https://www.tiktok.com/tag/foryoupage"
},
{
"tag": "#petsoftiktok",
"url": "https://www.tiktok.com/tag/petsoftiktok"
},
{
"tag": "#aesthetic",
"url": "https://www.tiktok.com/tag/aesthetic"
}
],
"thumbnailHeight": 576,
"thumbnailUrl": "https://p16-sign.tiktokcdn-us.com/obj/tos-useast5-p-0068-tx",
"thumbnailWidth": 1006,
"url": "https://www.tiktok.com/@tiktoktime",
"videoDuration": 13.984,
"videoViews": 34
},
"lastUpdated": "2022-04-23T18:44:29.778Z",
"nextUpdate": "2022-04-23T19:19:29.778Z"
}
...
See the analytics API for details.
Amplify Your Users’ B2B Marketing Using the TikTok API
This article introduced you to more effective B2B marketing using the posting capabilities of the TikTok APIs. For more social media API, read our articles on the best social media platform for attracting B2B clients and the top 10 social media APIs for developers.