TikTok has taken a strong hold in the social media world recently.  It is a phone app, but what if you want to add trending videos to a widget on your website?  Using the TlkTok API you can do that.  In this article, we will walk through how to use a TikTok API with JavaScript.

Let’s say you like frogs, and you want to show a TikTok feed about them on your website.  My teenage daughter explained to me that young people spell things wrong on purpose. She said they do this to make it more interesting.  It would be boring if the hashtag was “frog”.  So one of the most popular hashtags on TikTok now is #phrog.  We will walk through an example of how to add a feed from TikTok to your website using JavaScript. The feed will have the phrog hashtag.

TikTok Data Quality Caveat

But, be aware that when someone tags a video with #phrog that does not guarantee it has anything to do with frogs.  As with any social media outlet, TikTok users add popular tags to their videos to get people to see them.  I was amazed when I learned the meaning behind one of the most popular hashtags, #foryoupage or #fyp for short.  It refers to the recommendations that TikTok gives it’s users.  Do people think the recommendation algorithm would give any weight to that hashtag?  Do they think it would put their video on other people’s “For You” page?

Many people must think that way, and they may be right.  I checked the TikTok.com website I saw this at the top of the ‘For You’ page without logging in:

Wow, I guess that means TikTok is not as sophisticated as Google.  For SEO purposes the example above looks like keyword stuffing. This would incur a penalty in Google, but so far it flies in TikTok. 🙂
Back to the task at hand, using a TikTok API in Javascript.  Here are the steps we will follow:

A Five-Step Process

  1. Get an API Key
  2. Subscribe to the TlkTok API
  3. Create an output template
  4. Connect to the API using JavaScript
  5. Display on your website

Step 1. Get an API Key

First we need to get a free API Key.  The TlkTok API is miss-spelled like many of the popular hashtags on TikTok.  I’m starting to see the pattern now.  RapidAPI hosts the TlkTok API so the first step is to get an API Key if you don’t have one already.  That is a quick process, you get a Key after you register at RapidAPI.com.

Step 2. Subscribe to the TlkTok API

There are currently four different TikTok APIs on RapidAPI.  I tested them myself within a few minutes for free to decide which one I would use.  I chose the TlkTok API because it has an endpoint which allows me to search by hashtag. Also it worked the first time I tried it.  On the endpoints page there is a blue button in the middle called “Subscribe to Test”.  Once you click that you can choose the free option to start with. Then you can type in a hashtag and click the Test Endpoint button to make an API call.  The results are shown in the right hand column:

Step 3. Create an output template

Now that we have access to the API, we can create a simple template to display the results on our site.  We are going to have a simple frog video page with TikTok videos presented in a 3 by 3 grid.  We will make it look like the TikTok home page. First we will show a list of cover images and when you click them they will switch to a dynamic image.  To make the switching work we will put each TikTok in it’s own div.  Then each div will map to both static and dynamic photos using arrays.
The output template uses this HTML:
<h1> Phrog TikToks </h1>
    <div class="flex-grid">
    <div class="cell" >

This CSS puts the images into a 3 by 3 grid and collapses to one column for small screens:

<style>
.flex-grid {
  display: flex;
}
.cell {
  flex: 1;
  cursor: pointer;
  padding:1px;
}
.cellContent {
    width: 100%;
    height: 100%;
}
@media (max-width: 400px) {
  .flex-grid {
    display: block;
  }
}
</style>

Step 4. Connect to the API using JavaScript

Once we have a template, we’ll need to connect to the API to populate it.  I chose the jQuery option in the list of JavaScript code snippets. This is how it looks on the Endpoints page:

var settings = {
  "async": true,
  "crossDomain": true,
  "url": "https://tiktok.p.rapidapi.com/live/hashtag/feed?name=phrog",
  "method": "GET",
  "headers": {
    "x-rapidapi-host": "tiktok.p.rapidapi.com",
    "x-rapidapi-key": "Your-RapidAPI-Key-Here"
  }
}

$.ajax(settings).done(function (response) {
  console.log(response);
});

One other important piece to include is the jQuery library itself.  If you click on the “Install SDK” link on the API Endpoints page you will see a modal appear like this:

Copy the text and put it into your code somewhere before you call the API.  Using a provided code snippet makes it very easy to connect to the TikTok API using JavaScript.

Step 5. Display on your website

To improve page loading speed, we can set a limit to how often we will refresh the contents of the template.  In this example we set a time limit of one hour.  To do that we load on the page the latest saved TikToks from a text file on the server.  Then after the page loads we’ll check a last updated parameter added to the JSON response from the API.  If the last updated time is over 1 hour old, we will use the API to get fresh data. Then we send that data to the server to update the file there.  Below is the simple PHP file used to save new TikToks:

<?php
/*
File: updateJSON.php
Description: This file updates the local copy of a feed of TikToks from one hashtag.
  The data is passed in as an object, but it is stored as a JSON formatted string.
  NOTE: no validation is done for this data.  To prevent unauthorized access place
  this file outside of the web root.
Input:
  $_POST - this contains the data passed in object format
*/
//Grab the data passed into this file
if (!empty($_POST)) {
  $latestTikToks = json_encode($_POST);
}

//Update the local file with the latest TikToks in JSON format
file_put_contents(__DIR__."/latestTikToks.json",$latestTikToks);
?>

The main file which checks the timestamps, calls the TikTok API, saves the feed, and displays it is this:

