Search: list

API リクエストで指定したクエリ パラメータに一致する検索結果のコレクションを返します。デフォルトでは、検索結果のセットでは一致する videochannelplaylist の各リソースが識別されますが、特定の種類のリソースだけを取得するようにクエリを設定することもできます。 今すぐ試すまたは例を見る

リクエスト

HTTP リクエスト

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

パラメータ

下記の表は、このクエリでサポートされているパラメータの一覧です。このリストのパラメータはすべてクエリ パラメータです。

パラメータ
必須パラメータ
part string
part パラメータには、API レスポンスに含める 1 つまたは複数の search リソースのプロパティをカンマ区切りリストの形式で指定します。このパラメータに指定できる part 名は idsnippet です。

このパラメータに子プロパティを持つプロパティが指定されている場合、その子プロパティもレスポンスに含まれます。たとえば、search の結果では、snippet プロパティには、結果のタイトルや説明などを識別する別のプロパティが含まれます。この場合、part=snippet と設定すると、API レスポンスには、ネストされているプロパティもすべて含まれることになります。
フィルタ(以下のパラメータのいずれか 1 つのみを指定します)
forContentOwner boolean
このパラメータは、適切に承認されたリクエストでのみ使用できます。注: このパラメータは、YouTube コンテンツ パートナー専用です。

forContentOwner パラメータは、onBehalfOfContentOwner パラメータで指定したコンテンツ所有者のリソースのみに検索を限定します。ユーザーは、指定したコンテンツ所有者にリンクされている CMS アカウントを使用して認証される必要があります。また、onBehalfOfContentOwner の指定も必要です。
forMine boolean
forMine パラメータは、適切に認証されたリクエストでのみ使用できます。このパラメータは、認証されたユーザーの動画のみに検索を限定します。このパラメータを true に設定する場合は、type パラメータの値を video に設定する必要があります。
relatedToVideoId string
relatedToVideoId パラメータは、パラメータ値が識別する動画に関連する動画のリストを取得します。このパラメータ値には YouTube 動画 ID を設定します。このパラメータを使用する場合は、type パラメータを video に設定する必要があります。
省略可能なパラメータ
channelId string
channelId パラメータは、チャンネルによって作成されたリソースのみが API レスポンスに含まれるように指定します。
channelType string
channelType パラメータでは、検索対象を特定のタイプのチャンネルに制限できます。

以下の値を指定できます。
  • any – すべてのチャンネルを返します。
  • show – 番組のみを取得します。
eventType string
eventType パラメータは、検索対象をブロードキャスト イベントに制限します。

以下の値を指定できます。
  • completed – 完了したブロードキャストのみを含めます。
  • live – アクティブなブロードキャストのみを含めます。
  • upcoming – 今後配信予定のブロードキャストのみを含めます。
maxResults unsigned integer
maxResults パラメータには、結果セットとして返されるアイテムの最大数を指定します。0 以上 50 以下の値を指定できます。デフォルト値は 5 です。
onBehalfOfContentOwner string
このパラメータは、適切に承認されたリクエストでのみ使用できます。注: このパラメータは、YouTube コンテンツ パートナー専用です。

onBehalfOfContentOwner パラメータは、リクエストの承認用認証情報が、パラメータ値で指定されたコンテンツ所有者の代理人である YouTube CMS ユーザーのものであることを示します。このパラメータは、複数の YouTube チャンネルを所有、管理している YouTube コンテンツ パートナーを対象にしています。このパラメータを使用すると、コンテンツ所有者は一度認証されれば、すべての動画やチャンネル データにアクセスできるようになります。チャンネルごとに認証情報を指定する必要はありません。ユーザー認証に使用する CMS アカウントは、指定された YouTube コンテンツ所有者にリンクされていなければなりません。
order string
order パラメータには、API レスポンス内のリソースの並べ替え方法を指定します。デフォルト値は SEARCH_SORT_RELEVANCE です。

以下の値を指定できます。
  • date – リソースを作成日の新しい順に並べます。
  • rating – リソースを評価の高い順に並べます。
  • relevance – リソースを検索クエリの関連性が高い順に並べます。このパラメータのデフォルト値です。
  • title – リソースをタイトルのアルファベット順に並べます。
  • videoCount – アップロード動画の番号順(降順)にチャンネルを並べます。
  • viewCount – リソースを再生回数の多い順に並べます。
pageToken string
pageToken パラメータには、返される結果セットに含める特定のページを指定します。API レスポンスでは、nextPageTokenprevPageToken プロパティは取得可能な他のページを表します。
publishedAfter datetime
publishedAfter パラメータは、指定した日時より後に作成されたリソースのみが API レスポンスに含まれるように指定します。この値は RFC 3339 形式の date-time 値です(1970-01-01T00:00:00Z)。
publishedBefore datetime
publishedBefore パラメータは、指定した日時より前に作成されたリソースのみが API レスポンスに含まれるように指定します。この値は RFC 3339 形式の date-time 値です(1970-01-01T00:00:00Z)。
q string
q パラメータは検索クエリを指定します。
regionCode string
regionCode パラメータは、指定した国の検索結果を返すように API に指示します。パラメータの値は ISO 3166-1 alpha-2 の国コードです。
safeSearch string
safeSearch パラメータは、検索結果に標準コンテンツの他、制限コンテンツも含めるかどうかを指定します。

