Videos: update

동영상의 메타데이터를 업데이트합니다. 지금 사용해 보거나 예를 참조하세요.

요청

HTTP 요청

PUT https://www.googleapis.com/youtube/v3/videos

인증

이 요청에는 다음 범위 중 최소 하나를 사용하여 인증이 필요합니다. (인증 및 승인에 대해 자세히 알아보기)

범위
https://www.googleapis.com/auth/youtubepartner
https://www.googleapis.com/auth/youtube

매개변수

아래 표는 이 쿼리가 지원하는 매개변수 목록입니다. 나열된 모든 매개변수는 쿼리 매개변수입니다.

매개변수 이름
필수 매개변수
part string
part 매개변수는 이 연산에서 2가지 용도로 사용됩니다. 쓰기 연산에서 설정하는 속성과 API 응답에서 포함하는 속성을 식별합니다.

매개변수 값에 포함할 수 있는 part 이름은 snippet, contentDetails, fileDetails, player, processingDetails, recordingDetails, statistics, status, suggestions, topicDetails입니다.

이 메소드는 매개변수 값이 지정한 부분에 있는 변경이 용이한 모든 속성의 기존 값을 오버라이드하는 점에 유의합니다. 예를 들어 동영상의 개인정보 보호 설정은 status 부분에 포함되어 있습니다. 따라서 요청이 비공개 동영상을 업데이트하고 요청의 part 매개변수 값이 status 부분을 포함하는 경우, 동영상의 개인정보 보호 설정은 요청 본문이 지정한 값으로 업데이트됩니다. 요청 본문이 값을 지정하지 않은 경우, 기존 개인정보 보호 설정이 삭제되고 동영상은 기본 개인정보 보호 설정으로 되돌아갑니다.

또한 일부에는 동영상의 메타데이터를 설정하거나 업데이트할 때 설정할 수 있는 속성이 없습니다. 예를 들어 statistics 개체는 YouTube가 동영상에 대해 계산하는 통계를 요약하지만, 설정하거나 수정할 값을 포함하지 않습니다. 매개변수 값이 변경이 용이한 값을 포함하지 않는 part를 지정하는 경우 part는 API 응답에 여전히 포함됩니다.
선택적 매개변수
onBehalfOfContentOwner string
이 매개변수는 제대로 인증된 요청에서만 사용할 수 있습니다. 참고: 이 매개변수는 YouTube 콘텐츠 파트너 전용입니다.

onBehalfOfContentOwner 매개변수는 요청의 승인 사용자 인증 정보가 매개변수 값에 지정된 콘텐츠 소유자를 대신하는 YouTube CMS 사용자를 확인함을 나타냅니다. 이 매개변수는 다양한 여러 YouTube 채널을 소유하고 관리하는 YouTube 콘텐츠 파트너 전용입니다. 이 매개변수로 콘텐츠 소유자는 각 개별 채널에 승인 사용자 인증 정보를 제공할 필요 없이 한 번 인증하여 모든 동영상 및 채널 데이터에 액세스할 수 있습니다. 사용자가 인증할 실제 CMS 계정은 지정된 YouTube 콘텐츠 소유자에게 연결되어야 합니다.

요청 본문

요청 본문에 video 리소스를 제공합니다. 이 리소스의 경우

  • 다음 속성에 값을 지정해야 합니다.

    • id

  • 다음 속성에 값을 설정할 수 있습니다.

    • snippet.title
    • snippet.description
    • snippet.tags[]
    • snippet.categoryId
    • status.privacyStatus
    • status.embeddable
    • status.license
    • status.publicStatsViewable

    업데이트 요청을 제출하는데 값이 있는 속성에 요청이 값을 지정하지 않은 경우 속성의 기존 값은 삭제됩니다.

응답

성공하는 경우 이 메소드는 응답 본문에 video 리소스를 반환합니다.

참고: 아래의 코드 샘플은 지원되는 일부 프로그래밍 언어를 나타냅니다. 지원되는 언어 목록을 보려면 클라이언트 라이브러리 문서를 참조하세요.

Java

