Data API 代码段

操作说明

交互式代码段工具可让您轻松测试 API 请求,并生成特定于这些请求的代码示例。对于任何给定的方法,该工具会显示一个或多个用例的代码段,并且每个用例都会描述调用该方法的常用方法。例如,您可以调用 channels.list 方法来检索有关特定频道或当前用户频道的数据。

执行 API 请求

您可以点击请求参数列表旁边的执行按钮来执行请求。如果您之前没有授权应用程序代表您提交 API 请求,系统将提示您进行授权。作为一项额外的预防措施,如果您的请求执行了写入操作(插入、更新或删除与您的频道关联的资源),系统会要求您确认是否想要执行该请求,然后再实际执行。

切换代码段和完整示例

对于每个用例,该工具都会显示一个代码段,用于标识特定于所调用的特定方法的代码。每个代码段标识了所调用的方法,以及 API 请求中使用的参数和属性值。

此外,该工具还会显示完整的代码示例,该示例将代码段放入模板中,该模板定义了授权 API 请求和构建 API 请求所需的样板函数。您可以使用示例上方的滑块在代码段和完整示例之间切换:

在本地运行完整的代码示例

完整的代码示例可在本地复制和运行。请注意以下前提条件并设置运行完整代码示例的步骤:

<ph type="x-smartling-placeholder">
</ph> <ph type="x-smartling-placeholder">
</ph>
Java

前提条件

  • Java 1.7 或更高版本
  • Gradle 2.3 或更高版本