以下の値を指定できます。
  • moderate – 検索結果のコンテンツに対して一定のフィルタリングを行い、少なくともアプリケーションの言語/地域で制限されているコンテンツは除外します。動画の内容によっては、検索結果から動画が削除されたり検索結果内での優先度が下がったりすることがあります。これはデフォルトのパラメータ値です。
  • none – YouTube は検索結果セットのフィルタリングを行いません。
  • strict – 検索結果セットから制限コンテンツをすべて除外します。動画の内容によっては、検索結果から動画が削除されたり検索結果内での優先度が下がったりすることがあります。
topicId string
topicId パラメータは、指定したトピックに関連するリソースのみが API レスポンスに含まれるように指定します。この値は Freebase トピック ID を識別します。
type string
type パラメータは、検索クエリの対象を特定のタイプのリソースのみに制限します。値はカンマで区切られたリソースのタイプのリストです。デフォルト値は video,channel,playlist です。

以下の値を指定できます。
  • channel
  • playlist
  • video
videoCaption string
videoCaption パラメータは、字幕の有無に基づいて動画の検索結果をフィルタリングするように指定します。

以下の値を指定できます。
  • any – 字幕の有無に基づいた結果のフィルタリングを行いません。
  • closedCaption – 字幕がある動画のみを含めます。
  • none – 字幕がない動画のみを含めます。
videoCategoryId string
videoCategoryId パラメータは、動画の検索結果をカテゴリに基づいてフィルタリングします。
videoDefinition string
videoDefinition パラメータを使用すると、検索結果を HD(高解像度)または SD(標準解像度)のみに制限できます。HD 動画は 720p 以上で再生できます。また 1080p など、さらに高い解像度も利用できる場合があります。

以下の値を指定できます。
  • any – 解像度に関係なく、すべての動画を返します。
  • high – HD 動画のみを取得します。
  • standard – SD 動画のみを取得します。
videoDimension string
videoDimension パラメータでは、検索結果を 2D 動画または 3D 動画のみに限定できます。

以下の値を指定できます。
  • 2d – 検索結果から 3D 動画を除外します。
  • 3d – 検索結果を 3D 動画に限定します。
  • any – 返される結果に 3D 動画と 3D 以外の動画の両方を含めます。これはデフォルトの値です。
videoDuration string
videoDuration パラメータは、動画の検索結果を期間に基づいてフィルタリングします。

以下の値を指定できます。
  • any – 検索結果を期間に基づいてフィルタリングしません。これはデフォルトの値です。
  • long – 20 分を超える動画のみを含めます。
  • medium – 4 分以上 20 分以下の動画のみを含めます。
  • short – 4 分未満の動画のみを含めます。
videoEmbeddable string
videoEmbeddable パラメータでは、Web ページに埋め込み可能な動画のみを検索するように制限できます。

以下の値を指定できます。
  • any – 埋め込み可能かどうかにかかわらず、すべての動画を返します。
  • true – 埋め込み動画のみを取得します。
videoLicense string
videoLicense パラメータは、特定のライセンスがある動画のみが検索結果に含まれるようにフィルタリングします。YouTube では、動画をアップロードしたユーザーが、動画ごとにクリエイティブ・コモンズ ライセンスまたは標準の YouTube ライセンスを設定できます。

以下の値を指定できます。
  • any – ライセンスの種類にかかわらず、クエリ パラメータに一致するすべての動画を返します。
  • creativeCommon – クリエイティブ・コモンズ ライセンスを持つ動画のみを返します。このライセンスを持つ動画は、動画作成時に誰でも再利用できます。詳細
  • youtube – 標準の YouTube ライセンスを持つ動画のみを返します。
videoSyndicated string
videoSyndicated パラメータでは、検索対象を youtube.com 以外で再生できる動画のみに限定できます。

以下の値を指定できます。
  • any – シンジケートされているかどうかにかかわらず、すべての動画を返します。
  • true – シンジケートされている動画のみを取得します。
videoType string
videoType パラメータでは、検索対象を特定のタイプの動画に制限できます。

以下の値を指定できます。
  • any – すべての動画を返します。
  • episode – 番組のエピソードのみを取得します。
  • movie – 動画のみを取得します。

リクエストの本文

このメソッドを呼び出す場合は、リクエストの本文を指定しないでください。

レスポンス

成功すると、このメソッドは次の構造を持つレスポンスの本文を返します。

{
  "kind": "youtube#searchListResponse",
  "etag": etag,
  "nextPageToken": string,
  "prevPageToken": string,
  "pageInfo": {
    "totalResults": integer,
    "resultsPerPage": integer
  },
  "items": [
    検索リソース
  ]
}

プロパティ

次の表は、検索結果で使用されているプロパティの定義を示したものです。

プロパティ
kind string
API リソースのタイプ。値は youtube#searchListResponse です。
etag etag
このリソースの Etag。
nextPageToken string
結果セットの次のページを取得するために、pageToken パラメータの値として使用できるトークン。
prevPageToken string
結果セットの前のページを取得するために、pageToken パラメータの値として使用できるトークン。
pageInfo object
pageInfo オブジェクトは、結果セットのページング情報をカプセル化します。
pageInfo.totalResults integer
結果セット内の結果の総数。
pageInfo.resultsPerPage integer
API レスポンスに含まれる結果の数。
items[] list
検索条件に一致する結果のリスト。

注: 以下のコード サンプルは、サポートされているプログラミング言語すべてについて表したものではありません。サポートされている言語の一覧については、クライアント ライブラリのドキュメントを参照してください。

Java、例 1

