25 – YouTube Data API – Comments – list function

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

A comment resource contains information about a single YouTube comment. A comment resource can represent a comment about either a video or a channel. In addition, the comment could be a top-level comment or a reply to a top-level comment. You should get familiar with CommentThreads in the previous section first, if you have not already.

Every Comment is enclosed within a CommentThread resource. The following functions are available:

1.list

Retrieves a single comment or all the replies to a top level comment. When id is specified in the API call then only that particular comment is retrieved. When parentId is specified then all the replies to that comment are retrieved.

The Request URL is

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

 

Parameters

  • key (string) required. Your API key
  • part (string). Required. One or all of the following in comma separated fashion:
    • “id”
    • “snippet”
  • Filters (string) required. One of the following:
    • id (string) Specifies a single or comma-separated list of comment IDs for the resources that are being retrieved. In a comment resource, the id property specifies the comment’s ID.
    • parentId (string) Specifies the ID of the comment for which replies should be retrieved. YouTube currently supports replies only for top-level comments. However, replies to replies may be supported in the future
  • maxResults (unsigned int) Optional. Should be between 0 and 50. Default value is 5.
  • pageToken (string) Optional. Holds the value for nextPageToken or prevPageToken.
  • 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

Get comment using a comment id

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

Get replies to a Comment

https://www.googleapis.com/youtube/v3/comments?key=xx&part=id,snippet&parentId=xx

 

Response

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

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

 

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 Comment Resource items returned

 

 

The JSON structure of a Comment  Resource is shown below:

{
  "kind": "youtube#comment",
  "etag": etag,
  "id": string,
  "snippet": {
     "authorDisplayName": string,
     "authorProfileImageUrl": string,
     "authorChannelUrl": string,
     "authorChannelId": {
     "value": string
     },
     "channelId": string,
     "videoId": string,
     "textDisplay": string,
     "textOriginal": string,
     "parentId": string,
     "canRate": boolean,
     "viewerRating": string,
     "likeCount": unsigned integer,
     "moderationStatus": string,
     "publishedAt": datetime,
     "updatedAt": datetime
  }
}

 

An explanation of the various fields are given below:

  • kind (string) This value is always “youtube#comment”
  • 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.
  • authorDisplayName (string) The display name of the user who posted the comment.
  • authorProfileImageUrl (string) The URL for the avatar of the user who posted the comment.
  • authorChannelUrl (string) The URL of the comment author’s YouTube channel, if available.
  • authorChannelId (object) This object encapsulates information about the comment author’s YouTube channel, if available.
  • authorChannelId.value (string) The ID of the comment author’s YouTube channel, if available.
  • textDisplay (string) The comment’s text. The text can be retrieved in either plain text or HTML. (The comments.list and commentThreads.list methods both support a textFormat parameter, which specifies the desired text format.) Note that even the plain text may differ from the original comment text. For example, it may replace video links with video titles.
  • textOriginal (string) The original, raw text of the comment as it was initially posted or last updated. The original text is only returned if it is accessible to the authenticated user, which is only guaranteed if the user is the comment’s author.
  • parentId (string) The unique ID of the parent comment. This property is only set if the comment was submitted as a reply to another comment.
  • canRate (boolean) This setting indicates whether the current viewer can rate the comment.
  • viewerRating (string) The rating the viewer has given to this comment. Note that this property does not currently identify dislike ratings, though this behavior is subject to change. In the meantime, the property value is like if the viewer has rated the comment positively. The value is none in all other cases, including the user having given the comment a negative rating or not having rated the comment. Valid values for this property are:
  • “like”
  • “none”
  • likeCount (unsigned int) The total number of likes (positive ratings) the comment has received.
  • moderationStatus (string) The comment’s moderation status. This property is only returned if the API request was authorized by the owner of the channel or the video on which the requested comments were made. In addition, note that this property is not set if the API request used the id filter parameter. Valid values for this property are:
  • “heldForReview”
  • “likelySpam”
  • “published”
  • “rejected”
  • publishedAt (datetime) The date and time when the comment was orignally published. The value is specified in the (YYYY-MM-DDThh:mm:ss.sZ) format.
  • updatedAt (datetime) he date and time when the comment was last updated. The value is specified in the (YYYY-MM-DDThh:mm:ss.sZ) format.

 

 

Sample code to list a comment using comment id

<?php
    error_reporting(E_ALL ^ E_NOTICE ^ E_WARNING ^ E_DEPRECATED);
    set_time_limit(60 * 3);
    
    $g_youtubeDataAPIKey = "**";
    $commentId = "z12nuf2z1kfzcnzx004chrljwqmqinyjuvo0k";
    
   	 // make api request
   	 $url = "https://www.googleapis.com/youtube/v3/comments?key=" . $g_youtubeDataAPIKey .
   			 "&part=id,snippet&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->authorDisplayName;
   				 $authorPic = $item->snippet->authorProfileImageUrl;
   				 $authorChannelUrl = $item->snippet->authorChannelUrl;
   				 $authorChannelId = $item->snippet->authorChannelId->value;
   				 
   				 $textDisplay = $item->snippet->textDisplay;
   				 $publishedOn = $item->snippet->publishedAt;
   				 $likeCount = $item->snippet->likeCount;


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

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

   	 
   	 } // if resp

   	 
    
?>

Here is the output:

JSON decoded

id :z12nuf2z1kfzcnzx004chrljwqmqinyjuvo0k”I understand Japanese and this is beautiful ❤” by pratiksha sharma

On 2017-05-27T15:59:27.000Z , Likes :0

 

Sample code to list all the replies to a Comment.

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


   	 $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->authorDisplayName;
   				 $authorPic = $item->snippet->authorProfileImageUrl;
   				 $authorChannelUrl = $item->snippet->authorChannelUrl;
   				 $authorChannelId = $item->snippet->authorChannelId->value;
   				 
   				 $textDisplay = $item->snippet->textDisplay;
   				 $publishedOn = $item->snippet->publishedAt;
   				 $likeCount = $item->snippet->likeCount;


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


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

   	 
   	 } // if resp

   	 
    
?>

Here is the output:

JSON decoded

id :z13uzrmbmmupwdzj404cdtij0xikjh1piqg0k.1495727233478415″Debdoot Basu Ray What song?” by Unie Bagares

On 2017-05-25T15:47:13.000Z , Likes :0

id :z13uzrmbmmupwdzj404cdtij0xikjh1piqg0k.1495723688903897″Unie Bagares name of the song please” by Debdoot Basu Ray

On 2017-05-25T14:48:08.000Z , Likes :0

id :z13uzrmbmmupwdzj404cdtij0xikjh1piqg0k.1494761304885752″Unie Bagares the storyline 5cm per second is better than kimi no nawa” by Fadjar Ashari

On 2017-05-14T11:28:24.000Z , Likes :1

id :z13uzrmbmmupwdzj404cdtij0xikjh1piqg0k.1494759654220852″And for some reason, 5cmps and your name is kind of similar.” by Unie Bagares

On 2017-05-14T11:00:54.000Z , Likes :0

Be the first to comment

Leave a Reply

Your email address will not be published.


*