22 – YouTube Data API – Comment Threads- list function

This is article 22 of the YouTube API With PHP series.

It is easy to confuse Comments with Comment Threads. To put it simply, every Comment is contained within a Comment Thread. When someone posts a comment for a video, a Comment Thread structure is created within which the Comment is stored. All replies to that Comment are contained within the same Comment Thread. Comments can be in the form of nested replies. As long as the top level Comment is the same, the Comment Thread will contain all the replies and the replies to the replies.

The API does not support the fetching of third level comments or deeper. That means if a Comment Thread is like this:

  1. Top level Comment 1
    1. Reply 1 to Comment 1
    2. Reply 2 to Comment 1
      1. Reply a to Reply 1
        1. Reply to Reply a
      2. Top level Comment 2

Then the API cannot fetch the replies to Comment 1b. In the example above, Top Level Comment 1 is one Comment Thread and Top Level Comment 2 is another Comment Thread. Comments can be for a Channel or for a Video. If a video is marked as private, its comments are not available for API access.

The following functions are available:

1.list

Returns a list of comment threads that match the API request parameters. This can be used to fetch the comments of any public video or channel.

The Request URL is

GET https://www.googleapis.com/youtube/v3/commentThreads

 

Parameters

  • key (string) required. Your API key
  • part (string). Required. One or all of the following in comma separated fashion:
    • “id”
    • “snippet”
    • “replies”
  • Filters (string). Required. Should be one of the following:
    • allThreadsRelatedToChannelId (string) This instructs the API to return all comment threads associated with the specified channel. The response can include comments about the channel or about the channel’s videos.
    • channelId (string) This instructs the API to return comment threads containing comments about the specified channel.
    • id (string) Specifies a comma-separated list of comment thread IDs for the resources that should be retrieved.
    • videoId (string) Instructs the API to return comment threads associated with the specified video ID.
  • maxResults (unsigned int) Optional. Should be between 0 and 50. Default value is 5.
  • moderationStatus (string). Optional. This can only be used if the request has user authentication. Set this parameter to limit the returned comment threads to a particular moderation state. This parameter is not supported for use in conjunction with the id The default value is “published”. Possible values are:
    • “heldForReview” – Retrieve comment threads that are awaiting review by a moderator. A comment thread can be included in the response if the top-level comment or at least one of the replies to that comment are awaiting review.
    • “likelySpam” – Retrieve comment threads classified as likely to be spam. A comment thread can be included in the response if the top-level comment or at least one of the replies to that comment is considered likely to be spam.
    • published – Retrieve threads of published comments. This is the default value. A comment thread can be included in the response if its top-level comment has been published.
  • order (string) Optional. The order parameter specifies the order in which the API response should list comment threads. This parameter is not supported for use in conjunction with the  id parameter.  Valid values are:
    • “time” – Comment threads are ordered by time. This is the default behavior.
    • “relevance” – Comment threads are ordered by relevance
  • pageToken (string) Optional. Holds the value for nextPageToken or prevPageToken.
  • searchTerms (string) Optional. This instructs the API to limit the API response to only contain comments that contain the specified search terms. : This parameter is not supported for use in conjunction with the id parameter.
  • textFormat (string) Optional. Set this parameter’s value to html or plainText to instruct the API to return the comments left by users in html formatted or in plain text. The default value is html. Possible values are:
    • “html” – Returns the comments in HTML format. This is the default value.
    • “plainText” – Returns the comments in plain text format.

 

Example Requests

List top level comments of a Video.

https://www.googleapis.com/youtube/v3/commentThreads?key=xx&part=id,snippet,replies&videoId=xxx

List replies to a comment using the comment id

https://www.googleapis.com/youtube/v3/commentThreads?key=xx&part=id,snippet,replies&id=xxx

List top level comments of a Channel

https://www.googleapis.com/youtube/v3/commentThreads?key=xx&part=id,snippet,replies&channelId=xxx

 

Response

A successful API call will return an array of CommentThread resources encoded in json:

{
  "kind": "youtube#commentThreadListResponse",
  "etag": etag,
  "nextPageToken": string,
  "pageInfo": {
    "totalResults": integer,
    "resultsPerPage": integer
  },
  "items": [
    (commentThread Resource)
  ]
}

 

The Response components are explained below:

  • kind (string) “youtube#channelListResponse.”
  • etag (string) See ETags Explained section
  • nextPageToken (string) token for the next page
  • prevPageToken (string) token for the previous page
  • totalResults (int) total count of results obtained
  • resultsPerPage (int) results per page requested
  • items (array) array of CommentThread Resource items returned

 