この例では、Java クライアント ライブラリを使用しています。

  • Search.java

    /*
     * Copyright (c) 2012 Google Inc.
     *
     * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
     * in compliance with the License. You may obtain a copy of the License at
     *
     * http://www.apache.org/licenses/LICENSE-2.0
     *
     * Unless required by applicable law or agreed to in writing, software distributed under the License
     * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
     * or implied. See the License for the specific language governing permissions and limitations under
     * the License.
     */
    
    package com.google.api.services.samples.youtube.cmdline.youtube_cmdline_search_sample;
    
    import com.google.api.client.googleapis.json.GoogleJsonResponseException;
    import com.google.api.client.http.HttpRequest;
    import com.google.api.client.http.HttpRequestInitializer;
    import com.google.api.client.http.HttpTransport;
    import com.google.api.client.http.javanet.NetHttpTransport;
    import com.google.api.client.json.JsonFactory;
    import com.google.api.client.json.jackson2.JacksonFactory;
    import com.google.api.services.youtube.YouTube;
    import com.google.api.services.youtube.model.ResourceId;
    import com.google.api.services.youtube.model.SearchListResponse;
    import com.google.api.services.youtube.model.SearchResult;
    import com.google.api.services.youtube.model.Thumbnail;
    
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.util.Iterator;
    import java.util.List;
    import java.util.Properties;
    
    /**
     * Prints a list of videos based on a search term.
     *
     * @author Jeremy Walker
     */
    public class Search {
    
      /** Global instance properties filename. */
      private static String PROPERTIES_FILENAME = "youtube.properties";
    
      /** Global instance of the HTTP transport. */
      private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
    
      /** Global instance of the JSON factory. */
      private static final JsonFactory JSON_FACTORY = new JacksonFactory();
    
      /** Global instance of the max number of videos we want returned (50 = upper limit per page). */
      private static final long NUMBER_OF_VIDEOS_RETURNED = 25;
    
      /** Global instance of Youtube object to make all API requests. */
      private static YouTube youtube;
    
    
      /**
       * Initializes YouTube object to search for videos on YouTube (Youtube.Search.List). The program
       * then prints the names and thumbnails of each of the videos (only first 50 videos).
       *
       * @param args command line args.
       */
      public static void main(String[] args) {
        // Read the developer key from youtube.properties
        Properties properties = new Properties();
        try {
          InputStream in = Search.class.getResourceAsStream("/" + PROPERTIES_FILENAME);
          properties.load(in);
    
        } catch (IOException e) {
          System.err.println("There was an error reading " + PROPERTIES_FILENAME + ": " + e.getCause()
              + " : " + e.getMessage());
          System.exit(1);
        }
    
        try {
          /*
           * The YouTube object is used to make all API requests. The last argument is required, but
           * because we don't need anything initialized when the HttpRequest is initialized, we override
           * the interface and provide a no-op function.
           */
          youtube = new YouTube.Builder(HTTP_TRANSPORT, JSON_FACTORY, new HttpRequestInitializer() {
            public void initialize(HttpRequest request) throws IOException {}
          }).setApplicationName("youtube-cmdline-search-sample").build();
    
          // Get query term from user.
          String queryTerm = getInputQuery();
    
          YouTube.Search.List search = youtube.search().list("id,snippet");
          /*
           * It is important to set your API key from the Google Developer Console for
           * non-authenticated requests (found under the Credentials tab at this link:
           * console.developers.google.com/). This is good practice and increased your quota.
           */
          String apiKey = properties.getProperty("youtube.apikey");
          search.setKey(apiKey);
          search.setQ(queryTerm);
          /*
           * We are only searching for videos (not playlists or channels). If we were searching for
           * more, we would add them as a string like this: "video,playlist,channel".
           */
          search.setType("video");
          /*
           * This method reduces the info returned to only the fields we need and makes calls more
           * efficient.
           */
          search.setFields("items(id/kind,id/videoId,snippet/title,snippet/thumbnails/default/url)");
          search.setMaxResults(NUMBER_OF_VIDEOS_RETURNED);
          SearchListResponse searchResponse = search.execute();
    
          List<SearchResult> searchResultList = searchResponse.getItems();
    
          if (searchResultList != null) {
            prettyPrint(searchResultList.iterator(), queryTerm);
          }
        } catch (GoogleJsonResponseException e) {
          System.err.println("There was a service error: " + e.getDetails().getCode() + " : "
              + e.getDetails().getMessage());
        } catch (IOException e) {
          System.err.println("There was an IO error: " + e.getCause() + " : " + e.getMessage());
        } catch (Throwable t) {
          t.printStackTrace();
        }
      }
    
      /*
       * Returns a query term (String) from user via the terminal.
       */
      private static String getInputQuery() throws IOException {
    
        String inputQuery = "";
    
        System.out.print("Please enter a search term: ");
        BufferedReader bReader = new BufferedReader(new InputStreamReader(System.in));
        inputQuery = bReader.readLine();
    
        if (inputQuery.length() < 1) {
          // If nothing is entered, defaults to "YouTube Developers Live."
          inputQuery = "YouTube Developers Live";
        }
        return inputQuery;
      }
    
      /*
       * Prints out all SearchResults in the Iterator. Each printed line includes title, id, and
       * thumbnail.
       *
       * @param iteratorSearchResults Iterator of SearchResults to print
       *
       * @param query Search query (String)
       */
      private static void prettyPrint(Iterator<SearchResult> iteratorSearchResults, String query) {
    
        System.out.println("\n=============================================================");
        System.out.println(
            "   First " + NUMBER_OF_VIDEOS_RETURNED + " videos for search on \"" + query + "\".");
        System.out.println("=============================================================\n");
    
        if (!iteratorSearchResults.hasNext()) {
          System.out.println(" There aren't any results for your query.");
        }
    
        while (iteratorSearchResults.hasNext()) {
    
          SearchResult singleVideo = iteratorSearchResults.next();
          ResourceId rId = singleVideo.getId();
    
          // Double checks the kind is video.
          if (rId.getKind().equals("youtube#video")) {
            Thumbnail thumbnail = singleVideo.getSnippet().getThumbnails().get("default");
    
            System.out.println(" Video Id" + rId.getVideoId());
            System.out.println(" Title: " + singleVideo.getSnippet().getTitle());
            System.out.println(" Thumbnail: " + thumbnail.getUrl());
            System.out.println("\n-------------------------------------------------------------\n");
          }
        }
      }
    }
    
  • pom.xml

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
      <modelVersion>4.0.0</modelVersion>
    
      <groupId>com.google.api.services.samples.youtube.cmdline</groupId>
      <artifactId>youtube-cmdline-search-sample</artifactId>
      <version>1.0</version>
      <packaging>jar</packaging>
    
      <name>youtube-cmdline-search-sample</name>
      <url>http://maven.apache.org</url>
    
      <properties>
        <project.youtube.version>v3-rev8-1.12.0-beta</project.youtube.version>
        <project.http.version>1.12.0-beta</project.http.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      </properties>
    
      <repositories>
        <repository>
          <id>google-api-services</id>
          <url>http://google-api-client-libraries.appspot.com/mavenrepo</url>
        </repository>
      </repositories>
    
      <dependencies>
        <!-- YouTube Data V3 support -->
        <dependency>
          <groupId>com.google.apis</groupId>
          <artifactId>google-api-services-youtube</artifactId>
          <version>${project.youtube.version}</version>
        </dependency>
    
        <dependency>
          <groupId>com.google.http-client</groupId>
          <artifactId>google-http-client-jackson2</artifactId>
          <version>${project.http.version}</version>
        </dependency>
      </dependencies>
    
      <build>
        <plugins>
          <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>exec-maven-plugin</artifactId>
            <version>1.2.1</version>
            <configuration>
              <mainClass>com.google.api.services.samples.youtube.cmdline.youtube_cmdline_search_sample.Search</mainClass>
            </configuration>
          </plugin>
    
          <!-- Forces Maven to use Java 1.6 -->
          <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>2.3.2</version>
            <configuration>
              <source>1.6</source>
              <target>1.6</target>
              <compilerArgument></compilerArgument>
            </configuration>
          </plugin>
        </plugins>
      </build>
    </project>

