API 요청에 지정된 쿼리 매개변수와 일치하는 검색결과의 모음을 반환합니다. 기본적으로 검색결과의 집합은 쿼리 매개변수와 일치하는 video
, channel
, playlist
리소스를 식별하지만, 특정 유형의 리소스만 검색하도록 쿼리를 구성할 수도 있습니다.
지금 사용해 보거나 예를 참조하세요.
요청
HTTP 요청
GET https://www.googleapis.com/youtube/v3/search
매개변수
아래 표는 이 쿼리가 지원하는 매개변수 목록입니다. 나열된 모든 매개변수는 쿼리 매개변수입니다.
매개변수 이름 | ||
---|---|---|
필수 매개변수 | ||
part |
string part 매개변수는 API 응답이 포함하는 search 리소스 속성 하나 이상의 쉼표로 구분된 목록을 지정합니다. 매개변수 값에 포함할 수 있는 part 이름은 id 및 snippet 입니다.매개변수가 하위 속성을 포함하는 속성을 식별하는 경우 하위 속성이 응답에 포함됩니다. 예를 들어 search 결과에서 snippet 속성은 결과의 제목, 설명 등을 식별하는 다른 속성을 포함합니다. part=snippet 을 설정하는 경우 API 응답은 중첩된 속성도 모두 포함합니다. |
|
필터(다음 매개변수 중 하나만 지정합니다.) | ||
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 매개변수를 사용하여 채널의 특정 유형에 대한 검색을 제한할 수 있습니다.허용값은 다음과 같습니다.
|
|
eventType |
string eventType 매개변수는 방송 이벤트에 대한 검색을 제한합니다.허용값은 다음과 같습니다.
|
|
maxResults |
unsigned integer maxResults 매개변수는 결과 집합에 반환해야 하는 최대 항목 수를 지정합니다. 허용값은 0 이상 50 이하입니다. 기본값은 5 입니다. |
|
onBehalfOfContentOwner |
string 이 매개변수는 제대로 인증된 요청에서만 사용할 수 있습니다. 참고: 이 매개변수는 YouTube 콘텐츠 파트너 전용입니다. onBehalfOfContentOwner 매개변수는 요청의 승인 사용자 인증 정보가 매개변수 값에 지정된 콘텐츠 소유자를 대신하는 YouTube CMS 사용자를 확인함을 나타냅니다. 이 매개변수는 다양한 여러 YouTube 채널을 소유하고 관리하는 YouTube 콘텐츠 파트너 전용입니다. 이 매개변수로 콘텐츠 소유자는 각 개별 채널에 승인 사용자 인증 정보를 제공할 필요 없이 한 번 인증하여 모든 동영상 및 채널 데이터에 액세스할 수 있습니다. 사용자가 인증할 CMS 계정은 지정된 YouTube 콘텐츠 소유자에게 연결되어야 합니다. |
|
order |
string order 매개변수는 API 응답에서 리소스를 지시하는 데 사용할 메소드를 지정합니다. 기본값은 SEARCH_SORT_RELEVANCE 입니다.허용값은 다음과 같습니다.
|
|
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 매개변수는 검색할 검색어를 지정합니다. |
|
regionCode |
string regionCode 매개변수는 API에서 지정된 국가에 대한 검색결과를 반환하도록 합니다. 매개변수 값은 ISO 3166-1 alpha-2 국가 코드입니다. |
|
safeSearch |
string safeSearch 매개변수는 검색결과에 일반적인 콘텐츠뿐 아니라 제한된 콘텐츠도 포함되는지 여부를 나타냅니다.허용값은 다음과 같습니다.
|
|
topicId |
string topicId 매개변수는 API 응답이 지정된 주제와 관련된 리소스만 포함해야 한다는 것을 나타냅니다. 값은 Freebase 주제 ID를 식별합니다. |
|
type |
string type 매개변수는 특정 리소스 유형만 검색하도록 검색 쿼리를 제한합니다. 값은 쉼표로 구분된 리소스 유형의 목록입니다. 기본값은 video,channel,playlist 입니다.허용값은 다음과 같습니다.
|
|
videoCaption |
string videoCaption 매개변수는 캡션이 있는지에 따라 API가 동영상 검색결과를 필터링해야 하는지 여부를 나타냅니다.허용값은 다음과 같습니다.
|
|
videoCategoryId |
string videoCategoryId 매개변수는 카테고리를 기준으로 하는 동영상 검색결과를 필터링합니다. |
|
videoDefinition |
string videoDefinition 매개변수를 사용하여 HD(고화질) 또는 SD(표준 해상도) 동영상만 포함하도록 검색을 제한할 수 있습니다. HD 동영상은 최소 720p로 재생할 수 있고 1080p 같은 고해상도도 사용할 수 있습니다.허용값은 다음과 같습니다.
|
|
videoDimension |
string videoDimension 매개변수를 사용하여 2D 또는 3D 동영상만 검색하도록 검색을 제한할 수 있습니다.허용값은 다음과 같습니다.
|
|
videoDuration |
string videoDuration 매개변수는 동영상 길이를 기준으로 동영상 검색결과를 필터링합니다.허용값은 다음과 같습니다.
|
|
videoEmbeddable |
string videoEmbeddable 매개변수를 사용하여 웹페이지로 퍼갈 수 있는 동영상만 포함하도록 검색을 제한할 수 있습니다.허용값은 다음과 같습니다.
|
|
videoLicense |
string videoLicense 매개변수는 특정 라이선스가 있는 동영상만 포함하도록 검색결과를 필터링합니다. YouTube에서는 동영상 업로더가 각 동영상에 Creative Commons 라이선스 또는 표준 YouTube 라이선스를 첨부하도록 선택할 수 있습니다.허용값은 다음과 같습니다.
|
|
videoSyndicated |
string videoSyndicated 매개변수를 사용하여 youtube.com 외부에서 재생할 수 있는 동영상만 포함하도록 검색을 제한할 수 있습니다.허용값은 다음과 같습니다.
|
|
videoType |
string videoType 매개변수를 사용하여 특정 동영상 유형만 포함하도록 검색을 제한합니다.허용값은 다음과 같습니다.
|
요청 본문
이 메소드를 호출할 때 요청 본문을 제공하지 마세요.
응답
성공하는 경우 이 메소드는 다음 구조로 응답 본문을 반환합니다.
{ "kind": "youtube#searchListResponse", "etag": etag, "nextPageToken": string, "prevPageToken": string, "pageInfo": { "totalResults": integer, "resultsPerPage": integer }, "items": [ search Resource ] }
속성
다음 표는 검색결과에 표시되는 속성을 정의합니다.
속성 이름 | |
---|---|
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 요청 및 응답을 확인해 보세요.