Data API 程式碼片段

操作說明

透過互動式程式碼片段工具,您可以輕鬆測試 API 要求,並產生這些要求專屬的程式碼範例。工具會針對任何指定用途,顯示一或多個使用案例的程式碼片段,而每個用途都有說明呼叫該方法的常見方式。舉例來說,您可以呼叫 channels.list 方法,擷取特定頻道或目前使用者頻道的相關資料。

執行 API 要求

若要執行請求,請按一下要求參數清單旁的 [執行] 按鈕。如果您尚未授權應用程式代您提交 API 要求,系統會提示您這麼做。為避免這種情況,您必須執行寫入作業 (插入、更新或刪除與頻道相關聯的資源) 時,系統會要求您確認要在執行該要求之前執行該要求。

切換程式碼片段和完整範例

針對每種用途,此工具會顯示一個程式碼片段,用於識別所呼叫的特定方法專屬的程式碼。每個程式碼片段都會識別所呼叫的方法,以及 API 要求中使用的參數和屬性值。

另外,此工具也會顯示完整的程式碼片段,將這個程式碼片段放入範本中,用於定義授權 API 要求及建構 API 要求的樣板函式。您可以使用樣本上方的滑桿,在程式碼片段和完整樣本之間切換:

在本機執行完整程式碼範例

完整程式碼範例可複製並在本機執行。請留意以下先決條件,並設定執行完整程式碼範例的步驟:

Java

必要條件

  • Java 1.7 以上版本
  • Gradle 2.3 以上版本

設定專案並執行程式碼範例

  1. API 控制台中建立專案,並設定網路應用程式的憑證。視情況設定已獲授權的重新導向 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 控制台中建立專案,並設定網路應用程式的憑證。設定已授權的 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. 視需要授權要求。如果要求已取得授權,偵錯控制台應將請求的 API 回應顯示為 JSON 物件。

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,如果是網路應用程式範例,則會列印至您正在檢視的網頁。你也可以前往 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 網路應用程式架構 (如果您針對網路伺服器應用程式執行 Python 範例,則需使用)。
    pip install --upgrade flask
  • 要求 HTTP 程式庫。
    pip install --upgrade requests

設定專案並執行程式碼範例

  1. API 控制台中建立專案,然後在 Google API 控制台中設定 OAuth 2.0 憑證。設定憑證時,請將應用程式類型設為 [網路應用程式],以使用 Flask Python 網路應用程式架構的範例,並為這些憑證設定已獲授權的重新導向 URI。否則,請將應用程式類型設為「Other」

  2. 將與憑證相關聯的 client_secret.json 檔案儲存至本機檔案。

  3. 將完整程式碼範例複製到與 client_secret.json 檔案相同的目錄中的本機檔案 (或是修改範例以正確識別檔案位置)。

  4. 透過指令列執行範例:

    python sample.py
    網路伺服器應用程式註意事項:

    如果您是為網路伺服器應用程式執行 Python 範例,則執行指令碼會啟動本機網路伺服器。如要實際執行 API 要求,您必須用瀏覽器前往提供的網頁。舉例來說,使用 Flask 網路應用程式架構的 Python 範例包含以下這行程式碼:

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

    此程式碼會在 http://localhost:8080 啟動本機網路伺服器。不過,除非您實際在瀏覽器中前往 http://localhost:8080,否則指令碼不會嘗試執行 API 要求。(本機伺服器的網址也必須設為授權憑證的授權重新導向 URI)。
  5. 大部分範例會將內容列印到 STDOUT,如果是網路應用程式範例,則會列印至您正在檢視的網頁。你也可以前往 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 憑證。設定憑證時,請將應用程式類型設為 [其他]

  2. 將與憑證相關聯的 client_secret.json 檔案儲存至本機檔案。

  3. 將完整程式碼範例複製到與 client_secret.json 檔案相同的目錄中的本機檔案 (或是修改範例以正確識別檔案位置)。

  4. 透過指令列執行範例:

    php sample.php
  5. 大部分範例會將內容列印到 STDOUT,如果是網路應用程式範例,則會列印至您正在檢視的網頁。你也可以前往 YouTube 網站查看寫入要求所造成的影響,例如建立播放清單或頻道版面的要求。

Ruby

必要條件

  • 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,如果是網路應用程式範例,則會列印至您正在檢視的網頁。你也可以前往 YouTube 網站查看寫入要求所造成的影響,例如建立播放清單或頻道版面的要求。

前往
  1. API 控制台中建立專案,然後在 Google API 控制台中設定 OAuth 2.0 憑證。設定憑證時,請將應用程式類型設為 [其他]

  2. 將與憑證相關聯的 client_secret.json 檔案儲存至本機檔案。

  3. 將完整程式碼範例複製到與 client_secret.json 檔案相同的目錄中的本機檔案 (或是修改範例以正確識別檔案位置)。

  4. 透過指令列執行範例:

    go run sample.go
  5. 大部分範例會將內容列印到 STDOUT,如果是網路應用程式範例,則會列印至您正在檢視的網頁。你也可以前往 YouTube 網站查看寫入要求所造成的影響,例如建立播放清單或頻道版面的要求。

使用樣板函式

如上所述,完整程式碼範例使用樣板程式碼來授權並建構 API 要求。舉例來說,Python 範例中的 build_resource 函式會使用字典,將資源屬性對應至其值,以建立可插入或更新的資源。JavaScript、PHP、Ruby、Go 和 Apps Script 也提供了類似的函式。

舉例來說,以下分頁標籤說明瞭如何呼叫建構資源的樣板函式來建構 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 Script
// 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] (載入資源) 按鈕。目前的屬性值會載入表單,而且您可以只更新想要變更的值。