Java、例 2

この例では、Java クライアント ライブラリを使用しています。

  • Topics.java

    /*
     * Copyright (c) 2012 Google Inc.
     *
     * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
     * in compliance with the License. You may obtain a copy of the License at
     *
     * http://www.apache.org/licenses/LICENSE-2.0
     *
     * Unless required by applicable law or agreed to in writing, software distributed under the
     * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
     * express or implied. See the License for the specific language governing permissions and
     * limitations under the License.
     */
    
    package com.google.api.services.samples.youtube.cmdline.youtube_cmdline_topics_sample;
    
    import com.google.api.client.googleapis.json.GoogleJsonResponseException;
    import com.google.api.client.http.HttpRequest;
    import com.google.api.client.http.HttpRequestInitializer;
    import com.google.api.client.http.HttpTransport;
    import com.google.api.client.http.javanet.NetHttpTransport;
    import com.google.api.client.json.JsonFactory;
    import com.google.api.client.json.jackson2.JacksonFactory;
    import com.google.api.services.youtube.YouTube;
    import com.google.api.services.youtube.model.ResourceId;
    import com.google.api.services.youtube.model.SearchListResponse;
    import com.google.api.services.youtube.model.SearchResult;
    import com.google.api.services.youtube.model.Thumbnail;
    
    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.NameValuePair;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.client.utils.URLEncodedUtils;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.apache.http.message.BasicNameValuePair;
    import org.codehaus.jackson.JsonNode;
    import org.codehaus.jackson.map.ObjectMapper;
    import org.codehaus.jackson.node.ArrayNode;
    
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.List;
    import java.util.Properties;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    
    /**
     * Demo of a semantic YouTube search getting a topic and search term from the user.  The class
     * calls the Freebase API to get a topics id based on user input, then passes that id along with
     * another user query term to the YouTube APIs.  The result is a list of videos based on a
     * semantic search.
     *
     * @author Jeremy Walker
     */
    public class Topics {
    
      /** Global instance properties filename. */
      private static String PROPERTIES_FILENAME = "youtube.properties";
    
      /** Global instance of the HTTP transport. */
      private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
    
      /** Global instance of the JSON factory. */
      private static final JsonFactory JSON_FACTORY = new JacksonFactory();
    
      /** Global instance of the max number of videos we want returned. */
      private static final long NUMBER_OF_VIDEOS_RETURNED = 5;
    
      /** Global instance of the max number of topics we want returned. */
      private static final long NUMBER_OF_TOPICS_RETURNED = 5;
    
      /** Global instance of Youtube object to make all API requests. */
      private static YouTube youtube;
    
      /**
       * Method kicks off a search via the Freebase API for a topics id.  It initializes a YouTube
       * object to search for videos on YouTube (Youtube.Search.List) using that topics id to make the
       * search more specific.  The program then prints the names and thumbnails of each of the videos
       * (only first 5 videos).  Please note, user input is taken for both search on Freebase and on
       * YouTube.
       *
       * @param args command line args not used.
      */
      public static void main( String[] args ) {
        // Read the developer key from youtube.properties
        Properties properties = new Properties();
        try {
          InputStream in = Topics.class.getResourceAsStream("/" + PROPERTIES_FILENAME);
          properties.load(in);
    
        } catch (IOException e) {
          System.err.println("There was an error reading " + PROPERTIES_FILENAME + ": " + e.getCause()
              + " : " + e.getMessage());
          System.exit(1);
        }
    
    
        try {
          // Gets a topic id via the Freebase API based on user input.
          String topicsId = getTopicId();
          if(topicsId.length() < 1) {
            System.out.println("No topic id will be applied to your search.");
          }
    
          /*
           * Get query term from user.  The "search" parameter is just used as output to clarify that
           * we want a "search" term (vs. a "topics" term).
           */
          String queryTerm = getInputQuery("search");
    
          /*
           * The YouTube object is used to make all API requests.  The last argument is required, but
           * because we don't need anything initialized when the HttpRequest is initialized, we
           * override the interface and provide a no-op function.
           */
          youtube = new YouTube.Builder(HTTP_TRANSPORT, JSON_FACTORY, new HttpRequestInitializer() {
              public void initialize(HttpRequest request) throws IOException {}})
            .setApplicationName("youtube-cmdline-search-sample")
            .build();
    
          YouTube.Search.List search = youtube.search().list("id,snippet");
          /*
           * It is important to set your API key from the Google Developer Console for
           * non-authenticated requests (found under the Credentials tab at this link:
           * console.developers.google.com/). This is good practice and increases your quota.
           */
          String apiKey = properties.getProperty("youtube.apikey");
          search.setKey(apiKey);
          search.setQ(queryTerm);
          if(topicsId.length() > 0) {
            search.setTopicId(topicsId);
          }
    
          /*
           * We are only searching for videos (not playlists or channels).  If we were searching for
           * more, we would add them as a string like this: "video,playlist,channel".
           */
          search.setType("video");
          /*
           * This method reduces the info returned to only the fields we need.  It makes things more
           * efficient, because we are transmitting less data.
           */
          search.setFields("items(id/kind,id/videoId,snippet/title,snippet/thumbnails/default/url)");
          search.setMaxResults(NUMBER_OF_VIDEOS_RETURNED);
          SearchListResponse searchResponse = search.execute();
    
          List<SearchResult> searchResultList = searchResponse.getItems();
    
          if(searchResultList != null) {
            prettyPrint(searchResultList.iterator(), queryTerm, topicsId);
          } else {
            System.out.println("There were no results for your query.");
          }
        } catch (GoogleJsonResponseException e) {
          System.err.println("There was a service error: " + e.getDetails().getCode() +
              " : " + e.getDetails().getMessage());
          e.printStackTrace();
        } catch (IOException e) {
          System.err.println("There was an IO error: " + e.getCause() + " : " + e.getMessage());
          e.printStackTrace();
        }
      }
    
      /*
       * Returns a query term (String) from user via the terminal.
       *
       * @param searchCategory This is for output to the user to clariy what info we need from them.
       */
      private static String getInputQuery(String searchCategory) throws IOException {
    
        String inputQuery = "";
    
        BufferedReader bReader = new BufferedReader(new InputStreamReader(System.in));
    
        do {
          System.out.print("Please enter a " + searchCategory + " term: ");
          inputQuery = bReader.readLine();
        } while(inputQuery.length() < 1);
    
        return inputQuery;
      }
    
      /**
       * The Java Freebase client library does not include search functionality, so we created a call
       * directly via URL.  We use jackson functionality to put the JSON response into a POJO (Plain
       * Old Java Object).  The additional classes to create the object from JSON were created based on
       * the JSON response to make it easier to get the values we need.  For more info on jackson
       * classes, please search on the term.
       */
      private static String getTopicId() throws IOException {
    
        /*
         * Returned as an empty string if we can't find a matching topicsId or there aren't any
         * results available.
         */
        String topicsId = "";
    
        /*
         * Get query term from user.  The "topics" parameter is just used as output to clarify that
         * we want a "topics" term (vs. a general "search" term).
         */
        String topicQuery = getInputQuery("topics");
    
        /*
         * Again, there isn't search functionality in the Freebase Java Library, so we have to call
         * directly against the URL.  Below we construct the proper URL, then use jackson classes to
         * convert the JSON into an object for reading.  You can find out more about the search calls
         * here: http://wiki.freebase.com/wiki/ApiSearch.
         */
        HttpClient httpclient = new DefaultHttpClient();
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("query", topicQuery));
        params.add(new BasicNameValuePair("limit", Long.toString(NUMBER_OF_TOPICS_RETURNED)));
    
        String serviceURL = "https://www.googleapis.com/freebase/v1/search";
        String url = serviceURL + "?" + URLEncodedUtils.format(params, "UTF-8");
    
        HttpResponse httpResponse = httpclient.execute(new HttpGet(url));
        HttpEntity entity = httpResponse.getEntity();
    
        if (entity != null) {
            InputStream instream = entity.getContent();
            try {
              /*
               * Converts JSON to a Tree.  I could have specified extra classes and done an exact map
               * from JSON to POJO, but I was trying to keep the sample within one Java file.  If the
               * .get() function calls here and in getUserChoice() aren't your cup of tea, feel free
               * to create those classes and use them with the mapper.readValue() function.
               */
              ObjectMapper mapper = new ObjectMapper();
              JsonNode rootNode = mapper.readValue(instream, JsonNode.class);
    
              // Check that the response is valid.
              if(rootNode.get("status").asText().equals("200 OK")) {
                // I know the "result" field contains the list of results I need.
                ArrayNode arrayNodeResults = (ArrayNode) rootNode.get("result");
                // Only place we set the topicsId for a valid selection in this function.
                topicsId = getUserChoice(arrayNodeResults);
              }
            } finally {
              instream.close();
            }
        }
        return topicsId;
      }
    
      /**
       * Outputs topic search results to the user, records user selection, and returns topic id.
       *
       * @param freebaseResults ArrayNode object representing results of search.
       */
      private static String getUserChoice(ArrayNode freebaseResults) throws IOException {
    
        String freebaseId = "";
    
        if(freebaseResults.size() < 1) {
          return freebaseId;
        }
    
        for(int i = 0; i < freebaseResults.size(); i++) {
          JsonNode node = freebaseResults.get(i);
          System.out.print(" " + i + " = " + node.get("name").asText());
          if(node.get("notable") != null) {
            System.out.print(" (" + node.get("notable").get("name").asText() + ")");
          }
          System.out.println("");
        }
    
        BufferedReader bReader = new BufferedReader(new InputStreamReader(System.in));
        String inputChoice;
    
        do {
          System.out.print("Choose the number of the Freebase Node: ");
          inputChoice = bReader.readLine();
        } while (!isValidIntegerSelection(inputChoice, freebaseResults.size()));
    
        // Returns Topic id needed for YouTube Search.
        JsonNode node = freebaseResults.get(Integer.parseInt(inputChoice));
        freebaseId = node.get("mid").asText();
        return freebaseId;
      }
    
      /**
       * Checks if string contains a valid, positive integer that is less than max.  Please note, I am
       * not testing the upper limit of an integer (2,147,483,647).  I just go up to 999,999,999.
       *
       * @param input String to test.
       * @param max Integer must be less then this Maximum number.
       */
      public static boolean isValidIntegerSelection(String input, int max) {
        if (input.length() > 9)
          return false;
    
        boolean validNumber = false;
        // Only accepts positive numbers of up to 9 numbers.
        Pattern intsOnly = Pattern.compile("^\\d{1,9}$");
        Matcher makeMatch = intsOnly.matcher(input);
    
        if(makeMatch.find()){
          int number = Integer.parseInt(makeMatch.group());
          if((number >= 0) && (number < max)) {
            validNumber = true;
          }
        }
        return validNumber;
      }
    
      /*
       * Prints out all SearchResults in the Iterator.  Each printed line includes title, id, and
       * thumbnail.
       *
       * @param iteratorSearchResults Iterator of SearchResults to print
       * @param query Search query (String)
       */
      private static void prettyPrint(Iterator<SearchResult> iteratorSearchResults, String query, String topicsId) {
    
        System.out.println("\n=============================================================");
        System.out.println("   First " + NUMBER_OF_VIDEOS_RETURNED + " videos for search on \"" + query + "\" with Topics id: " + topicsId + ".");
        System.out.println("=============================================================\n");
    
        if(!iteratorSearchResults.hasNext()) {
          System.out.println(" There aren't any results for your query.");
        }
    
        while(iteratorSearchResults.hasNext()) {
    
          SearchResult singleVideo = iteratorSearchResults.next();
          ResourceId rId = singleVideo.getId();
    
          // Double checks the kind is video.
          if(rId.getKind().equals("youtube#video")) {
            Thumbnail thumbnail = singleVideo.getSnippet().getThumbnails().get("default");
    
            System.out.println(" Video Id" + rId.getVideoId());
            System.out.println(" Title: " + singleVideo.getSnippet().getTitle());
            System.out.println(" Thumbnail: " + thumbnail.getUrl());
            System.out.println("\n-------------------------------------------------------------\n");
          }
        }
      }
    }
    
  • pom.xml

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
      <modelVersion>4.0.0</modelVersion>
    
      <groupId>com.google.api.services.samples.youtube.cmdline</groupId>
      <artifactId>youtube-cmdline-topics-sample</artifactId>
      <version>0.0.1-SNAPSHOT</version>
      <packaging>jar</packaging>
    
      <name>youtube-cmdline-topics-sample</name>
      <url>http://maven.apache.org</url>
    
      <properties>
        <project.youtube.version>v3-rev8-1.12.0-beta</project.youtube.version>
        <project.http.version>1.12.0-beta</project.http.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      </properties>
    
      <repositories>
        <repository>
          <id>google-api-services</id>
          <url>http://google-api-client-libraries.appspot.com/mavenrepo</url>
        </repository>
        <repository>
          <id>codehaus</id>
          <url>http://repository.codehaus.org/org/codehaus</url>
        </repository>
      </repositories>
    
      <dependencies>
        <dependency>
          <groupId>org.codehaus.jackson</groupId>
          <artifactId>jackson-mapper-asl</artifactId>
          <version>1.9.4</version>
        </dependency>
    
        <!-- YouTube Data V3 support -->
        <dependency>
          <groupId>com.google.apis</groupId>
          <artifactId>google-api-services-youtube</artifactId>
          <version>${project.youtube.version}</version>
        </dependency>
    
        <dependency>
          <groupId>com.google.http-client</groupId>
          <artifactId>google-http-client-jackson2</artifactId>
          <version>${project.http.version}</version>
        </dependency>
      </dependencies>
    
        <build>
        <plugins>
          <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>exec-maven-plugin</artifactId>
            <version>1.2.1</version>
            <configuration>
              <mainClass>com.google.api.services.samples.youtube.cmdline.youtube_cmdline_topics_sample.Topics</mainClass>
            </configuration>
          </plugin>
    
          <!-- Forces Maven to use Java 1.6 -->
          <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>2.3.2</version>
            <configuration>
              <source>1.6</source>
              <target>1.6</target>
              <compilerArgument></compilerArgument>
            </configuration>
          </plugin>
        </plugins>
      </build>
    </project>

