DEV Community

Cover image for Retrieve Video List from the official TikTok APIs
Andrea Olivato
Andrea Olivato

Posted on • Originally published at andreaolivato.Medium

Retrieve Video List from the official TikTok APIs

The TikTok PHP SDK has been updated, and the new v0.2 brings support for retrieving the User’s Videos.

If you’re new to the TikTok PHP SDK, please read my previous tutorial on how to log in and receive the Access Token. In that article, I also provide a bit of backstory and more general information about the TikTok Login Kit APIs for Web.
Once you’re all caught up and know how to log in and retrieve the access Token, retrieving the Videos is blazing fast.

The easiest way is to use the getUserVideoPages helper method, since it provides built-in pagination.

$videos = $_TK->getUserVideoPages();
Enter fullscreen mode Exit fullscreen mode

This will return an array that contains all the videos of the logged in user. Watch out because this will keep looping and calling the APIs for all the videos you have. So you might want to add the max_pages parameter. For example to limit to the latest 10 pages only:

$videos = $_TK->getUserVideoPages(10);
Enter fullscreen mode Exit fullscreen mode

If you want more control over the pagination, you can use the higher-level getUserVideos method, which allows you to manage your own pagination via the cursor and num_results parameters. For example, let’s say you only want the latest video:

$videos = $_TK->getUserVideos(0, 1);
Enter fullscreen mode Exit fullscreen mode

The pagination info is provided in the cursor and has_more returned values.

Here’s how you can implement your own pagination:

$videos = [];
$cursor = 0;
$count_pages = 0;
$max_pages = 3;
while ($vids = $this->getUserVideos($cursor)) {
    $count_pages++;
    if ($count_pages > $max_pages && $max_pages > 0) {
        break;
    }
    foreach ($vids['videos'] as $v) {
        $videos[] = $v;
    }
    if ($vids['has_more']) {
        $cursor = $vids['cursor'];
    } else {
        break;
    }
}
Enter fullscreen mode Exit fullscreen mode

Once you have your $videos you can use the simple getter methods, for example getCoverImageURL to get all the available parameters.

Here’s a quick sample, populating a table

foreach ($videos as $v) {
   $trs[] = <<<HTML
       <tr>
           <td width="100"><img src="{$v->getCoverImageURL()}" style="width:100%"></td>
           <td width="100">
               <strong>ID</strong>: {$v->getID()}<br /><br />
               <strong>URL</strong>: {$v->getShareURL()}<br /><br />
               <strong>Caption</strong>: {$v->getVideoDescription()}
           </td>
       </tr>
HTML;
  }
Enter fullscreen mode Exit fullscreen mode

All done! If you have any suggestion on the class or its implementation please feel free to reach out on GitHub or Twitter.

Top comments (0)