<?php
/*
File: TikTokSampleFeedPage.php
Description: This page shows a feed of TikToks from one hashtag.
  They are static images but when you click each image
  it is replaced by a video clip (dynamic image).  The JSON file
  is placed one level higher up to keep it out of the webroot.
*/
//First get the current json data from a local file
$latestTikToks='';
if (file_exists(__DIR__."/../latestTikToks.json")) {
  $latestTikToks = file_get_contents(__DIR__."/../latestTikToks.json");
}
$numberOfTikToksToShow = 9;
$numberOfTikTokRowsToShow = $numberOfTikToksToShow/3;
?>
<!DOCTYPE html>
<html>
<head>
<title>TikTok Feed</title>
<style>
.flex-grid {
  display: flex;
}
.cell {
  flex: 1;
  cursor: pointer;
  padding:1px;
}
.cellContent {
    width: 100%;
    height: 100%;
}
@media (max-width: 400px) {
  .flex-grid {
    display: block;
  }
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript">
<?php
//Populate a javascript parameter with the latest json data
if (!empty($latestTikToks)) {
  echo "var latestTikToks = ".$latestTikToks."; \n";
} else {
  echo "var latestTikToks = {};\n";
}
?>

//Check last Modified date to see if we need to refresh the data - refresh after an hour
var nowMilliseconds = Date.now();
var nowSeconds = Math.floor(nowMilliseconds / 1000);
var oneHourAgoSeconds = nowSeconds - 3600;

//Define arrays to store static and dynamic images
var images = [];
var clips = [];

//Only do this after the page is loaded so we have elements to populate
$( document ).ready(function() {
  //Decide if we need to call the API or just pull data from the server
  if (latestTikToks.hasOwnProperty('modifiedDateSeconds') && latestTikToks.modifiedDateSeconds>oneHourAgoSeconds) {
    populateTikToks();
  } else {
    console.log("Retrieving TikToks now");
    refreshTikToks();
  }
});

//Use the javascript interface to pull TikToks
function refreshTikToks() {
  var settings = {
   "async": true,
   "crossDomain": true,
   "url": "https://tiktok.p.rapidapi.com/live/hashtag/feed?name=phrog",
   "method": "GET",
   "headers": {
    "x-rapidapi-host": "tiktok.p.rapidapi.com",
    "x-rapidapi-key": "Your-RapidAPI-Key-Here"
   }
  }

  $.ajax(settings).done(function (response) {
   //Save the API response to the server
    saveTikToks(response);
  });
}

//Save the latest tiktok feed to the server
function saveTikToks(jsonFeed) {
  var thisData = jsonFeed;

  //Capture the timestamp within the JSON file
  thisData.modifiedDateSeconds = nowSeconds;

  //Limit how much data is sent to server
  thisData.media = thisData.media.slice(0,10);

  //Update this parameter to use later for populating the page
  latestTikToks = thisData;

  //Send the updated json to the server to save it
  $.ajax({
      type: "POST",
      url: "../updateJSON.php",
      data: thisData,
  }).done(function( results ) {
    console.log(results);
  });

  //Show the latest TikToks on the page
  populateTikToks();
}

//Populate the 9 latest TikToks on the page, and update the arrays of images and clips
function populateTikToks() {
  //Loop through the media property of latestTikToks
  for (var i in latestTikToks.media) {
    //Only populate the number of tiktoks we saved
    if (i>=<?php echo $numberOfTikToksToShow; ?>) break;

    //First update the local arrays of images and clips
    images[i] = latestTikToks.media[i].video.cover;
    clips[i] = latestTikToks.media[i].video.dynamicCover;

    //Next show the image
    showImage(i);
  }
}

//Replace an image with a video clip
function showClip(cellIndex) {
  var outerDiv = document.getElementsByClassName('cell')[cellIndex];
  outerDiv.innerHTML = "<img class='cellContent' src='"+clips[cellIndex]+"'/>'";
}

//Replace a video clip with an image
function showImage(cellIndex) {
  var outerDiv = document.getElementsByClassName('cell')[cellIndex];
  outerDiv.innerHTML = "<img class='cellContent' src='"+images[cellIndex]+"'/>'";
}
</script>
</head>
<body>
  <h1> Phrog TikToks </h1>
  <?php
  //Show 9 tiktoks on the page at once
  for ($i=0;$i<$numberOfTikTokRowsToShow;$i++) {
    ?>
    <div class="flex-grid">
      <div class="cell" >

Below is an example of how it might look using the example code provided:

Conclusion

In this article we’ve walked through an example of how to use a TikTok API with JavaScript.  We first signed up to get an API Key, then subscribed to the TikTok API.  After that we used a JavaScript code snippet to connect to the API, and then displayed a feed on a webpage.  Using the provided code snippets is a great way to work with the APIs. They allow you to work within whatever language you are familiar with to access the TlkTok API.

5 / 5 ( 1 vote )
Robert Davis

Robert Davis is an IT Consultant with the following areas of emphasis: APIs | Automation | Data Visualization | Ecommerce | Open Source | WordPress

Share
Published by

Recent Posts

API Testing Tutorial: API Testing with RapidAPI

What is API Testing? API testing is a type of software testing that involves testing application programming interfaces (APIs) directly…

7 days ago

Test APIs From Development to Deployment with RapidAPI Testing

We are excited to introduce RapidAPI Testing — a functional API testing solution for creating…

1 week ago

Build a Influencer Search App with Ruby on Rails

Internet search has gone way beyond the traditional web search. Thanks to other mediums of…

4 weeks ago

React API Authentication & Authorization

Introduction Security on the internet comes under scrutiny the more our personal lives and business…

4 weeks ago

How to use WordPress with React (WordPress React API Tutorial)

WordPress WordPress claims to be, "the world’s most popular website builder" based on the statistic…

1 month ago

How to use an E-mail API with JavaScript

Introduction This tutorial will show you how to use JavaScript to call an API to…

1 month ago