How to Use the TikTok API with Python (in 5 Easy Steps)

What is TikTok?

TikTok is the leading destination for short-form mobile video. Our mission is to inspire creativity and bring joy.

TikTok was launched in 2017 by the Chinese firm Bytedance and is becoming one of the fastest-growing social media platforms to date. The application allows users to upload short mobile videos and share them with large audiences. The application has gained success by appealing to a younger generation of smartphone users. TikTok provides editing features that enhance the production of short films. Furthermore, TikTok provides a way for users to share videos and create a community around shared interests.

In late July of 2020, President Donald Trump threatened to ban TikTok from use in the U.S based on allegations that it was a security risk to the country. On August 2, 2020, it was reported on Microsoft’s Official Blog that Microsoft was in preliminary talks to purchase, “[…] the TikTok service in the United States, Canada, Australia, and New Zealand and would result in Microsoft owning and operating TikTok in these markets.” At the moment it’s unclear what this would mean for TikTok if the deal were to succeed.

Connect to the TikTok API

TikTok API

Does TikTok have an official API?

TikTok provides a single HTTP endpoint that allows developers to fetch the embed (oembed) code for individual videos. For instructions on embedding individual videos visit their For Developers page. Although it does provide an API for fetching embed code, the API is not very extensive.

TIkTok API on RapidAPI

The TikTok API was created to fill the gap between developers and TikTok due to a lack of an official TikTok API.

With this API you can, “[…] extract metadata about user and hashtag, extract video feed metadata from the user, hashtag, trending and music pages (video posts with statistics), extract user followers, following metadata […]”.

The API is divided into five sections:

  • Hashtag
  • User
  • Video Post
  • Trends
  • Music

API Dashboard

To view the various endpoints for the API visit the API’s homepage. Here, you will see an interactive dashboard that allows you to read about endpoints, test arguments, view sample code, and view example responses.

On the left side of the dashboard, you can use the dropdowns to select the endpoint you want to explore.

If you select an endpoint (i.e User feed) the other sections of the dashboard will update with the information for that endpoint. In the middle section, I can scroll to see the parameters that the route takes.

Also, the right side of the dashboard generates code snippets for different libraries and languages. In the picture below, I have selected Python and Requests.

The lower portion on the right side of the dashboard displays example responses and test responses.

You need to subscribe to the API to test it on the dashboard. In the next section, I’ll discuss the pricing for the API and how to subscribe.

TikTok API Pricing

Select the Pricing tab at the top of the page to see the different options for subscribing. You need to have an account on RapidAPI to subscribe to APIs, but don’t worry, it’s free! You can sign up on the RapidAPI’s homepage.

Notice I have signed up for the Basic plan for this API. Therefore, I have a link to Manage and View Usage on my developer dashboard. I can view my quotas and analytics across all my APIs there.

After signing up, I can test the endpoints back on the Endpoints page.

The TikTok API makes it easy to retrieve metadata from TikTok. The RapidAPI dashboard helps users discover and test endpoints. Next, we will look at Python and how we can use this friendly programming language to retrieve that information for an application.

Connect to the TikTok API

Python

Python is a programming language that lets you work quickly and integrate systems more effectively.

python.org

Python is an object-oriented programming language that we can use to write small scripts, web applications, or desktop applications. It focuses on readability and community support make it an ideal candidate for all skill levels.

Resources for Learning Python

My favorite tutorial for Python is from Python’s documentation. They have a Beginner Python Tutorial for a solid introduction to the language from the source. If you have a bigger appetite, I recommend the book Automate the Boring Stuff with Python.

For an introduction to sending HTTP requests and using an API with Python, check out this article. Additionally, you can find more Python API articles on RapidAPI’s blog.

If you are already comfortable with Python, then feel free to jump into the next section where we build a small Flask application to fetch TikTok videos based on a predefined hashtag. Let’s begin!

Connect to the TikTok API

How to Use the TikTok API with Python

View the code on Github

Flask is a microframework for web development with Python. Its easy setup has made it a popular way for developers to get a web application up and running.

We are going to use the framework to create one route that fetches videos for a predefined hashtag.

Prerequisites

To participate with this application you will need to have a few technologies and knowledge at your disposal:

  • Python installed on your local machine
  • An account on RapidAPI (refer to the TikTok API Pricing section above)
  • Subscription to the TikTok API (refer to the TikTok API Pricing section above)
  • Basic understanding of Python
  • Basic understanding on how to open and execute commands with the command line for Unix command shells or PowerShell with Windows
  • Internet connection
  • Code editor