JavaScript

この例では、JavaScript クライアント ライブラリを使用しています。

// After the API loads, call a function to enable the search box.
function handleAPILoaded() {
  $('#search-button').attr('disabled', false);
}

// Search for a specified string.
function search() {
  var q = $('#query').val();
  var request = gapi.client.youtube.search.list({
    q: q,
    part: 'snippet'
  });

  request.execute(function(response) {
    var str = JSON.stringify(response.result);
    $('#search-container').html('<pre>' + str + '</pre>');
  });
}

.NET

この例では、.NET クライアント ライブラリを使用しています。

using System;
using System.Collections;
using System.Collections.Generic;

/*
 * External dependencies, OAuth 2.0 support, and core client libraries are at:
 *   https://developers.google.com/api-client-library/dotnet/apis/
 * Also see the Samples.zip file for the Google.Apis.Samples.Helper classes at:
 *   https://github.com/youtube/api-samples/tree/master/dotnet
 */

using Google.Apis.Samples.Helper;
using Google.Apis.Services;
using Google.Apis.Youtube.v3;
using Google.Apis.Youtube.v3.Data;

namespace dotnet
{
  class search
  {
    static void Main(string[] args)
    {
      CommandLine.EnableExceptionHandling();
      CommandLine.DisplayGoogleSampleHeader("YouTube Data API: Search");

      SimpleClientCredentials credentials = PromptingClientCredentials.EnsureSimpleClientCredentials();

      YoutubeService youtube = new YoutubeService(new BaseClientService.Initializer() {
        ApiKey = credentials.ApiKey
      });

      SearchResource.ListRequest listRequest = youtube.Search.List("snippet");
      listRequest.Q = CommandLine.RequestUserInput<string>("Search term: ");
      listRequest.Order = SearchResource.Order.Relevance;

      SearchListResponse searchResponse = listRequest.Fetch();

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

      foreach (SearchResult searchResult in searchResponse.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;
        }
      }

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

