Search: list

返回与 API 请求中指定的查询参数匹配的一系列搜索结果。默认情况下,搜索结果集可识别匹配的 videochannelplaylist 资源,但您也可以将查询配置为仅检索特定类型的资源。

配额影响:调用此方法的配额费用为 100 个单位。

常见使用场景

请求

HTTP 请求

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

参数

下表列出了此查询支持的参数。列出的所有参数都是查询参数。

参数
必需参数
part string
part 参数用于指定 API 响应将包含的一个或多个 search 资源属性的逗号分隔列表。将参数值设为 snippet
过滤条件(指定以下 0 或 1 个参数)
forContentOwner boolean
此参数只能在适当的授权请求中使用,它专供 YouTube 内容合作伙伴使用。

forContentOwner 参数用于将搜索限制为仅检索由 onBehalfOfContentOwner 参数标识的内容所有者拥有的视频。如果 forContentOwner 设置为 true,请求还必须满足以下要求:
  • 必须提供 onBehalfOfContentOwner 参数。
  • 授权请求的用户必须使用与指定内容所有者关联的帐号。
  • 必须将 type 参数值设为 video
  • 其他任何参数都不能设置:videoDefinitionvideoDimensionvideoDurationvideoEmbeddablevideoLicensevideoPaidProductPlacementvideoSyndicatedvideoType
forDeveloper boolean
此参数只能在适当的授权请求中使用。forDeveloper 参数将搜索限制为仅检索通过开发者的应用或网站上传的视频。API 服务器使用请求的授权凭据来识别开发者。forDeveloper 参数可与 q 参数等可选搜索参数结合使用。

对于此功能,每个上传的视频都会自动使用与 Google Developers Console 中开发者的应用相关联的项目编号进行标记。

搜索请求随后将 forDeveloper 参数设置为 true 时,API 服务器会使用请求的授权凭据来识别开发者。因此,开发者可以将结果限制为通过开发者自己的应用或网站上传的视频,但无法限制通过其他应用或网站上传的视频。
forMine boolean
此参数只能在适当的授权请求中使用。forMine 参数将搜索限制为仅检索经过身份验证的用户拥有的视频。如果您将此参数的值设为 true,则 type 参数的值也必须设为 video。此外,您无法在同一请求中设置以下任何其他参数:videoDefinitionvideoDimensionvideoDurationvideoEmbeddablevideoLicensevideoPaidProductPlacementvideoSyndicatedvideoType
可选参数
channelId string
channelId 参数用于指示 API 响应仅包含频道创建的资源。

注意:如果您的请求为 channelId 参数指定了值,并将 type 参数值设为 video,但搜索结果并未设置 forContentOwnerforDeveloperforMine 过滤条件之一,则搜索结果不得超过 500 个视频。
channelType string
您可以使用 channelType 参数将搜索范围限制为特定类型的渠道。

可接受的值包括:
  • any - 返回所有频道。
  • show - 仅检索节目。
eventType string
eventType 参数用于限制搜索广播事件。如果您为此参数的值指定了值,则还必须将 type 参数的值设为 video

可接受的值:
  • completed - 仅包含已完成的广播。
  • live - 仅包含活跃广播。
  • upcoming - 仅包含即将播出的直播。
location string
location 形参与 locationRadius 形参结合使用可定义一个圆形地理区域,还可将搜索范围限定在其元数据中指定该区域内的地理位置。参数值是一个字符串,用于指定纬度/经度坐标,例如 (37.42307,-122.08427)。

  • location 参数值用于标识区域中心的点。
  • locationRadius 参数用于指定与视频相关联的营业地点与此位置相关联的视频的最大距离,以便视频仍包含在搜索结果中。
。如果您的请求指定了 location 参数的值,但未指定 locationRadius 参数的值,则 API 会返回错误。

注意:如果您为此参数指定值,则还必须将 type 参数的值设为 video
locationRadius string
locationRadius 形参与 location 形参定义了圆形地理区域。

此形参必须是一个浮点数,后跟衡量单位。有效的衡量单位包括 mkmftmi。例如,有效的参数值包括 1500m5km10000ft0.75mi。该 API 不支持大于 1000 公里的 locationRadius 参数值。

注意:如需了解详情,请参阅 location 参数的定义。
maxResults unsigned integer
maxResults 参数用于指定结果集中应返回的商品数量上限。可接受的值为 050(含)。默认值为 5
onBehalfOfContentOwner string
此参数只能在适当的授权请求中使用。注意:此参数专供 YouTube 内容合作伙伴使用。

