傳回符合 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 |
stringchannelType 參數可將搜尋範圍限制在特定類型的頻道。可接受的值包括:
|
|
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 不支援大於 1000 公里的 locationRadius 參數值。注意:詳情請參閱 location 參數的定義。 |
|
maxResults |
unsigned integermaxResults 參數指定結果集中應傳回的項目數量上限。可接受的值為 0 至 50 (含)。預設值為 5。 |
|
onBehalfOfContentOwner |
string這個參數只能用於授權要求。注意:這個參數僅供 YouTube 內容合作夥伴使用。 onBehalfOfContentOwner 參數表示要求的授權憑證會識別 YouTube CMS 使用者,該使用者代表參數值中指定的內容擁有者。這個參數適用於擁有及管理多個不同 YouTube 頻道的 YouTube 內容合作夥伴。內容擁有者只要驗證一次,就能存取所有影片和頻道資料,不必為每個頻道提供驗證憑證。使用者驗證的 CMS 帳戶必須連結至指定的 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 已淘汰, topicId 參數自 2017 年 2 月 27 日起,運作方式已有所不同。當時,YouTube 開始支援一小組精選主題 ID,而您只能使用這組較小的 ID 做為這個參數的值。 |
|
type |
stringtype 參數會限制搜尋查詢,只擷取特定類型的資源。值是以半形逗號分隔的資源類型清單。預設值為 video,channel,playlist。可接受的值如下:
|
|
videoCaption |
stringvideoCaption 參數會指出 API 是否應根據影片是否有字幕,篩選影片搜尋結果。如果為這個參數指定值,則必須將 type 參數的值設為 video。可接受的值如下:
|
|
videoCategoryId |
stringvideoCategoryId 參數會根據類別篩選影片搜尋結果。如要為這個參數指定值,也必須將 type 參數的值設為 video。 |
|
videoDefinition |
stringvideoDefinition 參數可讓您限制搜尋範圍,只納入高畫質 (HD) 或標準畫質 (SD) 影片。HD 高畫質影片至少能以 720p 畫質播放,但也可能提供 1080p 等更高解析度。如果指定這個參數的值,也必須將 type 參數的值設為 video。可接受的值如下:
|
|
videoDimension |
stringvideoDimension 參數可將搜尋範圍限制為僅擷取 2D 或 3D 影片。如要為這個參數指定值,也必須將 type 參數的值設為 video。可接受的值包括:
|
|
videoDuration |
stringvideoDuration 參數會根據影片長度篩選搜尋結果。如果為這個參數指定值,則必須將 type 參數的值設為 video。可接受的值如下:
|
|
videoEmbeddable |
stringvideoEmbeddable 參數可讓您限制搜尋範圍,只搜尋可嵌入網頁的影片。如要為這個參數指定值,也必須將 type 參數的值設為 video。可接受的值包括:
|
|
videoLicense |
stringvideoLicense 參數會篩選搜尋結果,只顯示具有特定授權的影片。YouTube 允許影片上傳者選擇為每部影片附加創用 CC 授權或標準 YouTube 授權。如果指定這個參數的值,也必須將 type 參數的值設為 video。可接受的值如下:
|
|
videoPaidProductPlacement |
stringvideoPaidProductPlacement 參數會篩選搜尋結果,只納入創作者標示為付費宣傳內容的影片。如果指定這個參數的值,也必須將 type 參數的值設為 video。可接受的值如下:
|
|
videoSyndicated |
stringvideoSyndicated 參數可將搜尋範圍限制為只能在 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 Script
這個函式會搜尋與關鍵字「dogs」相關的影片。搜尋結果的影片 ID 和標題會記錄到 Apps Script 的記錄檔。請注意,這個範例會將結果限制為 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))); } } }
小茹
這個範例會呼叫 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 要求和回應。