For the sake of brevity, I will use the terms command prompt, terminal, and command terminal interchangeably. When I use these words I am referring to BASH, Z-Shell, PowerShell, etc.

1. Set Up Python Project

Open up a fresh terminal on your local machine. I am using Mac, so I will open up the Terminal application. Navigate to the directory you want to create the project in using the cd command.

Create a new directory named rapidapi-tiktok-api-python.

mkdir rapidapi-tiktok-api-python

Change directories into that folder.

cd rapidapi-tiktok-api-python

We are going to create a virtual environment so we can keep the package versions that we install locally to each project that we create in Python. This is beyond the scope of this article but you can use the link at the beginning of the paragraph to learn more.

python3 -m venv venv

This command creates a virtual environment in our current directory. Before we start downloading packages, we need to activate the virtual environment. PIP (Python Package Installer) will install packages to the virtual environment that we have activated. If none is activated, the packages get installed to our global Python library.

On Windows, run:

venvScriptsactivate.bat

On Mac, run:

source venv/bin/activate

Your command prompt should now specify the virtual environment that you are using.

Next, download the Flask package using PIP.

pip3 install -U Flask

For the application, we are also going to need the requests library.

pip3 install requests

Then, open up the project with your code editor. I am using VSCode.

Create a file, in the root of the directory, name app.py. Paste the below code into the file.

from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello, World!'

Finally, we need to set an environment variable that tells Flask what file to use for our application.

On Mac:

export FLASK_APP=app.py

On Windows:

$env:FLASK_APP = "app.py"

We can now start the application! In the terminal execute flask run. You should see the output similar to the image below.

You can visit the URL http://localhost:5000/ in your browser to view the app.

2. Create HTML Templates

Create a new directory in your main folder and name it templates. Flask will recognize this folder and serve HTML files from it.

Inside that directory create the file base.html and add the following code,

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>RapidAPI - TIkTok API</title>
    <link href="/static/style.css" rel="stylesheet">
</head>
<body>
    <main>
        <h1>TikTok API</h1>
        {% block content %}{% endblock %}
    </main>
</body>
</html>

Flask uses Jinja2 templating to insert values and perform actions in HTML files. The templating syntax used in this file is:

{% block content %}{% endblock %}

We are creating a block content section named content.

Next, create another file in the templates directory and name it tiktok.html. Add the following code.

{% extends 'base.html' %}

{% block content %}
    <section>
        <h2>Check Out Videos For <span id="hashtag">#{{ hashtag }}</span></h2>
        {{ response }}
    </section>
{% endblock %}

In this file, we are specifying that this code extends the base.html file. Furthermore, we are providing content for block content section.

To render the new templates, we need to import the render_template function from Flask and return this function specifying the template name.

Change the code in app.py to reflect the code below.

from flask import Flask, render_template
app = Flask(__name__)

@app.route('/')
def hello_world():
    return render_template('tiktok.html')

Lastly, save the files, restart the app, and visit the webpage again.

Now, we are rendering HTML content from our templates.

3. Call TikTok API with Python

We can use code snippets from RapidAPI to easily gather the information we need for the API request.

First, import requests and json at the top of the file.

import requests
import json

Then, at the top of the hello_world route declaration function, add the code below to call the hashtag feed endpoint.

...    
    url = "https://tiktok.p.rapidapi.com/live/hashtag/feed"

    hashtag = "python"

    querystring = {"name": hashtag,"limit":"10"}
    headers = {
        'x-rapidapi-host': "tiktok.p.rapidapi.com",
        'x-rapidapi-key': "yourapikey"
    }

    response = requests.request(
        "GET",
        url,
        headers=headers,
        params=querystring
    )

    res_json = json.loads(response.text)
    videos = res_json['media']
...

This API call is essentially taken straight from the dashboard. To display the response video data, we can pass context variables into the render_template function.

....
    return render_template('tiktok.html', response=videos, hashtag=hashtag)
....

We are converting the text response data to a JSON object,

res_json = json.loads(response.text)

and then extracting the media property from the object. This property holds the video metadata that we are going to iterate over in the template to display the videos.

API Key

Notice that for the 'x-rapidapi-key' value I didn’t insert my actual API key.

