Retorna uma lista de vídeos que correspondem aos parâmetros de solicitação da API. Faça um teste agora ou veja um exemplo.
Solicitação
Solicitação HTTP
GET https://www.googleapis.com/youtube/v3/videos
Parâmetros
A tabela a seguir lista os parâmetros que esta consulta suporta. Todos os parâmetros listados são os parâmetros de consulta.
Parâmetros | ||
---|---|---|
Parâmetros obrigatórios | ||
part |
string O parâmetro part especifica uma lista separada por vírgulas de uma ou mais propriedades de recurso video que serão incluídas pela resposta da API. Os nomes part que podem ser incluídos no valor do parâmetro são id , snippet , contentDetails , fileDetails , player , processingDetails , recordingDetails , statistics , status , suggestions e topicDetails .Se o parâmetro identifica uma propriedade que contém propriedades criança, estas serão incluídas na resposta. Por exemplo, em um recurso video , a propriedade snippet contém as propriedades channelId , title , description , tags e categoryId . Como tal, se você definir part=snippet , a resposta da API conterá todas essas propriedades. |
|
Filtros (especifique exatamente um dos seguintes parâmetros) | ||
chart |
string O parâmetro chart identifica o gráfico que você deseja recuperar.Os valores aceitáveis são:
|
|
id |
string O parâmetro id especifica uma lista separada por vírgulas dos IDs dos vídeos do YouTube para os recursos que estiverem sendo recuperados. Em um recurso video , a propriedade id especifica o ID do vídeo. |
|
myRating |
string Este parâmetro pode ser usado apenas em uma solicitação autorizada adequadamente. Defina o valor deste parâmetro para like ou dislike para instruir a API para retornar apenas vídeos que o usuário autenticado tenha gostado ou não.Os valores aceitáveis são:
|
|
Parâmetros opcionais | ||
maxResults |
unsigned integer O parâmetro maxResults especifica o número máximo de itens que deve ser retornado no conjunto de resultadosObservação: este parâmetro é suportado para uso em conjunto com o parâmetro myRating , mas não com o parâmetro id . Os valores aceitáveis são 1 a 50 , inclusive. O valor padrão é 5 . |
|
onBehalfOfContentOwner |
string Este parâmetro só pode ser usado em uma solicitação autorizada adequadamente. Observação: este parâmetro é destinado exclusivamente a parceiros de conteúdo do YouTube. O parâmetro onBehalfOfContentOwner indica que as credenciais de autorização da solicitação identificam um usuário do CMS do YouTube que age em nome do proprietário do conteúdo especificado no valor do parâmetro. Este parâmetro destina-se a parceiros de conteúdo do YouTube que possuem e gerenciam vários canais do YouTube diferentes. Ele permite que os proprietários de conteúdo autentiquem uma vez e tenham acesso a todos os dados de seu canal e de seus vídeos sem ter que fornecer credenciais de autenticação para cada canal. A conta do CMS com a qual o usuário autentica deve estar vinculada ao proprietário do conteúdo do YouTube especificado. |
|
pageToken |
string O parâmetro pageToken identifica uma página específica no conjunto de resultados que será retornado. Em uma resposta da API, as propriedades nextPageToken e prevPageToken identificam outras páginas que podem ser recuperadas.Observação: este parâmetro é suportado para uso em conjunto com o parâmetro myRating , mas não com o parâmetro id . |
|
regionCode |
string O parâmetro regionCode instrui a API a selecionar um gráfico de vídeo disponível na região especificada. Se você estiver utilizando este parâmetro, o gráfico também deve ser definido. O valor do parâmetro é um código de país ISO 3166-1 Alfa 2. |
|
videoCategoryId |
string O parâmetro videoCategoryId identifica a categoria do vídeo para a qual o gráfico deve ser recuperado. Este parâmetro pode ser usado apenas em conjunto com o parâmetro chart . Por padrão, os gráficos não são restritos a determinada categoria. O valor padrão é 0 . |
Corpo de solicitação
Não forneça um corpo de solicitação ao chamar este método.
Resposta
Se for bem sucedido, este método retorna um corpo de resposta com a seguinte estrutura:
{ "kind": "youtube#videoListResponse", "etag": etag, "nextPageToken": string, "prevPageToken": string, "pageInfo": { "totalResults": integer, "resultsPerPage": integer }, "items": [ video Resource ] }
Propriedades
A tabela a seguir define as propriedades que aparecem nesse recurso:
Propriedades | |
---|---|
kind |
string O tipo do recurso da API. O valor será youtube#videoListResponse . |
etag |
etag A Etag deste recurso. |
nextPageToken |
string O token que pode ser utilizado como o valor do parâmetro pageToken para recuperar a página seguinte do conjunto de resultados. |
prevPageToken |
string O token que pode ser utilizado como o valor do parâmetro pageToken para recuperar a página anterior do conjunto de resultados. |
pageInfo |
object O objeto pageInfo encapsula informações de paginação para o conjunto de resultados. |
pageInfo.totalResults |
integer O número total de resultados no conjunto de resultados. |
pageInfo.resultsPerPage |
integer O número de resultados incluídos na resposta da API. |
items[] |
list A lista de vídeos que correspondem aos critérios de solicitação. |
Examples
Note: The following code samples may not represent all supported programming languages. See the client libraries documentation for a list of supported languages.
Java #1
This sample calls the API'ssearch.list
method with the type
, q
, location
, and
locationRadius
parameters to retrieve search results matching the provided keyword within the radius centered
at a particular location. Using the video IDs from the search result, the sample calls the API's videos.list
method to retrieve location details of each video.
This example uses the Java client library.
/* * Copyright (c) 2014 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.data; 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.util.Joiner; import com.google.api.services.samples.youtube.cmdline.Auth; import com.google.api.services.youtube.YouTube; import com.google.api.services.youtube.model.GeoPoint; 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 com.google.api.services.youtube.model.Video; import com.google.api.services.youtube.model.VideoListResponse; 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; /** * This sample lists videos that are associated with a particular keyword and are in the radius of * particular geographic coordinates by: * * 1. Searching videos with "youtube.search.list" method and setting "type", "q", "location" and * "locationRadius" parameters. * 2. Retrieving location details for each video with "youtube.videos.list" method and setting * "id" parameter to comma separated list of video IDs in search result. * * @author Ibrahim Ulukaya */ public class GeolocationSearch { /** * Define a global variable that identifies the name of a file that * contains the developer's API key. */ private static final String PROPERTIES_FILENAME = "youtube.properties"; private static final long NUMBER_OF_VIDEOS_RETURNED = 25; /** * Define a global instance of a Youtube object, which will be used * to make YouTube Data API requests. */ private static YouTube youtube; /** * Initialize a YouTube object to search for videos on YouTube. Then * display the name and thumbnail image of each video in the result set. * * @param args command line args. */ public static void main(String[] args) { // Read the developer key from the properties file. Properties properties = new Properties(); try { InputStream in = GeolocationSearch.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 { // This object is used to make YouTube Data API requests. The last // argument is required, but since 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(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, new HttpRequestInitializer() { @Override public void initialize(HttpRequest request) throws IOException { } }).setApplicationName("youtube-cmdline-geolocationsearch-sample").build(); // Prompt the user to enter a query term. String queryTerm = getInputQuery(); // Prompt the user to enter location coordinates. String location = getInputLocation(); // Prompt the user to enter a location radius. String locationRadius = getInputLocationRadius(); // Define the API request for retrieving search results. YouTube.Search.List search = youtube.search().list("id,snippet"); // Set your developer key from the {{ Google Cloud Console }} for // non-authenticated requests. See: // {{ https://cloud.google.com/console }} String apiKey = properties.getProperty("youtube.apikey"); search.setKey(apiKey); search.setQ(queryTerm); search.setLocation(location); search.setLocationRadius(locationRadius); // Restrict the search results to only include videos. See: // https://developers.google.com/youtube/v3/docs/search/list#type search.setType("video"); // As a best practice, only retrieve the fields that the // application uses. search.setFields("items(id/videoId)"); search.setMaxResults(NUMBER_OF_VIDEOS_RETURNED); // Call the API and print results. SearchListResponse searchResponse = search.execute(); List<SearchResult> searchResultList = searchResponse.getItems(); List<String> videoIds = new ArrayList<String>(); if (searchResultList != null) { // Merge video IDs for (SearchResult searchResult : searchResultList) { videoIds.add(searchResult.getId().getVideoId()); } Joiner stringJoiner = Joiner.on(','); String videoId = stringJoiner.join(videoIds); // Call the YouTube Data API's youtube.videos.list method to // retrieve the resources that represent the specified videos. YouTube.Videos.List listVideosRequest = youtube.videos().list("snippet, recordingDetails").setId(videoId); VideoListResponse listResponse = listVideosRequest.execute(); List<Video> videoList = listResponse.getItems(); if (videoList != null) { prettyPrint(videoList.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(); } } /* * Prompt the user to enter a query term and return the user-specified term. */ 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) { // Use the string "YouTube Developers Live" as a default. inputQuery = "YouTube Developers Live"; } return inputQuery; } /* * Prompt the user to enter location coordinates and return the user-specified coordinates. */ private static String getInputLocation() throws IOException { String inputQuery = ""; System.out.print("Please enter location coordinates (example: 37.42307,-122.08427): "); BufferedReader bReader = new BufferedReader(new InputStreamReader(System.in)); inputQuery = bReader.readLine(); if (inputQuery.length() < 1) { // Use the string "37.42307,-122.08427" as a default. inputQuery = "37.42307,-122.08427"; } return inputQuery; } /* * Prompt the user to enter a location radius and return the user-specified radius. */ private static String getInputLocationRadius() throws IOException { String inputQuery = ""; System.out.print("Please enter a location radius (examples: 5km, 8mi):"); BufferedReader bReader = new BufferedReader(new InputStreamReader(System.in)); inputQuery = bReader.readLine(); if (inputQuery.length() < 1) { // Use the string "5km" as a default. inputQuery = "5km"; } return inputQuery; } /* * Prints out all results in the Iterator. For each result, print the * title, video ID, location, and thumbnail. * * @param iteratorVideoResults Iterator of Videos to print * * @param query Search query (String) */ private static void prettyPrint(Iterator<Video> iteratorVideoResults, String query) { System.out.println("\n============================================================="); System.out.println( " First " + NUMBER_OF_VIDEOS_RETURNED + " videos for search on \"" + query + "\"."); System.out.println("=============================================================\n"); if (!iteratorVideoResults.hasNext()) { System.out.println(" There aren't any results for your query."); } while (iteratorVideoResults.hasNext()) { Video singleVideo = iteratorVideoResults.next(); Thumbnail thumbnail = singleVideo.getSnippet().getThumbnails().getDefault(); GeoPoint location = singleVideo.getRecordingDetails().getLocation(); System.out.println(" Video Id" + singleVideo.getId()); System.out.println(" Title: " + singleVideo.getSnippet().getTitle()); System.out.println(" Location: " + location.getLatitude() + ", " + location.getLongitude()); System.out.println(" Thumbnail: " + thumbnail.getUrl()); System.out.println("\n-------------------------------------------------------------\n"); } } }
Java #2
This sample demonstrates how to use the following API methods to set and retrieve localized metadata for a video:- It calls the
videos.update
method to update the default language of a video's metadata and to add a localized version of this metadata in a selected language. - It calls the
videos.list
method with thehl
parameter set to a specific language to retrieve localized metadata in that language. - It calls the
videos.list
method and includeslocalizations
in thepart
parameter value to retrieve all of the localized metadata for that video.
This example uses the Java client library.
/* * Copyright (c) 2015 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.data; import com.google.api.client.auth.oauth2.Credential; import com.google.api.client.googleapis.json.GoogleJsonResponseException; import com.google.api.client.util.ArrayMap; import com.google.api.services.samples.youtube.cmdline.Auth; import com.google.api.services.youtube.YouTube; import com.google.api.services.youtube.model.Video; import com.google.api.services.youtube.model.VideoListResponse; import com.google.api.services.youtube.model.VideoLocalization; import com.google.common.collect.Lists; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.List; import java.util.Map; /** * This sample sets and retrieves localized metadata for a video by: * * 1. Updating language of the default metadata and setting localized metadata * for a video via "videos.update" method. * 2. Getting the localized metadata for a video in a selected language using the * "videos.list" method and setting the "hl" parameter. * 3. Listing the localized metadata for a video using the "videos.list" method and * including "localizations" in the "part" parameter. * * @author Ibrahim Ulukaya */ public class VideoLocalizations { /** * Define a global instance of a YouTube object, which will be used to make * YouTube Data API requests. */ private static YouTube youtube; /** * Set and retrieve localized metadata for a video. * * @param args command line args (not used). */ public static void main(String[] args) { // This OAuth 2.0 access scope allows for full read/write access to the // authenticated user's account. List<String> scopes = Lists.newArrayList("https://www.googleapis.com/auth/youtube"); try { // Authorize the request. Credential credential = Auth.authorize(scopes, "localizations"); // This object is used to make YouTube Data API requests. youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, credential) .setApplicationName("youtube-cmdline-localizations-sample").build(); // Prompt the user to specify the action of the be achieved. String actionString = getActionFromUser(); System.out.println("You chose " + actionString + "."); //Map the user input to the enum values. Action action = Action.valueOf(actionString.toUpperCase()); switch (action) { case SET: setVideoLocalization(getId("video"), getDefaultLanguage(), getLanguage(), getMetadata("title"), getMetadata("description")); break; case GET: getVideoLocalization(getId("video"), getLanguage()); break; case LIST: listVideoLocalizations(getId("video")); break; } } catch (GoogleJsonResponseException e) { System.err.println("GoogleJsonResponseException code: " + e.getDetails().getCode() + " : " + e.getDetails().getMessage()); e.printStackTrace(); } catch (IOException e) { System.err.println("IOException: " + e.getMessage()); e.printStackTrace(); } catch (Throwable t) { System.err.println("Throwable: " + t.getMessage()); t.printStackTrace(); } } /** * Updates a video's default language and sets its localized metadata. * * @param videoId The id parameter specifies the video ID for the resource * that is being updated. * @param defaultLanguage The language of the video's default metadata * @param language The language of the localized metadata * @param title The localized title to be set * @param description The localized description to be set * @throws IOException */ private static void setVideoLocalization(String videoId, String defaultLanguage, String language, String title, String description) throws IOException { // Call the YouTube Data API's videos.list method to retrieve videos. VideoListResponse videoListResponse = youtube.videos(). list("snippet,localizations").setId(videoId).execute(); // Since the API request specified a unique video ID, the API // response should return exactly one video. If the response does // not contain a video, then the specified video ID was not found. List<Video> videoList = videoListResponse.getItems(); if (videoList.isEmpty()) { System.out.println("Can't find a video with ID: " + videoId); return; } Video video = videoList.get(0); // Modify video's default language and localizations properties. // Ensure that a value is set for the resource's snippet.defaultLanguage property. video.getSnippet().setDefaultLanguage(defaultLanguage); // Preserve any localizations already associated with the video. If the // video does not have any localizations, create a new array. Append the // provided localization to the list of localizations associated with the video. Map<String, VideoLocalization> localizations = video.getLocalizations(); if (localizations == null) { localizations = new ArrayMap<String, VideoLocalization>(); video.setLocalizations(localizations); } VideoLocalization videoLocalization = new VideoLocalization(); videoLocalization.setTitle(title); videoLocalization.setDescription(description); localizations.put(language, videoLocalization); // Update the video resource by calling the videos.update() method. Video videoResponse = youtube.videos().update("snippet,localizations", video) .execute(); // Print information from the API response. System.out.println("\n================== Updated Video ==================\n"); System.out.println(" - ID: " + videoResponse.getId()); System.out.println(" - Default Language: " + videoResponse.getSnippet().getDefaultLanguage()); System.out.println(" - Title(" + language + "): " + videoResponse.getLocalizations().get(language).getTitle()); System.out.println(" - Description(" + language + "): " + videoResponse.getLocalizations().get(language).getDescription()); System.out.println("\n-------------------------------------------------------------\n"); } /** * Returns localized metadata for a video in a selected language. * If the localized text is not available in the requested language, * this method will return text in the default language. * * @param videoId The id parameter specifies the video ID for the resource * that is being updated. * @param language The language of the localized metadata * @throws IOException */ private static void getVideoLocalization(String videoId, String language) throws IOException { // Call the YouTube Data API's videos.list method to retrieve videos. VideoListResponse videoListResponse = youtube.videos(). list("snippet").setId(videoId).set("hl", language).execute(); // Since the API request specified a unique video ID, the API // response should return exactly one video. If the response does // not contain a video, then the specified video ID was not found. List<Video> videoList = videoListResponse.getItems(); if (videoList.isEmpty()) { System.out.println("Can't find a video with ID: " + videoId); return; } Video video = videoList.get(0); // Print information from the API response. System.out.println("\n================== Video ==================\n"); System.out.println(" - ID: " + video.getId()); System.out.println(" - Title(" + language + "): " + video.getLocalizations().get(language).getTitle()); System.out.println(" - Description(" + language + "): " + video.getLocalizations().get(language).getDescription()); System.out.println("\n-------------------------------------------------------------\n"); } /** * Returns a list of localized metadata for a video. * * @param videoId The id parameter specifies the video ID for the resource * that is being updated. * @throws IOException */ private static void listVideoLocalizations(String videoId) throws IOException { // Call the YouTube Data API's videos.list method to retrieve videos. VideoListResponse videoListResponse = youtube.videos(). list("snippet,localizations").setId(videoId).execute(); // Since the API request specified a unique video ID, the API // response should return exactly one video. If the response does // not contain a video, then the specified video ID was not found. List<Video> videoList = videoListResponse.getItems(); if (videoList.isEmpty()) { System.out.println("Can't find a video with ID: " + videoId); return; } Video video = videoList.get(0); Map<String, VideoLocalization> localizations = video.getLocalizations(); // Print information from the API response. System.out.println("\n================== Video ==================\n"); System.out.println(" - ID: " + video.getId()); for (String language : localizations.keySet()) { System.out.println(" - Title(" + language + "): " + localizations.get(language).getTitle()); System.out.println(" - Description(" + language + "): " + localizations.get(language).getDescription()); } System.out.println("\n-------------------------------------------------------------\n"); } /* * Prompt the user to enter a resource ID. Then return the ID. */ private static String getId(String resource) throws IOException { String id = ""; System.out.print("Please enter a " + resource + " id: "); BufferedReader bReader = new BufferedReader(new InputStreamReader(System.in)); id = bReader.readLine(); System.out.println("You chose " + id + " for localizations."); return id; } /* * Prompt the user to enter the localized metadata. Then return the metadata. */ private static String getMetadata(String type) throws IOException { String metadata = ""; System.out.print("Please enter a localized " + type + ": "); BufferedReader bReader = new BufferedReader(new InputStreamReader(System.in)); metadata = bReader.readLine(); if (metadata.length() < 1) { // If nothing is entered, defaults to type. metadata = type + "(localized)"; } System.out.println("You chose " + metadata + " as localized "+ type + "."); return metadata; } /* * Prompt the user to enter the language for the resource's default metadata. * Then return the language. */ private static String getDefaultLanguage() throws IOException { String defaultlanguage = ""; System.out.print("Please enter the language for the resource's default metadata: "); BufferedReader bReader = new BufferedReader(new InputStreamReader(System.in)); defaultlanguage = bReader.readLine(); if (defaultlanguage.length() < 1) { // If nothing is entered, defaults to "en". defaultlanguage = "en"; } System.out.println("You chose " + defaultlanguage + " as the language for the resource's default metadata."); return defaultlanguage; } /* * Prompt the user to enter a language for the localized metadata. Then return the language. */ private static String getLanguage() throws IOException { String language = ""; System.out.print("Please enter the localized metadata language: "); BufferedReader bReader = new BufferedReader(new InputStreamReader(System.in)); language = bReader.readLine(); if (language.length() < 1) { // If nothing is entered, defaults to "de". language = "de"; } System.out.println("You chose " + language + " as the localized metadata language."); return language; } /* * Prompt the user to enter an action. Then return the action. */ private static String getActionFromUser() throws IOException { String action = ""; System.out.print("Please choose action to be accomplished: "); System.out.print("Options are: 'set', 'get' and 'list' "); BufferedReader bReader = new BufferedReader(new InputStreamReader(System.in)); action = bReader.readLine(); return action; } public enum Action { SET, GET, LIST } }
PHP #1
This sample calls the API'ssearch.list
method with the type
, q
,
location
and locationRadius
parameters to retrieve search results matching the provided
keyword within the radius centered at a particular location. Using the video IDs from the search result, the sample
calls the API's videos.list
method to retrieve location details of each video.
This example uses the PHP client library.
<?php /** * This sample lists videos that are associated with a particular keyword and are in the radius of * particular geographic coordinates by: * * 1. Searching videos with "youtube.search.list" method and setting "type", "q", "location" and * "locationRadius" parameters. * 2. Retrieving location details for each video with "youtube.videos.list" method and setting * "id" parameter to comma separated list of video IDs in search result. * * @author Ibrahim Ulukaya */ /** * 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> Location: <input type="text" id="location" name="location" placeholder="37.42307,-122.08427"> </div> <div> Location Radius: <input type="text" id="locationRadius" name="locationRadius" placeholder="5km"> </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 executes if the user enters a search query in the form // and submits 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 Cloud Console }} <{{ https://cloud.google.com/console }}> * 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); try { // Call the search.list method to retrieve results matching the specified // query term. $searchResponse = $youtube->search->listSearch('id,snippet', array( 'type' => 'video', 'q' => $_GET['q'], 'location' => $_GET['location'], 'locationRadius' => $_GET['locationRadius'], 'maxResults' => $_GET['maxResults'], )); $videoResults = array(); # Merge video ids foreach ($searchResponse['items'] as $searchResult) { array_push($videoResults, $searchResult['id']['videoId']); } $videoIds = join(',', $videoResults); # Call the videos.list method to retrieve location details for each video. $videosResponse = $youtube->videos->listVideos('snippet, recordingDetails', array( 'id' => $videoIds, )); $videos = ''; // Display the list of matching videos. foreach ($videosResponse['items'] as $videoResult) { $videos .= sprintf('<li>%s (%s,%s)</li>', $videoResult['snippet']['title'], $videoResult['recordingDetails']['location']['latitude'], $videoResult['recordingDetails']['location']['longitude']); } $htmlBody .= <<<END <h3>Videos</h3> <ul>$videos</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 Geolocation Search</title> </head> <body> <?=$htmlBody?> </body> </html>
PHP #2
This sample demonstrates how to use the following API methods to set and retrieve localized metadata for a video:- It calls the
videos.update
method to update the default language of a video's metadata and to add a localized version of this metadata in a selected language. - It calls the
videos.list
method with thehl
parameter set to a specific language to retrieve localized metadata in that language. - It calls the
videos.list
method and includeslocalizations
in thepart
parameter value to retrieve all of the localized metadata for that video.
This example uses the PHP client library.
<?php /** * This sample sets and retrieves localized metadata for a video by: * * 1. Updating language of the default metadata and setting localized metadata * for a video via "videos.update" method. * 2. Getting the localized metadata for a video in a selected language using the * "videos.list" method and setting the "hl" parameter. * 3. Listing the localized metadata for a video using the "videos.list" method and * including "localizations" in the "part" parameter. * * @author Ibrahim Ulukaya */ /** * 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'; session_start(); $htmlBody = <<<END <form method="GET"> <div> Action: <select id="action" name="action"> <option value="set">Set Localization - Fill in: video ID, default language, language, title and description</option> <option value="get">Get Localization- Fill in: video ID, language</option> <option value="list">List Localizations - Fill in: video ID, language</option> </select> </div> <br> <div> Video ID: <input type="text" id="videoId" name="videoId" placeholder="Enter Video ID"> </div> <br> <div> Default Language: <input type="text" id="defaultLanguage" name="defaultLanguage" placeholder="Enter Default Language (BCP-47 language code)"> </div> <br> <div> Language: <input type="text" id="language" name="language" placeholder="Enter Local Language (BCP-47 language code)"> </div> <br> <div> Title: <input type="text" id="title" name="title" placeholder="Enter Title"> </div> <br> <div> Description: <input type="text" id="description" name="description" placeholder="Enter Description"> </div> <br> <input type="submit" value="GO!"> </form> END; /* * You can acquire an OAuth 2.0 client ID and client secret from the * {{ Google Cloud Console }} <{{ https://cloud.google.com/console }}> * For more information about using OAuth 2.0 to access Google APIs, please see: * <https://developers.google.com/youtube/v3/guides/authentication> * Please ensure that you have enabled the YouTube Data API for your project. */ $OAUTH2_CLIENT_ID = 'REPLACE_ME'; $OAUTH2_CLIENT_SECRET = 'REPLACE_ME'; $client = new Google_Client(); $client->setClientId($OAUTH2_CLIENT_ID); $client->setClientSecret($OAUTH2_CLIENT_SECRET); /* * This OAuth 2.0 access scope allows for full read/write access to the * authenticated user's account. */ $client->setScopes('https://www.googleapis.com/auth/youtube'); $redirect = filter_var('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'], FILTER_SANITIZE_URL); $client->setRedirectUri($redirect); // Define an object that will be used to make all API requests. $youtube = new Google_Service_YouTube($client); // Check if an auth token exists for the required scopes $tokenSessionKey = 'token-' . $client->prepareScopes(); if (isset($_GET['code'])) { if (strval($_SESSION['state']) !== strval($_GET['state'])) { die('The session state did not match.'); } $client->authenticate($_GET['code']); $_SESSION[$tokenSessionKey] = $client->getAccessToken(); header('Location: ' . $redirect); } if (isset($_SESSION[$tokenSessionKey])) { $client->setAccessToken($_SESSION[$tokenSessionKey]); } // Check to ensure that the access token was successfully acquired. if ($client->getAccessToken()) { // This code executes if the user enters an action in the form // and submits the form. Otherwise, the page displays the form above. if (isset($_GET['action'])) { $htmlBody = ''; $videoId = $_GET['videoId']; $language = $_GET['language']; $defaultLanguage = $_GET['defaultLanguage']; $title = $_GET['title']; $description = $_GET['description']; try { switch ($_GET['action']) { case 'set': setVideoLocalization($youtube, $videoId, $defaultLanguage, $language, $title, $description, $htmlBody); break; case 'get': getVideoLocalization($youtube, $videoId, $language, $htmlBody); break; case 'list': listVideoLocalizations($youtube, $videoId, $htmlBody); break; } } 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())); } } $_SESSION[$tokenSessionKey] = $client->getAccessToken(); } elseif ($OAUTH2_CLIENT_ID == 'REPLACE_ME') { $htmlBody = <<<END <h3>Client Credentials Required</h3> <p> You need to set <code>\$OAUTH2_CLIENT_ID</code> and <code>\$OAUTH2_CLIENT_ID</code> before proceeding. <p> END; } else { // If the user hasn't authorized the app, initiate the OAuth flow $state = mt_rand(); $client->setState($state); $_SESSION['state'] = $state; $authUrl = $client->createAuthUrl(); $htmlBody = <<<END <h3>Authorization Required</h3> <p>You need to <a href="$authUrl">authorize access</a> before proceeding.<p> END; } /** * Updates a video's default language and sets its localized metadata. * * @param Google_Service_YouTube $youtube YouTube service object. * @param string $videoId The id parameter specifies the video ID for the resource * that is being updated. * @param string $defaultLanguage The language of the video's default metadata * @param string $language The language of the localized metadata * @param string $title The localized title to be set * @param string $description The localized description to be set * @param $htmlBody - html body. */ function setVideoLocalization(Google_Service_YouTube $youtube, $videoId, $defaultLanguage, $language, $title, $description, &$htmlBody) { // Call the YouTube Data API's videos.list method to retrieve videos. $videos = $youtube->videos->listVideos("snippet,localizations", array( 'id' => $videoId )); // If $videos is empty, the specified video was not found. if (empty($videos)) { $htmlBody .= sprintf('<h3>Can\'t find a video with video id: %s</h3>', $videoId); } else { // Since the request specified a video ID, the response only // contains one video resource. $updateVideo = $videos[0]; // Modify video's default language and localizations properties. // Ensure that a value is set for the resource's snippet.defaultLanguage property. $updateVideo['snippet']['defaultLanguage'] = $defaultLanguage; $localizations = $updateVideo['localizations']; if (is_null($localizations)) { $localizations = array(); } $localizations[$language] = array('title' => $title, 'description' => $description); $updateVideo['localizations'] = $localizations; // Call the YouTube Data API's videos.update method to update an existing video. $videoUpdateResponse = $youtube->videos->update("snippet,localizations", $updateVideo); $htmlBody .= "<h2>Updated video</h2><ul>"; $htmlBody .= sprintf('<li>(%s) default language: %s</li>', $videoId, $videoUpdateResponse['snippet']['defaultLanguage']); $htmlBody .= sprintf('<li>title(%s): %s</li>', $language, $videoUpdateResponse['localizations'][$language]['title']); $htmlBody .= sprintf('<li>description(%s): %s</li>', $language, $videoUpdateResponse['localizations'][$language]['description']); $htmlBody .= '</ul>'; } } /** * Returns localized metadata for a video in a selected language. * If the localized text is not available in the requested language, * this method will return text in the default language. * * @param Google_Service_YouTube $youtube YouTube service object. * @param string $videoId The videoId parameter instructs the API to return the * localized metadata for the video specified by the video id. * @param string language The language of the localized metadata. * @param $htmlBody - html body. */ function getVideoLocalization(Google_Service_YouTube $youtube, $videoId, $language, &$htmlBody) { // Call the YouTube Data API's videos.list method to retrieve videos. $videos = $youtube->videos->listVideos("snippet", array( 'id' => $videoId, 'hl' => $language )); // If $videos is empty, the specified video was not found. if (empty($videos)) { $htmlBody .= sprintf('<h3>Can\'t find a video with video id: %s</h3>', $videoId); } else { // Since the request specified a video ID, the response only // contains one video resource. $localized = $videos[0]["snippet"]["localized"]; $htmlBody .= "<h3>Video</h3><ul>"; $htmlBody .= sprintf('<li>title(%s): %s</li>', $language, $localized['title']); $htmlBody .= sprintf('<li>description(%s): %s</li>', $language, $localized['description']); $htmlBody .= '</ul>'; } } /** * Returns a list of localized metadata for a video. * * @param Google_Service_YouTube $youtube YouTube service object. * @param string $videoId The videoId parameter instructs the API to return the * localized metadata for the video specified by the video id. * @param $htmlBody - html body. */ function listVideoLocalizations(Google_Service_YouTube $youtube, $videoId, &$htmlBody) { // Call the YouTube Data API's videos.list method to retrieve videos. $videos = $youtube->videos->listVideos("snippet,localizations", array( 'id' => $videoId )); // If $videos is empty, the specified video was not found. if (empty($videos)) { $htmlBody .= sprintf('<h3>Can\'t find a video with video id: %s</h3>', $videoId); } else { // Since the request specified a video ID, the response only // contains one video resource. $localizations = $videos[0]["localizations"]; $htmlBody .= "<h3>Video</h3><ul>"; foreach ($localizations as $language => $localization) { $htmlBody .= sprintf('<li>title(%s): %s</li>', $language, $localization['title']); $htmlBody .= sprintf('<li>description(%s): %s</li>', $language, $localization['description']); } $htmlBody .= '</ul>'; } } ?> <!doctype html> <html> <head> <title>Set and retrieve localized metadata for a video</title> </head> <body> <?=$htmlBody?> </body> </html>
Python #1
This sample calls the API'ssearch.list
method with the type
,
q
, location
, and locationRadius
parameters to retrieve search results
matching the provided keyword within the radius centered at a particular location. Using the video ids from
the search result, the sample calls the API's videos.list
method to retrieve location details
of each video.
This example uses the Python client library.
#!/usr/bin/python # This sample executes a search request for the specified search term. # Sample usage: # python geolocation_search.py --q=surfing --location-"37.42307,-122.08427" --location-radius=50km --max-results=10 # NOTE: To use the sample, you must provide a developer key obtained # in the Google APIs Console. Search for "REPLACE_ME" in this code # to find the correct place to provide that key.. import argparse from googleapiclient.discovery import build from googleapiclient.errors import HttpError # 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, type='video', location=options.location, locationRadius=options.location_radius, part='id,snippet', maxResults=options.max_results ).execute() search_videos = [] # Merge video ids for search_result in search_response.get('items', []): search_videos.append(search_result['id']['videoId']) video_ids = ','.join(search_videos) # Call the videos.list method to retrieve location details for each video. video_response = youtube.videos().list( id=video_ids, part='snippet, recordingDetails' ).execute() videos = [] # Add each result to the list, and then display the list of matching videos. for video_result in video_response.get('items', []): videos.append('%s, (%s,%s)' % (video_result['snippet']['title'], video_result['recordingDetails']['location']['latitude'], video_result['recordingDetails']['location']['longitude'])) print 'Videos:\n', '\n'.join(videos), '\n' if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--q', help='Search term', default='Google') parser.add_argument('--location', help='Location', default='37.42307,-122.08427') parser.add_argument('--location-radius', help='Location radius', default='5km') parser.add_argument('--max-results', help='Max results', default=25) args = parser.parse_args() try: youtube_search(args) except HttpError, e: print 'An HTTP error %d occurred:\n%s' % (e.resp.status, e.content)
Python #2
This sample demonstrates how to use the following API methods to set and retrieve localized metadata for a video:- It calls the
videos.update
method to update the default language of a video's metadata and to add a localized version of this metadata in a selected language. - It calls the
videos.list
method with thehl
parameter set to a specific language to retrieve localized metadata in that language. - It calls the
videos.list
method and includeslocalizations
in thepart
parameter value to retrieve all of the localized metadata for that video.
This example uses the Python client library.
#!/usr/bin/python # Usage example: # python video_localizations.py --action='<action>' --video_id='<video_id>' --default_language='<default_language>' --language='<language>' --title='<title>' --description='<description>' import argparse import os import re import google.oauth2.credentials import google_auth_oauthlib.flow from googleapiclient.discovery import build from googleapiclient.errors import HttpError from google_auth_oauthlib.flow import InstalledAppFlow # The CLIENT_SECRETS_FILE variable specifies the name of a file that contains # the OAuth 2.0 information for this application, including its client_id and # client_secret. You can acquire an OAuth 2.0 client ID and client secret from # the {{ Google Cloud Console }} at # {{ https://cloud.google.com/console }}. # Please ensure that you have enabled the YouTube Data API for your project. # For more information about using OAuth2 to access the YouTube Data API, see: # https://developers.google.com/youtube/v3/guides/authentication # For more information about the client_secrets.json file format, see: # https://developers.google.com/api-client-library/python/guide/aaa_client_secrets CLIENT_SECRETS_FILE = 'client_secret.json' # This OAuth 2.0 access scope allows for full read/write access to the # authenticated user's account. SCOPES = ['https://www.googleapis.com/auth/youtube'] API_SERVICE_NAME = 'youtube' API_VERSION = 'v3' # Supported actions ACTIONS = ('get', 'list', 'set') # Authorize the request and store authorization credentials. def get_authenticated_service(): flow = InstalledAppFlow.from_client_secrets_file(CLIENT_SECRETS_FILE, SCOPES) credentials = flow.run_console() return build(API_SERVICE_NAME, API_VERSION, credentials = credentials) # Call the API's videos.update method to update an existing video's default language, # localized title and description in a specific language. def set_video_localization(youtube, args): # Retrieve the snippet and localizations for the video. results = youtube.videos().list( part='snippet,localizations', id=args.video_id ).execute() video = results['items'][0] # If the language argument is set, set the localized title and description # for that language. The "title" and "description" arguments have default # values to make the script simpler to run as a demo. In an actual app, you # would likely want to set those arguments also. if args.language and args.language != '': if 'localizations' not in video: video['localizations'] = {} video['localizations'][args.language] = { 'title': args.title, 'description': args.description } # If the default language is set AND there is localized metadata for that # language, set the video's title and description to match the localized # title and description for the newly set default language. if args.default_language and args.default_language in video['localizations']: video['snippet']['defaultLanguage'] = args.default_language video['snippet']['title'] = ( video['localizations'][args.default_language]['title']) video['snippet']['description'] = ( video['localizations'][args.default_language]['description']) # Update the video resource. update_result = youtube.videos().update( part='snippet,localizations', body=video ).execute() # Print the actions taken by running the script. if args.language: for language in update_result['localizations']: # Languages with locales, like "pt-br" are returned as pt-BR in metadata. # This ensures that the language specified when running the script can be # matched to the language returned in the metadata. if language.lower() == args.language.lower(): localization = update_result['localizations'][args.language] print ('Updated video \'%s\' localized title to \'%s\'' ' and description to \'%s\' in language \'%s\'' % (args.video_id, localization['title'], localization['description'], args.language)) break if (args.default_language and args.default_language == update_result['snippet']['defaultLanguage']): print 'Updated default language to %s' % args.default_language # Call the API's videos.list method to retrieve an existing video localization. # If the localized text is not available in the requested language, # this method returns text in the default language. def get_video_localization(youtube, args): results = youtube.videos().list( part='snippet', id=args.video_id, hl=args.language ).execute() # The localized object contains localized text if the hl parameter specified # a language for which localized text is available. Otherwise, the localized # object contains metadata in the default language. localized = results['items'][0]['snippet']['localized'] print ('Video title is \'%s\' and description is \'%s\' in language \'%s\'' % (localized['title'], localized['description'], args.language)) # Call the API's videos.list method to list the existing video localizations. def list_video_localizations(youtube, args): results = youtube.videos().list( part='snippet,localizations', id=args.video_id ).execute() if 'localizations' in results['items'][0]: localizations = results['items'][0]['localizations'] for language, localization in localizations.iteritems(): print ('Video title is \'%s\' and description is \'%s\' in language \'%s\'' % (localization['title'], localization['description'], language)) else: print 'There aren\'t any localizations for this video yet.' if __name__ == '__main__': parser = argparse.ArgumentParser() # The action to be processed: 'get', 'list', and 'set' are supported. parser.add_argument('--action', help='Action', choices=ACTIONS, required=True) # The ID of the selected YouTube video. parser.add_argument('--video_id', help='The video ID for which localizations are being set or retrieved.', required=True) # The language of the video's default metadata. parser.add_argument('--default_language', help='Default language of the video to update.') # The language of the localization that is being processed. parser.add_argument('--language', help='Language of the localization.') # The localized video title for the specified language. parser.add_argument('--title', help='Localized title of the video to be set.', default='Localized Title') # The localized description for the specified language. parser.add_argument('--description', help='Localized description of the video to be set.', default='Localized Description') args = parser.parse_args() if not args.video_id: exit('Please specify video id using the --video_id= parameter.') youtube = get_authenticated_service() try: if args.action == 'set': set_video_localization(youtube, args) elif args.action == 'get': get_video_localization(youtube, args) elif args.action == 'list': list_video_localizations(youtube, args) except HttpError, e: print 'An HTTP error %d occurred:\n%s' % (e.resp.status, e.content) else: print 'Set and retrieved localized metadata for a video
Erros
A tabela abaixo identifica as mensagens de erro que a API pode retornar em resposta a uma chamada para este método. Consulte a documentação mensagem de erro para mais detalhes.
Tipo de erro | Detalhe do erro | Descrição |
---|---|---|
badRequest |
videoChartNotFound |
O gráfico de vídeo solicitado não é suportado ou não está disponível. |
forbidden |
forbidden |
A solicitação não pode acessar informações de avaliação do usuário. Este erro pode ocorrer porque a solicitação não está devidamente autorizada a usar o parâmetro myRating . |
Conheça agora.
Use o Explorador de API para chamar este método em dados ativos e ver a solicitação e a resposta da API.