How to send and receive statistics using the TikTok API

[ad_1]
It is impossible to ignore the impact of TikTok. It has more than 1.5 billion active users. Each of those users spends more than 6 hours a week on the platform watching videos.
The platform has grown far beyond its origins in dance videos, now covering a wide variety of content on a variety of topics. Its support for multiple video formats – vertical, horizontal, and square – underscores its versatility and broad appeal.
For businesses and content creators, TikTok represents an untapped opportunity for audience growth and engagement. Using TikTok’s Application Programming Interface (API) for video distribution is a smart move for those who already produce video content. This article provides a complete guide to using the TikTok API to increase your content’s reach and impact on this influential platform.
Why TikTok Is Important For Your Business
A recent survey showed that TikTok reaches more than 50% of Internet users in the United States over the age of 18. Those numbers are even higher in other countries. Those users are spending money on the platform as well, as TikTok recently became the first non-gaming app to surpass $10 billion in consumer spending.
Those spending numbers will grow because TikTok is now 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, shopping cart and checkout information. The TikTok Store serves both digital and physical products.
Introduction to 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 API for sending video content. TikTok has published a Software Development Kit (SDK) for both Android and iOS.
The TikTok API posts content that enables web and mobile apps to use the TikTok platform. The content posting API has 2 offerings:
- Direct Posts – The method allows you to send directly to TikTok from your application. That includes video, captions and hashtags.
- Upload it – In some cases, the user may only want to upload a video to TikTok and complete the video upload within the TikTok app. Once the video has been uploaded via the API, you will receive a notification through the TikTok app that you have a new video to review and upload.
Getting ready to use the TikTok API
- Register and Create an App
- Sign in or Register for the TikTok Developer Portal.
- Navigate to the “Manage apps” section of your profile.
- Click on “Connect application” 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.
- Choose which platform you are building. You can select Web and enter your URL.
- Click on “Save changes”.
- Submit for review
- Click the “Submit for Review” button.
- Enter the reason for submission.
- Click Submit.
- The status is now “Under Review”, Wait for a response.
Your submission is reviewed to ensure compliance with TikTok’s Terms of Service. This may take a few days to a few weeks and requires additional submissions such as a video of your application.
Get Consent From Your Users
Your app should ask your users to allow it to use their TikTok accounts. This is done using the OAuth 2.0 authorization code flow. After user authentication with TikTok and app authorization, it generates an access token for each user that allows your app to make API calls to use 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 remember:
- Access tokens expire every 24 hours but can be renewed without the user’s permission. 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
The request body is a JSON object:
{
"source_info": {
"source": "PULL_FROM_URL",
"video_url": "
}
}
source
: There are 2 source options. Use itPULL_FROM_URL
if the source video is in the URL field. To use local filesFILE_UPLOAD
with video_size, chunk_size, and total_value need to be specified. See the TikTok API file upload documentation for details.video_url:
the URL of the video source to be sent
Always add these two request headers:
Authorization: Bearer {access_token}
Content-Type: application/json
If the request is successful, you get a 200 (OK) HTTP and JSON response:
{
"data": {
"publish_id": "v_inbox_url~v2.123456789"
},
"error": {
"code": "ok",
"message": "",
"log_id": "202312192248442CB9319E1FB30C1073F4"
}
}
Code that uses 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": "
}
};
const postResp = await fetch(
'', {
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 has recently improved its security by requiring all download URL domains to be verified. This means you will need to register your domain with TikTok and verify ownership by adding a signature unit to the domain’s DNS records.
Alternatively, you can directly upload the file to TikTok, which does not require proof of ownership.
Finding the Status of a TikTok Video Post
Even if you have successfully uploaded a video, it does not mean that the video has been successfully published on TikTok – and where is the actual URL to the video?
You will need to make one more call to the program to get the video post status and other metadata. Taking the publish_id returned from the post call:
curl --location '
--header 'Authorization: Bearer act.example12345Example12345Example'
--header 'Content-Type: application/json; charset=UTF-8'
--data '{
"publish_id": "v_pub_url~v2.123456789"
}'
Once the video is finished processing, a PUBLISH_COMPLETE
will be returned to the TikTok post video endpoint:
{
"data": {
"status": "PUBLISH_COMPLETE",
"publicaly_available_post_id": ["2392k292932dkew93"],
"uploaded_bytes": 10000
}
}
Using the publicaly_available_post_id field
create a URL to the original TikTok video, like:
`
TikTok videos take between 30 seconds and 2 minutes to complete processing, so you’ll probably need to make a few calls. If the video is still being processed you will get a status that says PROCESSING_UPLOAD
and if the post failed the status will be FAILED
.
Get Post Analytics with TikTok API
TikTok reports post statistics by using the Query Videos endpoint of the Display API. It restores the video details and can even be used to update the video cover image.
POST
fields
: query parameter to specify what video details are requested
The body of the application must include a list of video_ids
. A video_id
can be found in Direct Posts as opposed to Loaded posts. The post body looks like this with up to 20 video_ids:
{
"filters": {
"video_ids": [
"1234123412345678567",
"1010102020203030303"
]
}
}
The data in 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"
}
}
Alternative Social Media API for TikTok
As an alternative to integrating the TikTok API directly and seeking approval, you can use the Ayrshare social media API to publish posts, get advanced analytics, and manage TikTok comments.
Set up Ayrshare
Get started with the Ayrshare API in just three steps:
- Register on the Ayrshare platform.
- Find your API key on 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 are ready to use our APIs as shown in the examples below.
Upload your videos to TikTok using Python
Do you wish to post automatically on your TikTok page? For example, whenever your advertisers upload a helpful product demonstration video, you may want to share a video clip that promotes the demonstration.
To do so, simply 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 on 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': ['
'platforms': ['tiktok']
}
headers = {
'Authorization': f'Bearer {os.environ["AYRSHARE_API_KEY"]}',
'Content-Type': 'application/json'
}
r = requests.post('
json=params, headers=headers)
ret = r.json()
You will get 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 calls easier, or one of our social media SDK packages.
Get statistics for your posts with Ayrshare
Using the /analytics endpoint, you can get insights on how posts are performing and present them to your users:
POST
Ayrshare contains many TikTok Analytics posts, some of which are only available on Ayrshare such as demographic information:
...
"tiktok": {
"id": "7034682002927550598", // TikTok Social ID
"postUrl": "
"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": "
"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": " // if available
"name": "Mackly",
"postUrl": "
"reach": 252, // Total number of unique users who viewed the video. Available 24-48 hours after posting.
"shares": 0,
"shareUrl": " // Deprecated, user postUrl
"tags": [ // Tags included in the description
{
"tag": "#foryoupage",
"url": "
},
{
"tag": "#petsoftiktok",
"url": "
},
{
"tag": "#aesthetic",
"url": "
}
],
"thumbnailHeight": 576,
"thumbnailUrl": "
"thumbnailWidth": 1006,
"url": "
"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.
Increase B2B Marketing for Your Users Using the TikTok API
This article introduced you to effective B2B marketing using the sending power of TikTok APIs. For more social media APIs, read our articles on the best social media for attracting B2B clients and the top 10 social media APIs for developers.