返回与 API 请求中指定的查询参数匹配的搜索结果集合。默认情况下,搜索结果集会标识匹配的 video、channel 和 playlist 资源,但您也可以配置查询,以便仅检索特定类型的资源。
配额影响:每天 100 次调用。调用此方法会消耗搜索查询配额存储桶中的 1 个单位配额。
常见应用场景
请求
HTTP 请求
GET https://www.googleapis.com/youtube/v3/search
参数
下表列出了此查询支持的参数。列出的所有参数均为查询参数。
| 参数 | ||
|---|---|---|
| 必需参数 | ||
part |
stringpart 参数指定一个逗号分隔列表,其中包含 API 响应将包含的一个或多个 search 资源属性。将参数值设置为 snippet。
|
|
| 过滤条件(指定以下参数中的 0 个或 1 个) | ||
forContentOwner |
boolean此参数只能在经过适当授权的请求中使用,并且仅供 YouTube 内容合作伙伴使用。 forContentOwner 参数会将搜索范围限制为仅检索由 onBehalfOfContentOwner 参数标识的内容所有者拥有的视频。如果 forContentOwner 设置为 true,则请求还必须满足以下要求:
|
|
forDeveloper |
boolean此参数只能在经过适当授权的请求中使用。 forDeveloper 参数会限制搜索,使其仅检索通过开发者的应用或网站上传的视频。API 服务器会使用请求的授权凭据来识别开发者。forDeveloper 参数可以与可选搜索参数(例如 q 参数)结合使用。对于此功能,每个上传的视频都会自动标记有与 Google Developers Console 中开发者的应用相关联的项目编号。 当搜索请求随后将 forDeveloper 参数设置为 true 时,API 服务器会使用请求的授权凭据来识别开发者。因此,开发者可以将结果限制为通过开发者自己的应用或网站上传的视频,但不能限制为通过其他应用或网站上传的视频。 |
|
forMine |
boolean此参数只能在经过适当授权的请求中使用。 forMine 参数用于限制搜索范围,仅检索经过身份验证的用户拥有的视频。如果您将此参数设置为 true,则 type 参数的值也必须设置为 video。此外,在同一请求中,以下其他参数均不能设置:videoDefinition、videoDimension、videoDuration、videoEmbeddable、videoLicense、videoPaidProductPlacement、videoSyndicated、videoType。 |
|
| 可选参数 | ||
channelId |
stringchannelId 参数表示 API 响应应仅包含由渠道创建的资源。注意:如果您的请求为 channelId 参数指定了值,并将 type 参数值设置为 video,但未设置 forContentOwner、forDeveloper 或 forMine 过滤条件,则搜索结果最多只能包含 500 个视频。 |
|
channelType |
string借助 channelType 参数,您可以将搜索范围限定在特定类型的频道内。可接受的值包括:
|
|
eventType |
stringeventType 参数会将搜索范围限制为广播事件。如果您为此参数指定了值,则还必须将 type 参数的值设置为 video。可接受的值包括:
|
|
location |
stringlocation 参数与 locationRadius 参数结合使用,可定义一个圆形地理区域,并将搜索范围限制为在元数据中指定了该区域内地理位置的视频。参数值是一个字符串,用于指定纬度/经度坐标,例如 (37.42307,-122.08427)。
location 参数指定了值,但未同时为 locationRadius 参数指定值,则 API 会返回错误。注意:如果您为此参数指定了值,还必须将 type 参数的值设置为 video。
| |
locationRadius |
stringlocationRadius 参数与 location 参数结合使用,可定义圆形地理区域。参数值必须是浮点数,后跟度量单位。有效的测量单位包括 m、km、ft 和 mi。例如,有效的参数值包括 1500m、5km、10000ft 和 0.75mi。该 API 不支持大于 1,000 公里的 locationRadius 参数值。注意:如需了解详情,请参阅 location 参数的定义。 |
|
maxResults |
unsigned integermaxResults 参数用于指定结果集中应返回的最大项数。可接受的值为 0 到 50(含边界值)。默认值为 5。 |
|
onBehalfOfContentOwner |
string此参数只能在经过适当授权的请求中使用。注意:此参数仅供 YouTube 内容合作伙伴使用。 onBehalfOfContentOwner 参数表示相应请求的授权凭据标识的是一位 YouTube 内容管理系统用户,该用户代表参数值中指定的内容所有者行事。此参数适用于拥有和管理许多不同 YouTube 频道的 YouTube 内容合作伙伴。内容所有者只需进行一次身份验证,即可访问其所有视频和频道数据,而无需为每个频道提供身份验证凭证。用户用于身份验证的内容管理系统账号必须与指定的 YouTube 内容所有者相关联。 |
|
order |
stringorder 参数用于指定在 API 响应中对资源进行排序的方法。默认值为 relevance。可接受的值包括:
|
|
pageToken |
stringpageToken 参数用于标识应返回的结果集中的特定页面。在 API 响应中,nextPageToken 和 prevPageToken 属性用于标识可检索的其他网页。 |
|
publishedAfter |
datetimepublishedAfter 参数表示 API 响应应仅包含在指定时间或之后创建的资源。该值是采用 RFC 3339 格式的日期时间值 (1970-01-01T00:00:00Z)。 |
|
publishedBefore |
datetimepublishedBefore 参数表示 API 响应应仅包含在指定时间之前或指定时间创建的资源。该值是采用 RFC 3339 格式的日期时间值 (1970-01-01T00:00:00Z)。 |
|
q |
stringq 参数指定要搜索的查询字词。您的请求还可以使用布尔值 NOT ( -) 和 OR (|) 运算符来排除视频或查找与多个搜索字词之一相关联的视频。例如,如需搜索与“boating”或“sailing”匹配的视频,请将 q 参数值设置为 boating|sailing。同样,如需搜索与“boating”或“sailing”匹配但不与“fishing”匹配的视频,请将 q 参数值设置为 boating|sailing -fishing。请注意,在 API 请求中发送竖线字符时,必须对其进行网址转义。管道字符的网址转义值为 %7C。 |
|
regionCode |
stringregionCode 参数指示 API 返回可在指定国家/地区观看的视频的搜索结果。参数值是 ISO 3166-1 alpha-2 国家/地区代码。 |
|
relevanceLanguage |
stringrelevanceLanguage 参数指示 API 返回与指定语言最相关的搜索结果。参数值通常是 ISO 639-1 双字母语言代码。不过,您应使用值 zh-Hans 表示简体中文,使用值 zh-Hant 表示繁体中文。请注意,如果其他语言的搜索结果与搜索查询字词高度相关,系统仍会返回这些结果。 |
|
safeSearch |
stringsafeSearch 参数指示搜索结果是否应包含受限内容以及标准内容。可接受的值包括:
|
|
topicId |
stringtopicId 参数表示 API 响应应仅包含与指定主题相关的资源。该值用于标识 Freebase 主题 ID。重要提示:由于 Freebase 和 Freebase API 已被弃用,自 2017 年 2 月 27 日起, topicId 参数开始以不同的方式运行。当时,YouTube 开始支持一小部分精选主题 ID,您只能使用这一小部分 ID 作为此参数的值。 |
|
type |
stringtype 参数会限制搜索查询,使其仅检索特定类型的资源。该值是以逗号分隔列表形式表示的资源类型。默认值为 video,channel,playlist。可接受的值包括:
|
|
videoCaption |
stringvideoCaption 参数用于指示 API 是否应根据视频是否包含字幕来过滤视频搜索结果。如果您为此参数指定了值,还必须将 type 参数的值设置为 video。可接受的值包括:
|
|
videoCategoryId |
stringvideoCategoryId 参数会根据视频的类别过滤视频搜索结果。如果您为此参数指定了值,则还必须将 type 参数的值设置为 video。 |
|
videoDefinition |
string借助 videoDefinition 参数,您可以限制搜索结果仅包含高清晰度 (HD) 或标清 (SD) 视频。高清视频至少可以 720p 的分辨率播放,但也可能支持更高的分辨率(例如 1080p)。如果您为此参数指定了值,则还必须将 type 参数的值设置为 video。可接受的值包括:
|
|
videoDimension |
string借助 videoDimension 参数,您可以将搜索范围限制为仅检索 2D 或 3D 视频。如果您为此参数指定了值,则还必须将 type 参数的值设置为 video。可接受的值包括:
|
|
videoDuration |
stringvideoDuration 参数会根据视频时长过滤视频搜索结果。如果您为此参数指定了值,则还必须将 type 参数的值设置为 video。可接受的值包括:
|
|
videoEmbeddable |
stringvideoEmbeddable 参数可让您将搜索范围限制为只能嵌入到网页中的视频。如果您为此参数指定了值,则还必须将 type 参数的值设置为 video。可接受的值包括:
|
|
videoLicense |
stringvideoLicense 参数可过滤搜索结果,以便仅包含具有特定许可的视频。YouTube 允许视频上传者为每个视频选择附加知识共享许可或标准 YouTube 许可。如果您为此参数指定了值,则还必须将 type 参数的值设置为 video。可接受的值包括:
|
|
videoPaidProductPlacement |
stringvideoPaidProductPlacement 参数会过滤搜索结果,仅包含创作者已声明包含付费宣传内容的视频。如果您为此参数指定了值,则还必须将 type 参数的值设置为 video。可接受的值包括:
|
|
videoSyndicated |
string借助 videoSyndicated 参数,您可以将搜索范围限制为仅包含可在 youtube.com 以外的网站上播放的视频。如果您为此参数指定了值,还必须将 type 参数的值设置为 video。可接受的值包括:
|
|
videoType |
string借助 videoType 参数,您可以将搜索范围限定为特定类型的视频。如果您为此参数指定了值,则还必须将 type 参数的值设置为 video。可接受的值包括:
|
|
请求正文
调用此方法时,请勿提供请求正文。
响应
如果成功,此方法将返回采用以下结构的响应正文:
{
"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 |
objectpageInfo 对象封装了结果集的分页信息。 |
pageInfo.totalResults |
integer结果集中的结果总数。请注意,该值是近似值,可能不代表确切值。此外,最大值为 1,000,000。 您不应使用此值来创建分页链接。而是应使用 nextPageToken 和 prevPageToken 属性值来确定是否显示分页链接。 |
pageInfo.resultsPerPage |
integerAPI 响应中包含的结果数。 |
items[] |
list符合搜索条件的结果列表。 |
示例
注意:以下代码示例可能并未涵盖所有支持的编程语言。如需查看支持的语言列表,请参阅客户端库文档。
Apps 脚本
此函数会搜索与关键字“dogs”相关的视频。搜索结果的视频 ID 和标题会记录到 Apps 脚本的日志中。请注意,此示例将结果限制为 25 个。如需返回更多结果,请按照以下文档中的说明传递其他参数:https://developers.google.com/youtube/data/reference/rest/v3/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 |
请求包含无效的搜索过滤条件和/或限制条件组合。请注意,如果您将 forContentOwner 或 forMine 参数设置为 true,则必须将 type 参数设置为 video。如果您为 eventType、videoCaption、videoCategoryId、videoDefinition、videoDimension、videoDuration、videoEmbeddable、videoLicense、videoSyndicated 或 videoType 参数设置了值,则还必须将 type 参数设置为 video。 |
试试看!
使用 APIs Explorer 调用此 API,并查看 API 请求和响应。