Search: list

傳回符合 API 要求中指定查詢參數的搜尋結果集合。根據預設,搜尋結果集會找出相符的 video、channel 和 playlist 資源,但您也可以設定查詢,只擷取特定類型的資源。

配額影響:每天 100 次通話。呼叫這個方法時,搜尋查詢配額儲存區的配額費用為 1 個單位。

常見用途

要求

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。
  • 無法設定下列其他參數:videoDefinition、videoDimension、videoDuration、videoEmbeddable、videoLicense、videoPaidProductPlacement、videoSyndicated、videoType。
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 string
channelId 參數表示 API 回應應只包含頻道建立的資源。

注意:如果要求指定 channelId 參數的值,並將 type 參數值設為 video,但未設定 forContentOwner、forDeveloper 或 forMine 篩選器,則搜尋結果最多只能顯示 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 參數搭配使用,可定義圓形地理區域。

參數值必須是浮點數,後接測量單位。有效測量單位為 m、km、ft 和 mi。舉例來說,有效的參數值包括 1500m、5km、10000ft 和 0.75mi。API 不支援大於 1000 公里的 locationRadius 參數值。

注意:詳情請參閱 location 參數的定義。
maxResults unsigned integer
maxResults 參數指定結果集中應傳回的項目數量上限。可接受的值為 0 至 50 (含)。預設值為 5。

onBehalfOfContentOwner string
這個參數只能用於授權要求。注意:這個參數僅供 YouTube 內容合作夥伴使用。

onBehalfOfContentOwner 參數表示要求的授權憑證會識別 YouTube CMS 使用者,該使用者代表參數值中指定的內容擁有者。這個參數適用於擁有及管理多個不同 YouTube 頻道的 YouTube 內容合作夥伴。內容擁有者只要驗證一次,就能存取所有影片和頻道資料,不必為每個頻道提供驗證憑證。使用者驗證的 CMS 帳戶必須連結至指定的 YouTube 內容擁有者。
order string
order 參數會指定用於排序 API 回應中資源的方法。預設值為 relevance。

可接受的值如下:
  • date:資源會依建立日期,按時間倒序排列。注意:這項功能依賴搜尋索引,因此新內容的索引作業可能會延遲,或傳回不完整的結果集。如要確實擷取頻道最近上傳的影片,請勿使用 search.list。請改用 playlistItems.list 方法擷取頻道的上傳內容播放清單。
  • rating:資源會依評分由高到低排序。注意:這項評分是根據內部演算法分數計算得出,不完全等同於按讚數遞減。
  • relevance:資源會依據與搜尋查詢的關聯性排序。這是這個參數的預設值。
  • title - 資源會依標題的字母順序排序。
  • videoCount:頻道會依上傳影片數量遞減排序。
  • viewCount:資源會依觀看次數由高至低排序。直播期間,影片會依同時觀看人數排序。
pageToken string
pageToken 參數會識別結果集中的特定網頁,並傳回該網頁。在 API 回應中,nextPageToken 和 prevPageToken 屬性會識別可擷取的其他頁面。
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 (|) 運算子,排除影片或尋找與多個搜尋字詞之一相關聯的影片。舉例來說,如要搜尋符合「boating」或「sailing」的影片,請將 q 參數值設為 boating|sailing。同樣地,如要搜尋符合「boating」或「sailing」但不符合「fishing」的影片,請將 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 會嘗試從搜尋結果中排除所有限制內容。視內容而定,搜尋結果可能會從搜尋結果中移除,或在搜尋結果中降級。
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) 影片。HD 高畫質影片至少能以 720p 畫質播放,但也可能提供 1080p 等更高解析度。如果指定這個參數的值,也必須將 type 參數的值設為 video。

可接受的值如下:
  • any:傳回所有影片,不論解析度為何。
  • high - 只擷取 HD 高畫質影片。
  • 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 - 只能加入長度不到四分鐘的影片。
videoEmbeddable string
videoEmbeddable 參數可讓您限制搜尋範圍,只搜尋可嵌入網頁的影片。如要為這個參數指定值,也必須將 type 參數的值設為 video。

可接受的值包括:
  • any - 傳回所有影片,無論是否可嵌入。
  • true:只擷取可嵌入的影片。
videoLicense string
videoLicense 參數會篩選搜尋結果,只顯示具有特定授權的影片。YouTube 允許影片上傳者選擇為每部影片附加創用 CC 授權或標準 YouTube 授權。如果指定這個參數的值,也必須將 type 參數的值設為 video。

可接受的值如下:
  • any:傳回符合查詢參數的所有影片,無論影片的授權為何。
  • creativeCommon:只傳回具有創用 CC 授權的影片。使用者可以在自己製作的其他影片中,重複使用這類授權影片。瞭解詳情。
  • 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。

您不應使用這個值建立分頁連結。請改用 nextPageToken 和 prevPageToken 屬性值,判斷是否要顯示分頁連結。
pageInfo.resultsPerPage integer
API 回應中包含的結果數量。
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 要求和回應。