设置项目并运行代码示例

  1. API 控制台中创建一个项目,并为 Web 应用设置凭据。根据需要设置已获授权的重定向 URI。

  2. 按照 API Java 快速入门指南中的说明准备您的项目,但要将默认 build.gradle 文件的内容替换为以下代码:

     apply plugin: 'java' apply plugin: 'application'  mainClassName = 'ApiExample' sourceCompatibility = 1.7 targetCompatibility = 1.7 version = '1.0'  repositories {     mavenCentral() }  dependencies {     compile 'com.google.api-client:google-api-client:1.22.0'     compile 'com.google.oauth-client:google-oauth-client-jetty:1.22.0'     compile 'com.google.apis:google-api-services-youtube:v3-rev182-1.22.0'     compile group: 'com.google.code.gson', name: 'gson', version: '1.7.2'     compile group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.4.4' }  compileJava {     options.compilerArgs << "-Xlint:unchecked" << "-Xlint:deprecation" }
  3. 在工作目录中,将与您的凭据关联的 client_secrets.json 文件保存到 src/main/resources/client_secret.json

  4. 从您的工作目录中,将完整的代码示例复制到 src/main/java/ApiExample.java。(每个示例中的类名称均为 ApiExample,因此您无需修改 build.gradle 文件即可运行不同的示例。)

  5. 从命令行运行该示例:

    gradle -q run
  6. 大多数示例会将某些内容输出到 STDOUT。您也可以访问 YouTube 网站,了解写入数据的请求(例如创建播放列表或频道版块的请求)的效果。

<ph type="x-smartling-placeholder">
</ph>
JavaScript
  1. API 控制台中创建一个项目,并为 Web 应用设置凭据。设置已获授权的 JavaScript 来源,以确定您将从中发送请求的网址(例如 http://localhost)。

  2. 将完整的代码示例复制到您的 Web 服务器可访问的本地文件中(例如 /var/www/html/example.html)。

  3. 在代码示例中找到设置要用于请求的客户端 ID 的行,并将值替换为凭据的客户端 ID:

    gapi.client.init({     'clientId': 'REPLACE_ME',
  4. 在浏览器中打开文件(例如 http://localhost/example.html)。建议使用带有调试控制台的浏览器,例如 Google Chrome。

  5. 根据需要为请求授权。如果请求获得授权,调试控制台应以 JSON 对象形式显示该请求的 API 响应。

<ph type="x-smartling-placeholder">
</ph>
Node.js

前提条件

  • 必须安装 Node.js。
  • npm 软件包管理工具(随 Node.js 一起提供)。
  • 适用于 Node.js 的 Google API 客户端库:
    npm install googleapis --save
  • 能够访问互联网和网络浏览器。
  • Google 账号

设置项目并运行代码示例

  1. API 控制台中创建项目,并在 Google API 控制台中设置 OAuth 2.0 凭据。设置凭据时,将应用类型设置为其他

  2. 将与您的凭据关联的 client_secret.json 文件保存到本地文件。

  3. 将完整的代码示例复制到 client_secret.json 文件所在目录中的本地文件中(或修改示例以正确标识该文件的位置)。

  4. 从命令行运行该示例:

    node sample.js
  5. 大多数示例会将内容输出到 STDOUT,对于 Web 应用示例,则会输出到您正在查看的网页。您也可以访问 YouTube 网站,了解写入数据的请求(例如创建播放列表或频道版块的请求)的效果。

<ph type="x-smartling-placeholder">
</ph>
Python

前提条件

  • Python 2.6 或更高版本
  • pip 软件包管理工具
  • 适用于 Python 的 Google API 客户端库:
    pip install --upgrade google-api-python-client
  • 用于用户授权的 google-auth、google-auth-oauthlib 和 google-auth-httplib2。
    pip install --upgrade google-auth google-auth-oauthlib google-auth-httplib2
  • Flask Python Web 应用框架(如果您要为 Web 服务器应用运行 Python 示例)。
    pip install --upgrade flask
  • 请求 HTTP 库。
    pip install --upgrade requests

设置项目并运行代码示例

  1. API 控制台中创建项目,并在 Google API 控制台中设置 OAuth 2.0 凭据。设置凭据时,对于使用 Flask Python Web 应用框架的示例,请将应用类型设置为 Web 应用,并为这些凭据设置已获授权的重定向 URI。否则,请将应用类型设置为其他

  2. 将与您的凭据关联的 client_secret.json 文件保存到本地文件。

  3. 将完整的代码示例复制到 client_secret.json 文件所在目录中的本地文件中(或修改示例以正确标识该文件的位置)。

  4. 从命令行运行该示例:

    python sample.py
    网络服务器应用示例注意事项

    如果您要为网络服务器应用运行 Python 示例,则运行脚本会启动本地网络服务器。如需实际执行 API 请求,您需要在浏览器中转到提供的网页。例如,使用 Flask Web 应用框架的 Python 示例包含如下所示的一行代码:

    app.run('localhost', 8080, debug=True)

    此代码会在 http://localhost:8080 启动一个本地网络服务器。不过,在您在浏览器中实际导航到 http://localhost:8080 之前,脚本不会尝试执行 API 请求。(还必须将您的本地服务器的网址设置为授权凭据的授权重定向 URI。)
  5. 大多数示例会将内容输出到 STDOUT,对于 Web 应用示例,则会输出到您正在查看的网页。您也可以访问 YouTube 网站,了解写入数据的请求(例如创建播放列表或频道版块的请求)的效果。

<ph type="x-smartling-placeholder">
</ph>
PHP

前提条件

  • 安装了命令行界面 (CLI) 和 JSON 扩展程序的 PHP 5.4 或更高版本。
  • Composer 依赖项管理工具。
  • 适用于 PHP 的 Google API 客户端库:
    php composer.phar require google/apiclient:^2.0

设置项目并运行代码示例

  1. API 控制台中创建项目,并在 Google API 控制台中设置 OAuth 2.0 凭据。设置凭据时,将应用类型设置为其他

  2. 将与您的凭据关联的 client_secret.json 文件保存到本地文件。

  3. 将完整的代码示例复制到 client_secret.json 文件所在目录中的本地文件中(或修改示例以正确标识该文件的位置)。

  4. 从命令行运行该示例:

    php sample.php
  5. 大多数示例会将内容输出到 STDOUT,对于 Web 应用示例,则会输出到您正在查看的网页。您也可以访问 YouTube 网站,了解写入数据的请求(例如创建播放列表或频道版块的请求)的效果。

<ph type="x-smartling-placeholder">
</ph>
红宝石

前提条件

  • Ruby 2.0 或更高版本
  • 适用于 Ruby 的 Google API 客户端库:
    gem install google-api-client

设置项目并运行代码示例

  1. API 控制台中创建项目,并在 Google API 控制台中设置 OAuth 2.0 凭据。设置凭据时,将应用类型设置为其他

  2. 将与您的凭据关联的 client_secret.json 文件保存到本地文件。

  3. 将完整的代码示例复制到 client_secret.json 文件所在目录中的本地文件中(或修改示例以正确标识该文件的位置)。

  4. 从命令行运行该示例:

    ruby sample.rb
  5. 大多数示例会将内容输出到 STDOUT,对于 Web 应用示例,则会输出到您正在查看的网页。您也可以访问 YouTube 网站,了解写入数据的请求(例如创建播放列表或频道版块的请求)的效果。

<ph type="x-smartling-placeholder">。 <ph type="x-smartling-placeholder">
</ph>
开始
  1. API 控制台中创建项目,并在 Google API 控制台中设置 OAuth 2.0 凭据。设置凭据时,将应用类型设置为其他

  2. 将与您的凭据关联的 client_secret.json 文件保存到本地文件。

  3. 将完整的代码示例复制到 client_secret.json 文件所在目录中的本地文件中(或修改示例以正确标识该文件的位置)。

  4. 从命令行运行该示例:

    go run sample.go
  5. 大多数示例会将内容输出到 STDOUT,对于 Web 应用示例,则会输出到您正在查看的网页。您也可以访问 YouTube 网站,了解写入数据的请求(例如创建播放列表或频道版块的请求)的效果。

使用样板函数

如上所述,完整的代码示例均使用样板代码来授权和构建 API 请求。例如,Python 示例中的 build_resource 函数使用将资源属性映射到其值的字典,以构建可插入或更新的资源。为 JavaScript、PHP、Ruby、Go 和 Apps Script 提供了类似的函数。

例如,以下标签页显示了如何调用用于构建资源的样板函数来构建 playlist 资源。请注意,样板函数不需要知道正在创建哪种类型的资源。

<ph type="x-smartling-placeholder">
</ph> <ph type="x-smartling-placeholder">
</ph>
JavaScript
 function createResource(properties) {   var resource = {};   var normalizedProps = properties;   for (var p in properties) {     var value = properties[p];     if (p && p.substr(-2, 2) == '[]') {       var adjustedName = p.replace('[]', '');       if (value) {         normalizedProps[adjustedName] = value.split(',');       }       delete normalizedProps[p];     }   }   for (var p in normalizedProps) {     // Leave properties that don't have values out of inserted resource.     if (normalizedProps.hasOwnProperty(p) && normalizedProps[p]) {       var propArray = p.split('.');       var ref = resource;       for (var pa = 0; pa < propArray.length; pa++) {         var key = propArray[pa];         if (pa == propArray.length - 1) {           ref[key] = normalizedProps[p];         } else {           ref = ref[key] = ref[key] || {};         }       }     };   }   return resource; } var resource = createResource({     'snippet.title': 'Sample playlist ',     'snippet.description': 'This is a sample playlist description.',     'snippet.tags[]': 'JavaScript code, interactive',     'snippet.defaultLanguage': '',     'status.privacyStatus': 'private' }
Python
 # Build a resource based on a list of properties given as key-value pairs. # Leave properties with empty values out of the inserted resource. def build_resource(properties):   resource = {}   for p in properties:     # Given a key like "snippet.title", split into "snippet" and "title", where     # "snippet" will be an object and "title" will be a property in that object.     prop_array = p.split('.')     ref = resource     for pa in range(0, len(prop_array)):       is_array = False       key = prop_array[pa]       # Convert a name like "snippet.tags[]" to snippet.tags, but handle       # the value as an array.       if key[-2:] == '[]':         key = key[0:len(key)-2:]         is_array = True       if pa == (len(prop_array) - 1):         # Leave properties without values out of inserted resource.         if properties[p]:           if is_array:             ref[key] = properties[p].split(',')           else:             ref[key] = properties[p]       elif key not in ref:         # For example, the property is "snippet.title", but the resource does         # not yet have a "snippet" object. Create the snippet object here.         # Setting "ref = ref[key]" means that in the next time through the         # "for pa in range ..." loop, we will be setting a property in the         # resource's "snippet" object.         ref[key] = {}         ref = ref[key]       else:         # For example, the property is "snippet.description", and the resource         # already has a "snippet" object.         ref = ref[key]   return resource  resource = build_resource({     'snippet.title': 'Sample playlist ',     'snippet.description': 'This is a sample playlist description.',     'snippet.tags[]': 'Python code, interactive',     'snippet.defaultLanguage': '',     'status.privacyStatus': 'private'}   
PHP
 // Add a property to the resource. function addPropertyToResource(&$ref, $property, $value) {     $keys = explode(".", $property);     $is_array = false;     foreach ($keys as $key) {         // Convert a name like "snippet.tags[]" to "snippet.tags" and         // set a boolean variable to handle the value like an array.         if (substr($key, -2) == "[]") {             $key = substr($key, 0, -2);             $is_array = true;         }         $ref = &$ref[$key];     }      // Set the property value. Make sure array values are handled properly.     if ($is_array && $value) {         $ref = $value;         $ref = explode(",", $value);     } elseif ($is_array) {         $ref = array();     } else {         $ref = $value;     } }  // Build a resource based on a list of properties given as key-value pairs. function createResource($properties) {     $resource = array();     foreach ($properties as $prop => $value) {         if ($value) {             addPropertyToResource($resource, $prop, $value);         }     }     return $resource; }  $propertyObject = createResource(array(     'snippet.title' => 'Sample playlist ',     'snippet.description' => 'This is a sample playlist description.',     'snippet.tags[]' => 'Python code, interactive',     'snippet.defaultLanguage' => '',     'status.privacyStatus' => 'private'));
红宝石
 # Build a resource based on a list of properties given as key-value pairs. def create_resource(properties)   resource = {}   properties.each do |prop, value|     ref = resource     prop_array = prop.to_s.split(".")     for p in 0..(prop_array.size - 1)       is_array = false       key = prop_array[p]       if key[-2,2] == "[]"         key = key[0...-2]         is_array = true       end       if p == (prop_array.size - 1)         if is_array           if value == ""             ref[key.to_sym] = []           else             ref[key.to_sym] = value.split(",")           end         elsif value != ""           ref[key.to_sym] = value         end       elsif ref.include?(key.to_sym)         ref = ref[key.to_sym]       else         ref[key.to_sym] = {}         ref = ref[key.to_sym]       end     end   end   return resource end  resource = create_resource({     'snippet.title': 'Sample playlist ',     'snippet.description': 'This is a sample playlist description.',     'snippet.tags[]': 'Ruby code, interactive',     'snippet.default_language': '',     'status.privacy_status': 'private'})
Google Apps 脚本
 // Build an object from an object containing properties as key-value pairs function createResource(properties) {   var res = {};   var normalizedProps = {};   for (var p in properties) {     var value = properties[p];     if (p.substr(-2, 2) == '[]' && value) {       var adjustedName = p.replace('[]', '');       normalizedProps[adjustedName] = value.split(',');     } else {       normalizedProps[p] = value;     }   }   for (var p in normalizedProps) {     if (normalizedProps.hasOwnProperty(p) && normalizedProps[p]) {       var propArray = p.split('.');       var ref = res;       for (var pa = 0; pa < propArray.length; pa++) {         var key = propArray[pa];         if (pa == propArray.length - 1) {           ref[key] = normalizedProps[p];         } else {           ref = ref[key] = ref[key] || {};         }       }     };   }   return res; }  var resource = createResource({     'snippet.title': 'Sample playlist ',     'snippet.description': 'This is a sample playlist description.',     'snippet.tags[]': 'Apps Script code, interactive',     'snippet.defaultLanguage': '',     'status.privacyStatus': 'private' });
执行
 func addPropertyToResource(ref map[string]interface{}, keys []string, value string, count int) map[string]interface{} {         for k := count; k < (len(keys) - 1); k++ {                 switch val := ref[keys[k]].(type) {                 case map[string]interface{}:                         ref[keys[k]] = addPropertyToResource(val, keys, value, (k + 1))                 case nil:                         next := make(map[string]interface{})                         ref[keys[k]] = addPropertyToResource(next, keys, value, (k + 1))                 }         }         // Only include properties that have values.         if (count == len(keys) - 1 && value != "") {                 valueKey := keys[len(keys)-1]                 if valueKey[len(valueKey)-2:] == "[]" {                         ref[valueKey[0:len(valueKey)-2]] = strings.Split(value, ",")                 } else if len(valueKey) > 4 && valueKey[len(valueKey)-4:] == "|int" {                         ref[valueKey[0:len(valueKey)-4]], _ = strconv.Atoi(value)                 } else if value == "true" {                         ref[valueKey] = true                 } else if value == "false" {                         ref[valueKey] = false                 } else {                         ref[valueKey] = value                 }         }         return ref }  func createResource(properties map[string]string) string {         resource := make(map[string]interface{})         for key, value := range properties {                 keys := strings.Split(key, ".")                 ref := addPropertyToResource(resource, keys, value, 0)                 resource = ref         }         propJson, err := json.Marshal(resource)         if err != nil {                log.Fatal("cannot encode to JSON ", err)         }         return string(propJson) }  func main() {         properties := (map[string]string{                  "snippet.title": "Sample playlist ",                  "snippet.description": "This is a sample playlist description.",                  "snippet.tags[]": "Go code, interactive",                  "snippet.defaultLanguage": "",                  "status.privacyStatus": "private",         })         res := createResource(properties)

加载现有资源

要测试更新现有资源的请求,您可以将该资源的当前属性值加载到更新表单中。例如,如需更新某个视频的元数据,请在 id 属性字段中输入视频 ID,然后点击 Load resource 按钮。当前属性值会加载到表单中,您可以只更新要更改的值。