The JSON structure of a CommentThread Resource is shown below:

{
  "kind": "youtube#commentThread",
  "etag": etag,
  "id": string,
  "snippet": {
     "channelId": string,
     "videoId": string,
     "topLevelComment": comments Resource,
     "canReply": boolean,
     "totalReplyCount": unsigned integer,
     "isPublic": boolean
  },
  "replies": {
     "comments": [
     comments Resource
     ]
  }
}

An explanation of the various fields are given below:

  • kind (string) This value is always “youtube#commentThread”
  • etag (string) See ETags Explained section
  • id (string) unique id of this Comment Thread
  • channelId (string) The YouTube channel that is associated with the comments in the thread. (The snippet.videoId property identifies the video.)
  • If the comments are about a video, then the value identifies the channel that uploaded the video. (The snippet.videoId property identifies the video.)
  • If the comments refer to the channel itself, the snippet.videoId property will not have a value.
  • videoId (string) string The ID of the video that the comments refer to, if any. If this property is not present or does not have a value, then the thread applies to the channel and not to a specific video.
  • topLevelComment (object) The thread’s top-level comment. The property’s value is a Comment resource.
  • canReply (boolean) This setting indicates whether the current viewer can reply to the thread.
  • totalReplyCount (unsigned int) The total number of replies that have been submitted in response to the top-level comment.
  • isPublic (boolean) This setting indicates whether the thread, including all of its comments and comment replies, is visible to all YouTube users.
  • replies (object) The replies object is a container that contains a list of replies to the comment, if any exist. The replies.comments property represents the list of comments itself.
  • comments (list) A list of one or more replies to the top-level comment. Each item in the list is a Comment resource. The list contains a limited number of replies, and unless the number of items in the list equals the value of the snippet.totalReplyCount property, the list of replies is only a subset of the total number of replies available for the top-level comment. To retrieve all of the replies for the top-level comment, you need to call the comments.list method and use the parentId request parameter to identify the comment for which you want to retrieve replies.

Sample code to list all top level comments for a Video:

<?php
    error_reporting(E_ALL ^ E_NOTICE ^ E_WARNING ^ E_DEPRECATED);
    set_time_limit(60 * 3);
    
    $g_youtubeDataAPIKey = "**";
    $videoId = "CUpAOHyVskA";
    
   	 // make api request
   	 $url = "https://www.googleapis.com/youtube/v3/commentThreads?key=" . $g_youtubeDataAPIKey .
   			 "&part=id,snippet,replies&videoId=" . $videoId;


   	 $curl = curl_init();
   	 curl_setopt_array($curl, array(
   				 CURLOPT_RETURNTRANSFER => 1,
   				 CURLOPT_URL => $url,
   				 CURLOPT_USERAGENT => 'YouTube API Tester',
   				 CURLOPT_SSL_VERIFYPEER => 1,
   				 CURLOPT_SSL_VERIFYHOST=> 0,
   				 CURLOPT_CAINFO => "../../cert/cacert.pem",
   				 CURLOPT_CAPATH => "../../cert/cacert.pem",
   				 CURLOPT_FOLLOWLOCATION => TRUE
   				 ));
   	 $resp = curl_exec($curl);

   	 curl_close($curl);

   	 if ($resp) {
   		 $json = json_decode($resp);

   		 if ($json) {
   			 echo("JSON decoded<br>");

   			 $items = $json->items;

   			 foreach($items as $item) {
   				 $id = $item->id;
   				 $author = $item->snippet->topLevelComment->snippet->authorDisplayName;
   				 $authorPic = $item->snippet->topLevelComment->snippet->authorProfileImageUrl;
   				 $authorChannelUrl = $item->snippet->topLevelComment->snippet->authorChannelUrl;
   				 $authorChannelId = $item->snippet->topLevelComment->snippet->authorChannelId->value;
   				 
   				 $textDisplay = $item->snippet->topLevelComment->snippet->textDisplay;
   				 $publishedOn = $item->snippet->topLevelComment->snippet->publishedAt;
   				 $replyCount = $item->snippet->totalReplyCount;


   				 echo("\"" . $textDisplay . "\"  by " . $author . "<br>");
   				 echo("<img src=\"" . $authorPic . "\" border=0 align=left>");
   				 echo("On " . $publishedOn . " , Replies :" . $replyCount);
   				 echo("<hr>");    
   			 }

   		 
   		 } else
   			 exit("Error. could not parse JSON." . json_last_error_msg());

   	 
   	 } // if resp

   	 
    