onBehalfOfContentOwner 参数表示请求的授权凭据用于标识代表参数值中指定的内容所有者行事的 YouTube 内容管理系统用户。此参数适用于拥有和管理许多不同 YouTube 频道的 YouTube 内容合作伙伴。借助此功能,内容所有者只需身份验证一次并访问所有视频和频道数据,而无需为每个频道提供身份验证凭据。用户身份验证所用的 CMS 帐号必须与指定的 YouTube 内容所有者相关联。
order string
order 参数用于指定将用于对 API 响应中的资源进行排序的方法。默认值为 relevance

可接受的值为:
  • date - 资源按照创建时间倒序排列。
  • rating - 资源按评分从高到低排序。
  • relevance - 资源按与搜索查询的相关性排序。这是此参数的默认值。
  • title - 资源按标题的字母顺序排序。
  • videoCount - 频道已上传的视频数量按降序排序。
  • viewCount - 资源按浏览次数从高到低排序。对于直播,视频会按直播的同时观看人数进行排序,
pageToken string
pageToken 参数用于标识结果集中应返回的特定网页。在 API 响应中,nextPageTokenprevPageToken 属性用于标识可检索的其他页面。
publishedAfter datetime
publishedAfter 参数用于指明 API 响应应仅包含在指定时间或之后创建的资源。该值是 RFC 3339 格式的日期时间值 (1970-01-01T00:00:00Z)。
publishedBefore datetime
publishedBefore 参数用于指明 API 响应应仅包含指定时间之前或在指定时间创建的资源。该值是 RFC 3339 格式的日期时间值 (1970-01-01T00:00:00Z)。
q string
q 参数用于指定要搜索的查询字词。

您的请求还可以使用布尔值 NOT (-) 和 OR (|) 运算符来排除视频或查找与多个搜索字词之一相关联的视频。例如,若要搜索与“泛舟”或“帆船”匹配的视频,请将 q 参数值设为 boating|sailing。同样,如需搜索与“帆船”或“帆船”匹配但不与“钓鱼”匹配的视频,请将 q 参数值设为 boating|sailing -fishing。请注意,在 API 请求中发送字符时,管道字符必须进行网址转义。竖线字符的网址转义值为 %7C
regionCode string
regionCode 参数用于指示 API 返回可在指定国家/地区观看的视频的搜索结果。此参数值是 ISO 3166-1 alpha-2 国家/地区代码。
relevanceLanguage string
relevanceLanguage 参数用于指示 API 返回与指定语言最相关的搜索结果。此参数值通常为 ISO 639-1(由两个字母组成)语言代码。不过,您应使用 zh-Hans 来表示简体中文,使用 zh-Hant 表示繁体中文。请注意,如果其他语言的结果与搜索查询字词高度相关,则仍会返回这些结果。
safeSearch string
safeSearch 参数用于指明搜索结果是否应包含受限内容以及标准内容。

可接受的值包括:
  • moderate – YouTube 会从搜索结果中滤除某些内容,并至少过滤掉您语言区域受限的内容。根据搜索结果的内容,我们可能会将其从搜索结果中移除或降低其在搜索结果中的排名。这是默认参数值。
  • none - YouTube 不会过滤搜索结果集。
  • strict – YouTube 会尝试从搜索结果中排除所有受限内容。YouTube 会根据搜索结果的内容,从搜索结果中删除某些搜索结果或将其降位。
topicId string
topicId 参数用于指示 API 响应只能包含与指定主题相关联的资源。此值用于标识 Freebase 主题 ID。

重要提示:由于 Freebase 和 Freebase API 已被弃用,因此 topicId 参数从 2017 年 2 月 27 日起开始工作。当时,YouTube 开始支持一小部分精选主题 ID,您只能使用一小部分 ID 作为此参数的值。

type string
type 参数可将搜索查询限制为仅检索特定类型的资源。该值是以英文逗号分隔的资源类型列表。默认值为 video,channel,playlist

可接受的值为:
  • channel
  • playlist
  • video
videoCaption string
videoCaption 参数用于指明 API 是否应根据视频字幕显示内容过滤视频搜索结果。如果您为此参数的值指定了值,则还必须将 type 参数的值设为 video

可接受的值:
  • any - 请勿根据字幕可用性过滤结果。
  • closedCaption - 仅包含包含字幕的视频。
  • none - 仅添加没有字幕的视频。
