Data API 代码段

操作说明

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

执行 API 请求

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

切换代码段和完整示例

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

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

在本地运行完整代码示例

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

Java

前提条件

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

设置项目并运行代码示例

  1. 在 Cloud 控制台 中创建一个项目,并为 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. 在 Cloud 控制台 中创建一个项目,并为 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 响应。

Node.js

前提条件

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

设置项目并运行代码示例

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

  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
  • requests HTTP 库。
    pip install --upgrade requests

设置项目并运行代码示例

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

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

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

  4. 从命令行运行示例:

    python sample.py
    适用于 Web 服务器应用示例的注意事项:

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

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

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

PHP

前提条件

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

设置项目并运行代码示例

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

  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. 在 Cloud 控制台 中创建一个项目,并在 Google Cloud 控制台 中设置 OAuth 2.0 凭据。设置凭据时,请将应用类型设置为其他 。

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

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

  4. 从命令行运行示例:

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

Go
  1. 在 Cloud 控制台 中创建一个项目,并在 Google Cloud 控制台 中设置 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 脚本也提供了类似函数。

例如,下面的标签页显示了如何调用用于构建资源的样板函数来构建 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'
});
Go
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,然后点击加载资源 按钮。当前属性值会加载到表单中,您只需更新要更改的值即可。