      CommandLine.PressAnyKeyToExit();
    }
  }
}

PHP

この例では、PHP クライアント ライブラリを使用しています。

<?php

/**
 * Library Requirements
 *
 * 1. Install composer (https://getcomposer.org)
 * 2. On the command line, change to this directory (api-samples/php)
 * 3. Require the google/apiclient library
 *    $ composer require google/apiclient:~2.0
 */
if (!file_exists(__DIR__ . '/vendor/autoload.php')) {
  throw new \Exception('please run "composer require google/apiclient:~2.0" in "' . __DIR__ .'"');
}

require_once __DIR__ . '/vendor/autoload.php';

$htmlBody = <<<END
<form method="GET">
  <div>
    Search Term: <input type="search" id="q" name="q" placeholder="Enter Search Term">
  </div>
  <div>
    Max Results: <input type="number" id="maxResults" name="maxResults" min="1" max="50" step="1" value="25">
  </div>
  <input type="submit" value="Search">
</form>
END;

// This code will execute if the user entered a search query in the form
// and submitted the form. Otherwise, the page displays the form above.
if (isset($_GET['q']) && isset($_GET['maxResults'])) {
  /*
   * Set $DEVELOPER_KEY to the "API key" value from the "Access" tab of the
   * Google API Console <https://console.cloud.google.com/>
   * Please ensure that you have enabled the YouTube Data API for your project.
   */
  $DEVELOPER_KEY = 'REPLACE_ME';

  $client = new Google_Client();
  $client->setDeveloperKey($DEVELOPER_KEY);

  // Define an object that will be used to make all API requests.
  $youtube = new Google_Service_YouTube($client);

  $htmlBody = '';
  try {

    // Call the search.list method to retrieve results matching the specified
    // query term.
    $searchResponse = $youtube->search->listSearch('id,snippet', array(
      'q' => $_GET['q'],
      'maxResults' => $_GET['maxResults'],
    ));

    $videos = '';
    $channels = '';
    $playlists = '';

    // Add each result to the appropriate list, and then display the lists of
    // matching videos, channels, and playlists.
    foreach ($searchResponse['items'] as $searchResult) {
      switch ($searchResult['id']['kind']) {
        case 'youtube#video':
          $videos .= sprintf('<li>%s (%s)</li>',
              $searchResult['snippet']['title'], $searchResult['id']['videoId']);
          break;
        case 'youtube#channel':
          $channels .= sprintf('<li>%s (%s)</li>',
              $searchResult['snippet']['title'], $searchResult['id']['channelId']);
          break;
        case 'youtube#playlist':
          $playlists .= sprintf('<li>%s (%s)</li>',
              $searchResult['snippet']['title'], $searchResult['id']['playlistId']);
          break;
      }
    }

    $htmlBody .= <<<END
    <h3>Videos</h3>
    <ul>$videos</ul>
    <h3>Channels</h3>
    <ul>$channels</ul>
    <h3>Playlists</h3>
    <ul>$playlists</ul>
END;
  } catch (Google_Service_Exception $e) {
    $htmlBody .= sprintf('<p>A service error occurred: <code>%s</code></p>',
      htmlspecialchars($e->getMessage()));
  } catch (Google_Exception $e) {
    $htmlBody .= sprintf('<p>An client error occurred: <code>%s</code></p>',
      htmlspecialchars($e->getMessage()));
  }
}
?>