videoCategoryId string
videoCategoryId 参数可根据视频类别对视频搜索结果进行过滤。如果您指定此参数的值,则还必须将 type 参数的值设为 video
videoDefinition string
您可以使用 videoDefinition 参数将搜索限制为仅包含高清 (HD) 或标清 (SD) 视频。高清视频支持最低 720p 的视频播放,不过也有可能采用 1080p 等较高分辨率。如果您为此参数的值指定了值,则还必须将 type 参数的值设为 video

可接受的值:
  • any - 返回所有视频,无论其分辨率如何。
  • high - 仅检索高清视频。
  • standard - 仅检索标清视频。
videoDimension string
您可以使用 videoDimension 参数将搜索限制为仅检索 2D 或 3D 视频。如果您为此参数的值指定了值,则还必须将 type 参数的值设为 video

可接受的值:
  • 2d - 将搜索结果限制为排除 3D 视频。
  • 3d - 将搜索结果限制为仅包含 3D 视频。
  • any - 在返回的结果中包括 3D 和非 3D 视频。这是默认值。
videoDuration string
videoDuration 参数会根据视频的时长过滤搜索结果。如果您为此参数的值指定了值,则还必须将 type 参数的值设为 video

可接受的值:
  • any - 请勿根据时长来过滤视频搜索结果。这是默认值。
  • long - 仅包含时长超过 20 分钟的视频。
  • medium - 仅包含时长在 4-20 分钟(含)之间的视频。
  • short - 仅包含时长不到 4 分钟的视频。
videoEmbeddable string
借助 videoEmbeddable 参数,您可以将搜索范围限定为只能嵌入到网页中的视频。如果您为此参数的值指定了值,则还必须将 type 参数的值设为 video

可接受的值:
  • any - 返回所有视频,无论是否可嵌入。
  • true - 仅检索可嵌入视频。
videoLicense string
videoLicense 参数用于过滤搜索结果,以便仅包含具有特定许可的视频。YouTube 允许视频上传者为每个视频选择附加知识共享许可或标准 YouTube 许可。如果您为此参数的值指定了值,则还必须将 type 参数的值设为 video

可接受的值:
  • any - 返回与查询参数匹配的所有视频,无论其拥有何种许可。
  • creativeCommon - 仅返回具有知识共享许可的视频。用户可以在自己创建的其他视频中重复使用使用此许可的视频。了解详情
  • youtube - 仅返回具有标准 YouTube 许可的视频。
videoPaidProductPlacement string
videoPaidProductPlacement 参数会过滤搜索结果,以便仅包含创作者标记为付费宣传内容的视频。如果您为此参数的值指定了值,则还必须将 type 参数的值设为 video

可接受的值:
  • any - 返回所有视频,无论它们是否包含付费宣传内容。
  • true - 仅检索包含付费宣传内容的视频。
videoSyndicated string
借助 videoSyndicated 参数,您可以将搜索范围限制为仅限可在 youtube.com 之外播放的视频。如果您为此参数指定了值,则还必须将 type 参数的值设为 video

可接受的值包括:
  • any - 返回所有视频(无论是否已整合)。
  • true - 仅检索整合视频。
videoType string
您可以使用 videoType 参数将搜索范围限制为特定类型的视频。如果您为此参数的值指定了值,则还必须将 type 参数的值设为 video

可接受的值:
  • any - 返回所有视频。
  • episode - 仅检索节目的剧集。
  • movie - 仅检索影片。

请求正文

调用此方法时,请勿提供请求正文。

响应

如果成功,此方法将返回采用以下结构的响应正文:

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

属性

下表定义了搜索结果中显示的属性:

属性
kind string
标识 API 资源类型。值为 youtube#searchListResponse
etag etag
此资源的 Etag。
nextPageToken string
可用作 pageToken 参数的值来检索结果集中的下一页的令牌。
prevPageToken string
可用作 pageToken 参数的值来检索结果集中的上一页的令牌。
regionCode string
搜索查询所用的地区代码。属性值是一个由两个字母构成的 ISO 国家/地区代码,用于标识区域。i18nRegions.list 方法会返回受支持区域的列表。默认值为 US。如果指定了不受支持的区域,YouTube 可能仍会选择其他区域(而不是默认值)来处理查询。
pageInfo object
pageInfo 对象用于封装结果集的分页信息。
pageInfo.totalResults integer
结果集中的结果总数。请注意,该值为近似值,并不代表确切值。此外,最大值为 1,000,000。