Java 클라이언트 라이브러리를 사용하는 예입니다.

  • UpdateVideo.java

    /*
     * Copyright (c) 2013 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.youtube_cmdline_updatevideo_sample;
    
    import com.google.api.client.auth.oauth2.Credential;
    import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
    import com.google.api.client.extensions.java6.auth.oauth2.FileCredentialStore;
    import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
    import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
    import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
    import com.google.api.client.googleapis.json.GoogleJsonResponseException;
    import com.google.api.client.http.HttpTransport;
    import com.google.api.client.http.javanet.NetHttpTransport;
    import com.google.api.client.json.JsonFactory;
    import com.google.api.client.json.jackson2.JacksonFactory;
    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.VideoSnippet;
    import com.google.common.collect.Lists;
    
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.util.ArrayList;
    import java.util.List;
    
    /**
     * Demo of updating a video by adding a tag, using the YouTube Data API (V3) with OAuth2 for
     * authorization.
     *
     * @author Ibrahim Ulukaya
     */
    public class UpdateVideo {
    
      /** Global instance of the HTTP transport. */
      private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
    
      /** Global instance of the JSON factory. */
      private static final JsonFactory JSON_FACTORY = new JacksonFactory();
    
      /** Global instance of YouTube object to make all API requests. */
      private static YouTube youtube;
    
      /**
       * Authorizes the installed application to access user's protected data.
       *
       * @param scopes list of scopes needed to run YouTube upload.
       */
      private static Credential authorize(List<String> scopes) throws Exception {
    
        // Load client secrets.
        GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(
            JSON_FACTORY, UpdateVideo.class.getResourceAsStream("/client_secrets.json"));
    
        // Checks that the defaults have been replaced (Default = "Enter X here").
        if (clientSecrets.getDetails().getClientId().startsWith("Enter")
            || clientSecrets.getDetails().getClientSecret().startsWith("Enter ")) {
          System.out.println(
              "Enter Client ID and Secret from https://console.developers.google.com/project/_/apiui/credential"
              + "into youtube-cmdline-updatevideo-sample/src/main/resources/client_secrets.json");
          System.exit(1);
        }
    
        // Set up file credential store.
        FileCredentialStore credentialStore = new FileCredentialStore(
            new File(System.getProperty("user.home"), ".credentials/youtube-api-updatevideo.json"),
            JSON_FACTORY);
    
        // Set up authorization code flow.
        GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
            HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, scopes).setCredentialStore(credentialStore)
            .build();
    
        // Build the local server and bind it to port 9000
        LocalServerReceiver localReceiver = new LocalServerReceiver.Builder().setPort(8080).build();
    
        // Authorize.
        return new AuthorizationCodeInstalledApp(flow, localReceiver).authorize("user");
      }
    
      /**
       * Uploads user selected video in the project folder to the user's YouTube account using OAuth2
       * for authentication.
       *
       * @param args command line args (not used).
       */
      public static void main(String[] args) {
    
        // An OAuth 2 access scope that allows for full read/write access.
        List<String> scopes = Lists.newArrayList("https://www.googleapis.com/auth/youtube");
    
        try {
          // Authorization.
          Credential credential = authorize(scopes);
    
          // YouTube object used to make all API requests.
          youtube = new YouTube.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential).setApplicationName(
              "youtube-cmdline-updatevideo-sample").build();
    
          // Get the user selected video Id.
          String videoId = getVideoIdFromUser();
          System.out.println("You chose " + videoId + " to update.");
    
          // Get the user selected tag for video.
          String tag = getTagFromUser();
          System.out.println("You chose " + tag + " as a tag.");
    
          // Create the video list request
          YouTube.Videos.List listVideosRequest = youtube.videos().list(videoId, "snippet");
    
          // Request is executed and video list response is returned
          VideoListResponse listResponse = listVideosRequest.execute();
    
          List<Video> videoList = listResponse.getItems();
          if (videoList.isEmpty()) {
            System.out.println("Can't find a video with video id: " + videoId);
            return;
          }
    
          // Since a unique video id is given, it will only return 1 video.
          Video video = videoList.get(0);
          VideoSnippet snippet = video.getSnippet();
    
          List<String> tags = snippet.getTags();
    
          // getTags() returns null if the video didn't have any tags, so we will check for this and
          // create a new list if needed
          if (tags == null) {
            tags = new ArrayList<String>(1);
            snippet.setTags(tags);
          }
          tags.add(tag);
    
          // Create the video update request
          YouTube.Videos.Update updateVideosRequest = youtube.videos().update("snippet", video);
    
          // Request is executed and updated video is returned
          Video videoResponse = updateVideosRequest.execute();
    
          // Print out returned results.
          System.out.println("\n================== Returned Video ==================\n");
          System.out.println("  - Title: " + videoResponse.getSnippet().getTitle());
          System.out.println("  - Tags: " + videoResponse.getSnippet().getTags());
    
        } 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();
        }
      }
    
      /*
       * Prompts for a tag from standard input and returns it.
       */
      private static String getTagFromUser() throws IOException {
    
        String title = "";
    
        System.out.print("Please enter a tag for your video: ");
        BufferedReader bReader = new BufferedReader(new InputStreamReader(System.in));
        title = bReader.readLine();
    
        if (title.length() < 1) {
          // If nothing is entered, defaults to "New Tag"
          title = "New Tag";
        }
        return title;
      }
    
      /*
       * Prompts for a video ID from standard input and returns it.
       */
      private static String getVideoIdFromUser() throws IOException {
    
        String title = "";
    
        System.out.print("Please enter a video Id to update: ");
        BufferedReader bReader = new BufferedReader(new InputStreamReader(System.in));
        title = bReader.readLine();
    
        if (title.length() < 1) {
          // If nothing is entered, exits
          System.out.print("Video Id can't be empty!");
          System.exit(1);
        }
    
        return title;
      }
    
    }
    
  • pom.xml

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
      <modelVersion>4.0.0</modelVersion>
    
      <groupId>com.google.api.services.samples.youtube.cmdline</groupId>
      <artifactId>youtube-cmdline-updatevideo-sample</artifactId>
      <version>0.0.1-SNAPSHOT</version>
      <packaging>jar</packaging>
    
      <name>youtube-cmdline-updatevideo-sample</name>
      <url>http://maven.apache.org</url>
    
      <properties>
        <project.youtube.version>v3-rev24-1.13.2-beta</project.youtube.version>
        <project.http.version>1.13.1-beta</project.http.version>
        <project.oauth.version>1.13.1-beta</project.oauth.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      </properties>
    
      <repositories>
        <repository>
          <id>google-api-services</id>
          <url>http://google-api-client-libraries.appspot.com/mavenrepo</url>
        </repository>
      </repositories>
    
      <dependencies>
    
        <!-- YouTube Data V3 support -->
        <dependency>
          <groupId>com.google.apis</groupId>
          <artifactId>google-api-services-youtube</artifactId>
          <version>${project.youtube.version}</version>
        </dependency>
    
        <dependency>
          <groupId>com.google.http-client</groupId>
          <artifactId>google-http-client-jackson2</artifactId>
          <version>${project.http.version}</version>
        </dependency>
        <dependency>
          <groupId>com.google.oauth-client</groupId>
          <artifactId>google-oauth-client-jetty</artifactId>
          <version>${project.oauth.version}</version>
        </dependency>
      </dependencies>
    
      <build>
        <plugins>
          <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>exec-maven-plugin</artifactId>
            <version>1.2.1</version>
            <configuration>
              <mainClass>com.google.api.services.samples.youtube.cmdline.youtube_cmdline_updatevideo_sample.UpdateVideo</mainClass>
            </configuration>
          </plugin>
    
          <!-- Forces Maven to use Java 1.6 -->
          <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>2.3.2</version>
            <configuration>
              <source>1.6</source>
              <target>1.6</target>
              <compilerArgument></compilerArgument>
            </configuration>
          </plugin>
        </plugins>
      </build>
    </project>
    
  • client_secrets.json

    {
      "installed": {
        "client_id": "Enter Client ID",
        "client_secret": "Enter Client Secret"
      }
    }
    
    