<!doctype html>
<html>
  <head>
    <title>YouTube Search</title>
  </head>
  <body>
    <?=$htmlBody?>
  </body>
</html>

Python、例 1

この例では、Python クライアント ライブラリを使用しています。

#!/usr/bin/python

from apiclient.discovery import build
from apiclient.errors import HttpError
from oauth2client.tools import argparser


# Set DEVELOPER_KEY 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.
DEVELOPER_KEY = "REPLACE_ME"
YOUTUBE_API_SERVICE_NAME = "youtube"
YOUTUBE_API_VERSION = "v3"

def youtube_search(options):
  youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION,
    developerKey=DEVELOPER_KEY)

  # Call the search.list method to retrieve results matching the specified
  # query term.
  search_response = youtube.search().list(
    q=options.q,
    part="id,snippet",
    maxResults=options.max_results
  ).execute()

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

  # Add each result to the appropriate list, and then display the lists of
  # matching videos, channels, and playlists.
  for search_result in search_response.get("items", []):
    if search_result["id"]["kind"] == "youtube#video":
      videos.append("%s (%s)" % (search_result["snippet"]["title"],
                                 search_result["id"]["videoId"]))
    elif search_result["id"]["kind"] == "youtube#channel":
      channels.append("%s (%s)" % (search_result["snippet"]["title"],
                                   search_result["id"]["channelId"]))
    elif search_result["id"]["kind"] == "youtube#playlist":
      playlists.append("%s (%s)" % (search_result["snippet"]["title"],
                                    search_result["id"]["playlistId"]))

  print "Videos:\n", "\n".join(videos), "\n"
  print "Channels:\n", "\n".join(channels), "\n"
  print "Playlists:\n", "\n".join(playlists), "\n"