您不应使用此值来创建分页链接。请改为使用 nextPageTokenprevPageToken 属性值来确定是否显示分页链接。
pageInfo.resultsPerPage integer
API 响应中包含的结果数量。
items[] list
与搜索条件匹配的结果列表。

示例

注意:以下代码示例并不代表所有受支持的编程语言。如需查看支持的语言列表,请参阅客户端库文档。

Apps 脚本

此函数会搜索与关键字“狗”相关的视频。搜索结果的视频 ID 和标题会记录到 Apps 脚本的日志中。

请注意,此示例的结果数上限为 25。如需返回更多结果,请传递以下网址中所述的其他参数:https://developers.google.com/youtube/v3/docs/search/list
function searchByKeyword() {
  var results = YouTube.Search.list('id,snippet', {q: 'dogs', maxResults: 25});

  for(var i in results.items) {
    var item = results.items[i];
    Logger.log('[%s] Title: %s', item.id.videoId, item.snippet.title);
  }
}

Go

此代码示例会调用 API 的 search.list 方法,以检索与特定关键字相关联的搜索结果。

此示例使用 Go 客户端库

package main

import (
	"flag"
	"fmt"
	"log"
	"net/http"

	"google.golang.org/api/googleapi/transport"
	"google.golang.org/api/youtube/v3"
)

var (
	query      = flag.String("query", "Google", "Search term")
	maxResults = flag.Int64("max-results", 25, "Max YouTube results")
)

const developerKey = "YOUR DEVELOPER KEY"

func main() {
	flag.Parse()

	client := &http.Client{
		Transport: &transport.APIKey{Key: developerKey},
	}

	service, err := youtube.New(client)
	if err != nil {
		log.Fatalf("Error creating new YouTube client: %v", err)
	}

	// Make the API call to YouTube.
	call := service.Search.List("id,snippet").
		Q(*query).
		MaxResults(*maxResults)
	response, err := call.Do()
	handleError(err, "")

	// Group video, channel, and playlist results in separate lists.
	videos := make(map[string]string)
	channels := make(map[string]string)
	playlists := make(map[string]string)

	// Iterate through each item and add it to the correct list.
	for _, item := range response.Items {
		switch item.Id.Kind {
		case "youtube#video":
			videos[item.Id.VideoId] = item.Snippet.Title
		case "youtube#channel":
			channels[item.Id.ChannelId] = item.Snippet.Title
		case "youtube#playlist":
			playlists[item.Id.PlaylistId] = item.Snippet.Title
		}
	}

	printIDs("Videos", videos)
	printIDs("Channels", channels)
	printIDs("Playlists", playlists)
}

// Print the ID and title of each result in a list as well as a name that
// identifies the list. For example, print the word section name "Videos"
// above a list of video search results, followed by the video ID and title
// of each matching video.
func printIDs(sectionName string, matches map[string]string) {
	fmt.Printf("%v:\n", sectionName)
	for id, title := range matches {
		fmt.Printf("[%v] %v\n", id, title)
	}
	fmt.Printf("\n\n")
}

.NET

以下代码示例调用 API 的 search.list 方法来检索与特定关键字相关联的搜索结果。

此示例使用 .NET 客户端库

using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;

using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using Google.Apis.Upload;
using Google.Apis.Util.Store;
using Google.Apis.YouTube.v3;
using Google.Apis.YouTube.v3.Data;

namespace Google.Apis.YouTube.Samples
{
  /// <summary>
  /// YouTube Data API v3 sample: search by keyword.
  /// Relies on the Google APIs Client Library for .NET, v1.7.0 or higher.
  /// See https://developers.google.com/api-client-library/dotnet/get_started
  ///
  /// Set ApiKey to the API key value from the APIs & auth > Registered apps tab of
  ///   https://cloud.google.com/console
  /// Please ensure that you have enabled the YouTube Data API for your project.
  /// </summary>
  internal class Search
  {
    [STAThread]
    static void Main(string[] args)
    {
      Console.WriteLine("YouTube Data API: Search");
      Console.WriteLine("========================");

      try
      {
        new Search().Run().Wait();
      }
      catch (AggregateException ex)
      {
        foreach (var e in ex.InnerExceptions)
        {
          Console.WriteLine("Error: " + e.Message);
        }
      }

      Console.WriteLine("Press any key to continue...");
      Console.ReadKey();
    }

