YouTube

Search: list

experimental feature
The YouTube Data API (v3) is an experimental API version, which means it is still in development. We'll be adding many more features to the API while it is still an experimental version. Until the experimental label is removed, however, the Deprecation Policy for YouTube APIs won't apply to this version as discussed in the API Terms of Service.

Returns a collection of search results that match the query parameters specified in the API request. By default, a search result set identifies matching video, channel, and playlist resources, but you can also configure queries to only retrieve a specific type of resource. Try it now or see an example.

Request

HTTP request

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

Parameters

Parameter name Value Description
Required parameters
part string The part parameter specifies a comma-separated list of one or more search resource properties that the API response will include. The part names that you can include in the parameter value are id and snippet.

If the parameter identifies a property that contains child properties, the child properties will be included in the response. For example, in a search result, the snippet property contains other properties that identify the result's title, description, and so forth. If you set part=snippet, the API response will also contain all of those nested properties.
Filters (specify exactly one of the following parameters)
q string The q parameter specifies the query term to search for.
relatedToVideo string The relatedToVideo parameter retrieves a list of videos that are related to the video that the parameter value identifies. The parameter value must be set to a YouTube video ID and, if you are using this parameter, the type parameter must be set to video.
Optional parameters
maxResults unsigned integer The maxResults parameter specifies the maximum number of items that should be returned in the result set. Acceptable values are 0 to 50, inclusive. The default value is 5.
order string The order parameter specifies the method that will be used to order resources in the API response. The default value is SEARCH_SORT_RELEVANCE.

Acceptable values are:
  • date – Resources are sorted in reverse chronological order based on the date they were created.
  • rating – Resources are sorted from highest to lowest rating.
  • relevance – Resources are sorted based on their relevance to the search query. This is the default value for this parameter.
  • view_count – Resources are sorted from highest to lowest number of views.
published string The published parameter indicates that the API response should only contain resources created within the specified time period.

Acceptable values are:
  • any – Do not filter results based on their creation date. This is the default value.
  • thisMonth – Return videos that were uploaded within the past month.
  • thisWeek – Return videos that were uploaded within the past week.
  • today – Return videos that were uploaded today.
type string The type parameter restricts a search query to only retrieve a particular type of resource. The default value is video,channel,playlist.
videoCaption string The videoCaption parameter indicates whether the API should filter video search results based on whether they have captions.

Acceptable values are:
  • any – Do not filter results based on caption availability.
  • closedCaption – Only include videos that have captions.
  • none – Only include videos that do not have captions.
videoDefinition string The videoDefinition parameter lets you restrict a search to only include either high definition (HD) or standard definition (SD) videos. HD videos are available for playback in at least 720p, though higher resolutions, like 1080p, might also be available.

Acceptable values are:
  • any – Return all videos, regardless of their resolution.
  • high – Only retrieve HD videos.
  • standard – Only retrieve videos in standard definition.
videoDimension string The videoDimension parameter lets you restrict a search to only retrieve 2D or 3D videos.

Acceptable values are:
  • 2d – Restrict search results to exclude 3D videos.
  • 3d – Restrict search results to only include 3D videos.
  • any – Include both 3D and non-3D videos in returned results. This is the default value.
videoDuration string The videoDuration parameter filters video search results based on their duration.

Acceptable values are:
  • any – Do not filter video search results based on their duration. This is the default value.
  • long – Only include videos longer than 20 minutes.
  • medium – Only include videos that are between four and 20 minutes long (inclusive).
  • short – Only include videos that are less than four minutes long.
videoLicense string The videoLicense parameter filters search results to only include videos with a particular license. YouTube lets video uploaders choose to attach either the Creative Commons license or the standard YouTube license to each of their videos.

Acceptable values are:
  • any – Return all videos, regardless of which license they have, that match the query parameters.
  • creativeCommon – Only return videos that have a Creative Commons license. Users can reuse videos with this license in other videos that they create. Learn more.
  • youtube – Only return videos that have the standard YouTube license.
topicId string The topicId parameter indicates that the API response should only contain resources associated with the specified topic. The value identifies a Freebase topic ID.
pageToken string The pageToken parameter identifies a specific page in the result set that should be returned. In an API response, the nextPageToken and prevPageToken properties identify other pages that could be retrieved.

Request body

Do not provide a request body when calling this method.

Response

If successful, this method returns a response body with the following structure:

{
  "kind": "youtube#searchListResponse",
  "etag": etag,
  "pageInfo": {
    "totalResults": integer,
    "resultsPerPage": integer
  },
  "nextPageToken": string,
  "prevPageToken": string,
  "items": [
    search result
  ]
}

Properties

The following table defines the properties that appear in a search result:

Property name Value Description
kind string The type of the API response. For this operation, the value will be youtube#searchListResponse.
etag etag The ETag for the response.
pageInfo nested object The pageInfo object encapsulates paging information for the search result set.
pageInfo.totalResults integer The total number of results in the result set.
nextPageToken string The token that can be used as the value of the pageToken parameter to retrieve the next page in the result set.
prevPageToken string The token that can be used as the value of the pageToken parameter to retrieve the previous page in the result set.
items[] list A list of results that match the search criteria.