Your API key is a secret key that is unique to your account on RapidAPI. If someone discovers this key they can abuse it and run up your API quota. We need to keep this key secure.

To do this, we are going to use an environment variable to load the value in.

Stop the Flask server using the keyboard shortcut Ctrl+C in the terminal. Download python-dotenv, making sure the virtual environment is active and you are at the root of the project.

pip3 install python-dotenv

Then, create a file in the project root named .env. Add the following line to it replacing yourapikey with your secret API key from RapidAPI.

RAPIDAPI_KEY=yourapikey

In app.py, add this code below the last import statement.

from dotenv import load_dotenv

load_dotenv()
RAPIDAPI_KEY = os.getenv("RAPIDAPI_KEY")

Finally, provide the variable RAPIDAPI_KEY as the value in the headers object for 'x-rapidapi-key'.

headers = {
    'x-rapidapi-host': "tiktok.p.rapidapi.com",
    'x-rapidapi-key': RAPIDAPI_KEY
}

Save the files, restart the app, and refresh the browser.

We can take note of a few things:

  1. Our API call works!
  2. The API key is loaded successfully and securely
  3. We need to format the data in the browser

4. Rendering TikTok API Response Data

We can use Jinja2 templating syntax and keywords to iterate over the video data and render it in the browser.

Open tiktok.html, and replace the {{ response }} variable with this code.

<ul>
    {% for video in response %}
        <li>
            <h3>{{ video.description }}</h3>
            <video width="{{ video.video.width }}" height="{{ video.video.height }}" controls>
                <source src="{{ video.video.playAddr }}">
            </video>
            <p>Author: {{ video.author.nickname }}</p>
        </li>
    {% endfor %}
</ul>

There is plenty of data to extract from the API call. However, we are only going to use the:

  • video description
  • play address (playAddr)
  • video height and width
  • author nickname

In the above code, I am using dot-notation to access these values from each video object in the response data.

If you restart the Flask server and refresh the browser, you’ll notice that the videos are now displayed. They can also be played!

We have successfully fetched data, based on the python hashtag, and rendered it in the browser.

5. Style the Application

Create a folder in the root of the project and name it static. Inside of static, add the file style.css.

Inside of style.css, add the below code.

body {
    background: #EEE;
}

#hashtag {
    color: rgb(11, 250, 119);
}

main {
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    font-family: 'Courier New', Courier, monospace;
}

section {
    text-align: center;
}

ul {
    list-style-type: none;
    text-align: center;
    width: 60%;
    margin: auto;
}

ul li {
    margin: 1rem;
    padding-bottom: 2rem;
}

h1, h2 {
    margin-bottom: 30px;
    margin-top: 30px;
    background: black;
    color: white;
    padding: .2rem .5rem;
    display: inline-block;
}

h1, h2, h3 {
    text-align: center;
}

h1 {
    font-size: 3.2rem;
}

h2 {
    font-size: 2.2rem;
}

video {
    box-shadow: 0px 0px 20px -2px black;
}

Finally, save the file and restart the application. The app now has some style!

Connect to the TikTok API

Conclusion

Python can be used in many different ways to fetch data from APIs. You can use web frameworks like Flask and Django, Jupyter notebooks, or short scripts using a code editor like Python’s IDLE. Regardless of the medium, the API call remains largely unchanged.

However, the TikTok API will most likely change, but we can always check out the different endpoints and read about how to use them on the dashboard in RapidAPI.

Thanks for reading the article and congratulations on successfully building the application!

5 / 5 ( 1 vote )
Jarrett Retz

Jarrett is a Web and Automation Application Developer based in Spokane, WA. He is well versed in NodeJS, React, Django, Python, MongoDB, third-party APIs (i.e Sendgrid, Stripe), PostgreSQL, HTML5, CSS3, and cloud-computing resources. Learn more about Jarrett on his website.

Share
Published by

Recent Posts

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 week 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 week ago

How to Document your API

Documentation is an essential part of any API, and this is what we're going to…

2 weeks ago

How to use the Google Play Store API to Search App Details

Modern mobile phones are replacing many different devices and services. And the bigger part of…

2 weeks ago

The 10 Chrome Flags That Can Transform Your Browsing Experience

Being one of the most popular web browsers out there, Google Chrome has a reputation…

3 weeks ago

How to use the Google Translate API with Ruby on Rails

Google, mostly known for its search engine and extremely popular email service, Gmail, also provides…

3 weeks ago