    private async Task Run()
    {
      var youtubeService = new YouTubeService(new BaseClientService.Initializer()
      {
        ApiKey = "REPLACE_ME",
        ApplicationName = this.GetType().ToString()
      });

      var searchListRequest = youtubeService.Search.List("snippet");
      searchListRequest.Q = "Google"; // Replace with your search term.
      searchListRequest.MaxResults = 50;

      // Call the search.list method to retrieve results matching the specified query term.
      var searchListResponse = await searchListRequest.ExecuteAsync();

      List<string> videos = new List<string>();
      List<string> channels = new List<string>();
      List<string> playlists = new List<string>();

      // Add each result to the appropriate list, and then display the lists of
      // matching videos, channels, and playlists.
      foreach (var searchResult in searchListResponse.Items)
      {
        switch (searchResult.Id.Kind)
        {
          case "youtube#video":
            videos.Add(String.Format("{0} ({1})", searchResult.Snippet.Title, searchResult.Id.VideoId));
            break;

          case "youtube#channel":
            channels.Add(String.Format("{0} ({1})", searchResult.Snippet.Title, searchResult.Id.ChannelId));
            break;

          case "youtube#playlist":
            playlists.Add(String.Format("{0} ({1})", searchResult.Snippet.Title, searchResult.Id.PlaylistId));
            break;
        }
      }

      Console.WriteLine(String.Format("Videos:\n{0}\n", string.Join("\n", videos)));
      Console.WriteLine(String.Format("Channels:\n{0}\n", string.Join("\n", channels)));
      Console.WriteLine(String.Format("Playlists:\n{0}\n", string.Join("\n", playlists)));
    }
  }
}

Ruby

此示例会调用该 API 的 search.list 方法来检索与特定关键字相关联的搜索结果。

此示例使用 Ruby 客户端库

#!/usr/bin/ruby

require 'rubygems'
gem 'google-api-client', '>0.7'
require 'google/api_client'
require 'trollop'

# Set DEVELOPER_KEY to the API key value from the APIs & auth > Credentials
# tab of
# {{ Google Cloud Console }} <{{ https://cloud.google.com/console }}>
# 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 get_service
  client = Google::APIClient.new(
    :key => DEVELOPER_KEY,
    :authorization => nil,
    :application_name => $PROGRAM_NAME,
    :application_version => '1.0.0'
  )
  youtube = client.discovered_api(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION)

  return client, youtube
end

def main
  opts = Trollop::options do
    opt :q, 'Search term', :type => String, :default => 'Google'
    opt :max_results, 'Max results', :type => :int, :default => 25
  end

  client, youtube = get_service

  begin
    # Call the search.list method to retrieve results matching the specified
    # query term.
    search_response = client.execute!(
      :api_method => youtube.search.list,
      :parameters => {
        :part => 'snippet',
        :q => opts[:q],
        :maxResults => opts[:max_results]
      }
    )

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

    # Add each result to the appropriate list, and then display the lists of
    # matching videos, channels, and playlists.
    search_response.data.items.each do |search_result|
      case search_result.id.kind
        when 'youtube#video'
          videos << "#{search_result.snippet.title} (#{search_result.id.videoId})"
        when 'youtube#channel'
          channels << "#{search_result.snippet.title} (#{search_result.id.channelId})"
        when 'youtube#playlist'
          playlists << "#{search_result.snippet.title} (#{search_result.id.playlistId})"
      end
    end

    puts "Videos:\n", videos, "\n"
    puts "Channels:\n", channels, "\n"
    puts "Playlists:\n", playlists, "\n"
  rescue Google::APIClient::TransmissionError => e
    puts e.result.body
  end
end

main

错误数

下表列出了 API 可能会在调用该方法时返回的错误消息。如需了解详情,请参阅错误消息文档。

错误类型 错误详情 说明
badRequest (400) invalidChannelId channelId”参数指定的渠道 ID 无效。
badRequest (400) invalidLocation location 和/或 locationRadius 参数值格式不正确。
badRequest (400) invalidRelevanceLanguage relevanceLanguage 参数值格式不正确。
badRequest (400) invalidSearchFilter 该请求包含无效搜索过滤条件和/或限制组合。请注意,如果您将 forContentOwnerforMine 参数设置为 true,则必须将 type 参数设为 video。如果您为 eventTypevideoCaptionvideoCategoryIdvideoDefinitionvideoDimensionvideoDurationvideoEmbeddablevideoLicensevideoSyndicatedvideoType 参数设置了值,还必须将 type 参数设置为 video

试试看!

使用 APIs Explorer 调用此 API 并查看 API 请求和响应。