if __name__ == "__main__":
  argparser.add_argument("--q", help="Search term", default="Google")
  argparser.add_argument("--max-results", help="Max results", default=25)
  args = argparser.parse_args()

  try:
    youtube_search(args)
  except HttpError, e:
    print "An HTTP error %d occurred:\n%s" % (e.resp.status, e.content)

Python、例 2

この例では、Python クライアント ライブラリを使用しています。

#!/usr/bin/python

from apiclient.discovery import build
from apiclient.errors import HttpError
from oauth2client.tools import argparser

import json
import urllib


# Set DEVELOPER_KEY 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.
DEVELOPER_KEY = "REPLACE_ME"
YOUTUBE_API_SERVICE_NAME = "youtube"
YOUTUBE_API_VERSION = "v3"
FREEBASE_SEARCH_URL = "https://www.googleapis.com/freebase/v1/search?%s"

def get_topic_id(options):
  # Retrieve a list of Freebase topics associated with the provided query term.
  freebase_params = dict(query=options.query, key=DEVELOPER_KEY)
  freebase_url = FREEBASE_SEARCH_URL % urllib.urlencode(freebase_params)
  freebase_response = json.loads(urllib.urlopen(freebase_url).read())

  if len(freebase_response["result"]) == 0:
    exit("No matching terms were found in Freebase.")

  # Display the list of matching Freebase topics.
  mids = []
  index = 1
  print "The following topics were found:"
  for result in freebase_response["result"]:
    mids.append(result["mid"])
    print "  %2d. %s (%s)" % (index, result.get("name", "Unknown"),
      result.get("notable", {}).get("name", "Unknown"))
    index += 1

  # Display a prompt for the user to select a topic and return the topic ID
  # of the selected topic.
  mid = None
  while mid is None:
    index = raw_input("Enter a topic number to find related YouTube %ss: " %
      options.type)
    try:
      mid = mids[int(index) - 1]
    except ValueError:
      pass
  return mid


def youtube_search(mid, options):
  youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION,
  developerKey=DEVELOPER_KEY)

  # Call the search.list method to retrieve results associated with the
  # specified Freebase topic.
  search_response = youtube.search().list(
    topicId=mid,
    type=options.type,
    part="id,snippet",
    maxResults=options.max_results
  ).execute()

  # Print the title and ID of each matching resource.
  for search_result in search_response.get("items", []):
    if search_result["id"]["kind"] == "youtube#video":
      print "%s (%s)" % (search_result["snippet"]["title"],
        search_result["id"]["videoId"])
    elif search_result["id"]["kind"] == "youtube#channel":
      print "%s (%s)" % (search_result["snippet"]["title"],
        search_result["id"]["channelId"])
    elif search_result["id"]["kind"] == "youtube#playlist":
      print "%s (%s)" % (search_result["snippet"]["title"],
        search_result["id"]["playlistId"])


if __name__ == "__main__":
  argparser.add_argument("--query", help="Freebase search term", default="Google")
  argparser.add_argument("--max-results", help="Max YouTube results",
    default=25)
  argparser.add_argument("--type",
    help="YouTube result type: video, playlist, or channel", default="channel")
  args = argparser.parse_args()

  mid = get_topic_id(args)
  try:
    youtube_search(mid, args)
  except HttpError, e:
    print "An HTTP error %d occurred:\n%s" % (e.resp.status, e.content)

Ruby

この例では、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 API Console <https://console.cloud.google.com/>
# 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 invalidSearchFilter リクエストに含まれている検索フィルタ、または制限、もしくはこの両方の組み合わせが無効です。
badRequest invalidVideoId relatedToVideo パラメータに指定されている動画 ID が無効です。

実際に試してみる

API Explorer を使用し、ライブ データに対してこのメソッドを呼び出して、API リクエストとレスポンスを確認してください。