Examples

Note: The code samples below may not represent all supported programming languages. See the client libraries documentation for a list of supported languages.

PHP

This example uses the PHP client library.

<?php
$htmlBody = <<<END
<form method="GET">
  <div>
    Search Term: <input type="search" id="q" name="q" placeholder="Enter Search Term">
  </div>
  <div>
    Max Results: <input type="number" id="maxResults" name="maxResults" min="1" max="50" step="1" value="25">
  </div>
  <input type="submit" value="Search">
</form>
END;

if ($_GET['q'] && $_GET['maxResults']) {
  // Call set_include_path() as needed to point to your client library.
  require_once 'Google_Client.php';
  require_once 'contrib/Google_YoutubeService.php';

  /* Set $DEVELOPER_KEY to the "API key" value from the "Access" tab of the
  Google APIs Console <http://code.google.com/apis/console#access>
  Please ensure that you have enabled the YouTube Data API for your project. */
  $DEVELOPER_KEY = 'REPLACE_ME';

  $client = new Google_Client();
  $client->setDeveloperKey($DEVELOPER_KEY);

  $youtube = new Google_YoutubeService($client);

  try {
    $searchResponse = $youtube->search->listSearch('id,snippet', array(
      'q' => $_GET['q'],
      'maxResults' => $_GET['maxResults'],
    ));

    $videos = '';
    $channels = '';
    $playlists = '';

    foreach ($searchResponse['items'] as $searchResult) {
      switch ($searchResult['id']['kind']) {
        case 'youtube#video':
          $videos .= sprintf('<li>%s (%s)</li>', $searchResult['snippet']['title'],
            $searchResult['id']['videoId']);
          break;
        case 'youtube#channel':
          $channels .= sprintf('<li>%s (%s)</li>', $searchResult['snippet']['title'],
            $searchResult['id']['channelId']);
          break;
        case 'youtube#playlist':
          $playlists .= sprintf('<li>%s (%s)</li>', $searchResult['snippet']['title'],
            $searchResult['id']['playlistId']);
          break;
      }
    }

    $htmlBody .= <<<END
    <h3>Videos</h3>
    <ul>$videos</ul>
    <h3>Channels</h3>
    <ul>$channels</ul>
    <h3>Playlists</h3>
    <ul>$playlists</ul>
END;
  } catch (Google_ServiceException $e) {
    $htmlBody .= sprintf('<p>A service error occurred: <code>%s</code></p>',
      htmlspecialchars($e->getMessage()));
  } catch (Google_Exception $e) {
    $htmlBody .= sprintf('<p>An client error occurred: <code>%s</code></p>',
      htmlspecialchars($e->getMessage()));
  }
}
?>

<!doctype html>
<html>
  <head>
    <title>YouTube Search</title>
  </head>
  <body>
    <?=$htmlBody?>
  </body>
</html>

Python

This example uses the Python client library.

#!/usr/bin/python

from apiclient.discovery import build
from optparse import OptionParser

# Set DEVELOPER_KEY to the "API key" value from the "Access" tab of the
# Google APIs Console http://code.google.com/apis/console#access
# Please ensure that you have enabled the YouTube Data API for your project.
DEVELOPER_KEY = "REPLACE_ME"
YOUTUBE_API_SERVICE_NAME = "youtube"
YOUTUBE_API_VERSION = "v3"

def youtube_search(options):
  youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION,
    developerKey=DEVELOPER_KEY)

  search_response = youtube.search().list(
    q=options.q,
    part="id,snippet",
    maxResults=options.maxResults
  ).execute()

  videos = []
  channels = []
  playlists = []

  for search_result in search_response.get("items", []):
    if search_result["id"]["kind"] == "youtube#video":
      videos.append("%s (%s)" % (search_result["snippet"]["title"],
                                 search_result["id"]["videoId"]))
    elif search_result["id"]["kind"] == "youtube#channel":
      channels.append("%s (%s)" % (search_result["snippet"]["title"],
                                   search_result["id"]["channelId"]))
    elif search_result["id"]["kind"] == "youtube#playlist":
      playlists.append("%s (%s)" % (search_result["snippet"]["title"],
                                    search_result["id"]["playlistId"]))

  print "Videos:\n", "\n".join(videos), "\n"
  print "Channels:\n", "\n".join(channels), "\n"
  print "Playlists:\n", "\n".join(playlists), "\n"


if __name__ == "__main__":
  parser = OptionParser()
  parser.add_option("--q", dest="q", help="Search term",
    default="Google")
  parser.add_option("--max-results", dest="maxResults",
    help="Max results", default=25)
  (options, args) = parser.parse_args()

  youtube_search(options)

Errors

The table below identifies error messages that the API could return in response to a call to this method.

Error name Reason Likely cause
badRequest invalidVideoId The relatedToVideo parameter specified an invalid video ID.
badRequest invalidSearchFilter The request contains an invalid combination of search filters and/or restrictions.

Try it!

Use the API Explorer to call this method on live data and see the API request and response.

Authentication required

You need to be signed in with Google+ to do that.

Signing you in...

Google Developers needs your permission to do that.