?>

Here is the output:

JSON decoded

"I understand Japanese and this is beautiful ❤" by pratiksha sharma
On 2017-05-27T15:59:27.000Z , Replies :0

"Have the movie this music?" by 餘數
On 2017-05-26T17:52:43.000Z , Replies :0

"jadi nangis,inget mantan terindah.
damn i hate this anime" by Galang Bio
On 2017-05-24T16:03:55.000Z , Replies :0

":)" by Rainy Lovegood
On 2017-05-23T14:48:20.000Z , Replies :0


Sample code to show all the comments and replies contained in a CommentThread.

<?php
    error_reporting(E_ALL ^ E_NOTICE ^ E_WARNING ^ E_DEPRECATED);
    set_time_limit(60 * 3);
    
    $g_youtubeDataAPIKey = "**";
    $commentId = "z13uzrmbmmupwdzj404cdtij0xikjh1piqg0k";
    
   	 // make api request
   	 $url = "https://www.googleapis.com/youtube/v3/commentThreads?key=" . $g_youtubeDataAPIKey .
   			 "&part=id,snippet,replies&id=" . $commentId;


   	 $curl = curl_init();
   	 curl_setopt_array($curl, array(
   				 CURLOPT_RETURNTRANSFER => 1,
   				 CURLOPT_URL => $url,
   				 CURLOPT_USERAGENT => 'YouTube API Tester',
   				 CURLOPT_SSL_VERIFYPEER => 1,
   				 CURLOPT_SSL_VERIFYHOST=> 0,
   				 CURLOPT_CAINFO => "../../cert/cacert.pem",
   				 CURLOPT_CAPATH => "../../cert/cacert.pem",
   				 CURLOPT_FOLLOWLOCATION => TRUE
   				 ));
   	 $resp = curl_exec($curl);

   	 curl_close($curl);


   	 if ($resp) {
   		 $json = json_decode($resp);

   		 if ($json) {
   			 echo("JSON decoded<br>");

   			 $items = $json->items;

   			 foreach($items as $item) {
   				 $id = $item->id;
   				 $author = $item->snippet->topLevelComment->snippet->authorDisplayName;
   				 $authorPic = $item->snippet->topLevelComment->snippet->authorProfileImageUrl;
   				 $authorChannelUrl = $item->snippet->topLevelComment->snippet->authorChannelUrl;
   				 $authorChannelId = $item->snippet->topLevelComment->snippet->authorChannelId->value;
   				 
   				 $textDisplay = $item->snippet->topLevelComment->snippet->textDisplay;
   				 $publishedOn = $item->snippet->topLevelComment->snippet->publishedAt;
   				 $replyCount = $item->snippet->totalReplyCount;

   			 
   				 echo("\"" . $textDisplay . "\"  by " . $author . "<br>");
   				 echo("<img src=\"" . $authorPic . "\" border=0 align=left>");
   				 echo("On " . $publishedOn . " , Replies :" . $replyCount);

   				 if ($replyCount > 0) {
   					 $comments  = $item->replies->comments;
   					 echo("<br><br><br><b>Replies</b><br>");
   					 foreach($comments as $comment) {
   							 $id = $comment->id;
   							 $author = $comment->snippet->authorDisplayName;
   							 $authorPic = $comment->snippet->authorProfileImageUrl;
   							 $authorChannelUrl = $comment->snippet->authorChannelUrl;
   							 $authorChannelId = $comment->snippet->authorChannelId->value;

   							 $textDisplay = $comment->snippet->textDisplay;
   							 $publishedOn = $comment->snippet->publishedAt;


   							 echo("&nbsp;&nbsp;&nbsp;\"" . $textDisplay . "\"  by " . $author . "<br>");
   							 echo("&nbsp;&nbsp;&nbsp;<img src=\"" . $authorPic . "\" border=0 align=left>");
   							 echo("&nbsp;&nbsp;&nbsp;On " . $publishedOn );
   							 echo("<br><br><br>");
   					 }
   				 }
   				 echo("<hr>");    
   			 }

   		 
   		 } else
   			 exit("Error. could not parse JSON." . json_last_error_msg());

   	 
   	 } // if resp

   	 
    
?>

 

Note that in the case of replies to a Comment, we do not get the number of replies to those replies, because the API does not support that feature.

Be the first to comment

Leave a Reply

Your email address will not be published.


*