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 API 伺服器會使用要求的授權憑證來識別開發人員。

true因此,開發人員只能將結果限制在透過開發人員的應用程式或網站上傳的影片,而非從其他應用程式或網站上傳的影片。
forMine boolean
這個參數只能在適當的授權要求中使用。forMine 參數會將搜尋範圍限制為由通過驗證的使用者擁有的影片。如果將這個參數設為 true,則 type 參數的值也必須設定為 video。此外,您無法在同一項要求中設定下列任何其他參數:videoDefinitionvideoDimensionvideoDurationvideoEmbeddablevideoLicensevideoPaidProductPlacementvideoSyndicatedvideoType
選用參數
channelId string
channelId 參數表示 API 回應只能包含 API 建立的資源。

注意:如果您的要求為 channelId 參數指定值,並將 type 參數值設為 video,則搜尋結果最多不得超過 500 部影片,但不含 forContentOwnerforDeveloperforMine 其中一個篩選器。
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 CMS 使用者,代表了該參數值在內容擁有者中指定的內容擁有者。這個參數的適用對象為擁有及管理許多不同 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 會嘗試從搜尋結果範圍中排除所有受限制的內容。視內容性質而定,搜尋結果可能會遭到移除,也可能降低在搜尋結果中的排名。
topicId string
topicId 參數表示 API 回應只能包含與指定主題相關聯的資源。這個值可識別 Freebase 主題 ID。

重要事項:隨著 Freebase API 和 Freebase API 的淘汰,topicId 參數的運作方式自 2017 年 2 月 27 日起開始運作。當時,YouTube 已開始支援一組精選主題 ID,因此您只能將這組 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 – 只包含不超過 4 分鐘的影片。
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 個。

請勿使用這個值來建立分頁連結。因此,請使用 nextPageTokenprevPageToken 屬性值來判斷是否要顯示分頁連結。
pageInfo.resultsPerPage integer
API 回應中包含的結果數量。
items[] list
符合搜尋條件的結果清單。

範例

注意:下列程式碼範例可能無法完整支援所有程式設計語言。如需支援的語言清單,請參閱用戶端程式庫說明文件。

Apps Script

這個函式會搜尋與關鍵字「狗」相關的影片。搜尋結果的影片 ID 和標題會記錄在 Apps Script 的記錄中。

請注意,這個範例會將結果範圍限制在 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);
  }
}

查看

這個程式碼範例會呼叫 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,也必須將 type 參數設為 video

試試看!

使用 APIs Explorer 呼叫這個 API 並查看 API 要求和回應。