Data API 代码段

操作说明

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

执行 API 请求

点击请求参数列表旁边的执行按钮,即可执行请求。如果您之前没有授权应用代表您提交 API 请求,系统会提示您执行此操作。作为额外的预防措施,如果您的请求执行写入操作(插入、更新或删除与您的频道关联的资源),系统会要求您在实际执行之前确认您希望执行该请求。

切换代码段和完整示例

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

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

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

完整的代码示例旨在在本地复制和运行。请注意运行先进代码示例的前提条件,并设置相关步骤:

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 网站,了解写入数据的请求(例如创建播放列表或频道版块的请求)的影响。

JavaScript
  1. API 控制台中创建项目,并为 Web 应用设置凭据。设置已获授权的 JavaScript 来源,以指定您用于发送请求的网址(例如 http://localhost)。

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

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

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

  5. 如有必要,请对请求进行授权。如果请求已获得授权,调试控制台应将 JSON 响应作为 JSON 对象显示。

Node.js

前提条件

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

设置项目并运行代码示例

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

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

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

  4. 从命令行运行示例:

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

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

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 凭据。设置凭据时,将应用类型设置为 Other

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

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

  4. 从命令行运行示例:

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

Ruby

前提条件

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

设置项目并运行代码示例

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

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

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

  4. 从命令行运行示例:

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

开始
  1. API 控制台中创建项目,然后在 Google API 控制台中设置 OAuth 2.0 凭据。设置凭据时,将应用类型设置为 Other

  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 脚本提供了类似的函数。

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

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'));
Ruby
# 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'})
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,然后点击加载资源按钮。当前的属性值会加载到表单中,您可以只更新要更改的值。