PHP

PHP 클라이언트 라이브러리를 사용하는 예입니다.

<?php

/**
 * This sample adds new tags to a YouTube video by:
 *
 * 1. Retrieving the video resource by calling the "youtube.videos.list" method
 *    and setting the "id" parameter
 * 2. Appending new tags to the video resource's snippet.tags[] list
 * 3. Updating the video resource by calling the youtube.videos.update method.
 *
 * @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();

/*
 * You can acquire an OAuth 2.0 client ID and client secret from the
 * Google API Console <https://console.developers.google.com/>
 * 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);
$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()) {
  $htmlBody = '';
  try{

    // REPLACE this value with the video ID of the video being updated.
    $videoId = "VIDEO_ID";

    // Call the API's videos.list method to retrieve the video resource.
    $listResponse = $youtube->videos->listVideos("snippet",
        array('id' => $videoId));

    // If $listResponse is empty, the specified video was not found.
    if (empty($listResponse)) {
      $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.
      $video = $listResponse[0];
      $videoSnippet = $video['snippet'];
      $tags = $videoSnippet['tags'];

      // Preserve any tags already associated with the video. If the video does
      // not have any tags, create a new list. Replace the values "tag1" and
      // "tag2" with the new tags you want to associate with the video.
      if (is_null($tags)) {
        $tags = array("tag1", "tag2");
      } else {
        array_push($tags, "tag1", "tag2");
      }

      // Set the tags array for the video snippet
      $videoSnippet['tags'] = $tags;

      // Update the video resource by calling the videos.update() method.
      $updateResponse = $youtube->videos->update("snippet", $video);

      $responseTags = $updateResponse['snippet']['tags'];

      $htmlBody .= "<h3>Video Updated</h3><ul>";
      $htmlBody .= sprintf('<li>Tags "%s" and "%s" added for video %s (%s) </li>',
          array_pop($responseTags), array_pop($responseTags),
          $videoId, $video['snippet']['title']);

      $htmlBody .= '</ul>';
    }
  } 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;
}
?>

<!doctype html>
<html>
<head>
<title>Video Updated</title>
</head>
<body>
  <?=$htmlBody?>
</body>
</html>

Python

Python 클라이언트 라이브러리를 사용하는 예입니다.

#!/usr/bin/python

import httplib2
import os
import sys

from apiclient.discovery import build
from apiclient.errors import HttpError
from oauth2client.client import flow_from_clientsecrets
from oauth2client.file import Storage
from oauth2client.tools import argparser, run_flow


# 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 API Console at
# https://console.developers.google.com/.
# 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_secrets.json"

# This OAuth 2.0 access scope allows for full read/write access to the
# authenticated user's account.
YOUTUBE_READ_WRITE_SCOPE = "https://www.googleapis.com/auth/youtube"
YOUTUBE_API_SERVICE_NAME = "youtube"
YOUTUBE_API_VERSION = "v3"

# This variable defines a message to display if the CLIENT_SECRETS_FILE is
# missing.
MISSING_CLIENT_SECRETS_MESSAGE = """
WARNING: Please configure OAuth 2.0

To make this sample run you will need to populate the client_secrets.json file
found at:

   %s

with information from the API Console
https://console.developers.google.com/

For more information about the client_secrets.json file format, please visit:
https://developers.google.com/api-client-library/python/guide/aaa_client_secrets
""" % os.path.abspath(os.path.join(os.path.dirname(__file__),
                                   CLIENT_SECRETS_FILE))

def get_authenticated_service(args):
  flow = flow_from_clientsecrets(CLIENT_SECRETS_FILE,
    scope=YOUTUBE_READ_WRITE_SCOPE,
    message=MISSING_CLIENT_SECRETS_MESSAGE)

  storage = Storage("%s-oauth2.json" % sys.argv[0])
  credentials = storage.get()

  if credentials is None or credentials.invalid:
    credentials = run_flow(flow, storage, args)

  return build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION,
    http=credentials.authorize(httplib2.Http()))

def update_video(youtube, options):
  # Call the API's videos.list method to retrieve the video resource.
  videos_list_response = youtube.videos().list(
    id=options.video_id,
    part='snippet'
  ).execute()

  # If the response does not contain an array of "items" then the video was
  # not found.
  if not videos_list_response["items"]:
    print "Video '%s' was not found." % options.video_id
    sys.exit(1)

  # Since the request specified a video ID, the response only contains one
  # video resource. This code extracts the snippet from that resource.
  videos_list_snippet = videos_list_response["items"][0]["snippet"]

  # Preserve any tags already associated with the video. If the video does
  # not have any tags, create a new array. Append the provided tag to the
  # list of tags associated with the video.
  if "tags" not in  videos_list_snippet:
    videos_list_snippet["tags"] = []
  videos_list_snippet["tags"].append(options.tag)

  # Update the video resource by calling the videos.update() method.
  videos_update_response = youtube.videos().update(
    part='snippet',
    body=dict(
      snippet=videos_list_snippet,
      id=options.video_id
    )).execute()

if __name__ == "__main__":
  argparser.add_argument("--video-id", help="ID of video to update.",
    required=True)
  argparser.add_argument("--tag", default="youtube",
    help="Additional tag to add to video.")
  args = argparser.parse_args()

  youtube = get_authenticated_service(args)
  try:
    update_video(youtube, args)
  except HttpError, e:
    print "An HTTP error %d occurred:\n%s" % (e.resp.status, e.content)
  else:
    print "Tag '%s' was added to video id '%s'." % (args.tag, args.video_id)

오류

아래 표에서는 이 메소드에 대한 호출에 응답하기 위해 API가 반환할 수 있는 오류 메시지를 식별합니다. 자세한 내용은 오류 메시지 설명서를 참조하세요.

오류 유형 오류 세부정보 설명
badRequest invalidRequest 요청 메타데이터가 잘못되었습니다.
forbidden forbidden
forbidden forbiddenLicenseSetting 요청이 동영상에 잘못된 라이선스를 설정하려고 합니다.
forbidden forbiddenPrivacySetting 요청이 동영상에 대해 잘못된 개인정보 보호 설정을 지정하려고 합니다.
notFound videoNotFound 업뎅하려는 동영상을 찾을 수 없습니다. 요청 본문에 있는 id 필드 값이 올바른지 확인하세요.

직접 사용해 보세요!

API Explorer를 사용하여 실시간 데이터에서 이 메소드를 호출하고 API 요청 및 응답을 확인해 보세요.