채널의 메타데이터를 업데이트합니다. 이 메소드는 현재 channel
리소스의 brandingSettings
및 invideoPromotion
개체와 해당 하위 속성의 업데이트만 지원합니다.
지금 사용해 보거나 예를 참조하세요.
요청
HTTP 요청
PUT https://www.googleapis.com/youtube/v3/channels
인증
이 요청에는 다음 범위 중 최소 하나를 사용하여 인증이 필요합니다. (인증 및 승인에 대해 자세히 알아보기)
범위 |
---|
https://www.googleapis.com/auth/youtubepartner |
https://www.googleapis.com/auth/youtube |
매개변수
아래 표는 이 쿼리가 지원하는 매개변수 목록입니다. 나열된 모든 매개변수는 쿼리 매개변수입니다.
매개변수 이름 | ||
---|---|---|
필수 매개변수 | ||
part |
string part 매개변수는 이 연산에서 2가지 용도로 사용됩니다. 쓰기 연산에서 설정하는 속성과 API 응답에서 포함하는 속성을 확인합니다.현재 API는 매개변수 값에 id 및 invideoPromotion 부분만 포함하도록 허용합니다.이 메소드는 매개변수 값이 지정한 부분에 있는 변경이 용이한 모든 속성의 기존 값을 오버라이드하는 점에 유의합니다. |
|
선택적 매개변수 | ||
onBehalfOfContentOwner |
string 이 매개변수는 제대로 인증된 요청에서만 사용할 수 있습니다. onBehalfOfContentOwner 매개변수는 인증된 사용자가 매개변수 값에 지정된 콘텐츠 소유자를 대신함을 나타냅니다. 이 매개변수는 다양한 여러 YouTube 채널을 소유하고 관리하는 YouTube 콘텐츠 파트너 전용입니다. 이 매개변수로 콘텐츠 소유자는 각 개별 채널에 승인 사용자 인증 정보를 제공할 필요 없이 한 번 인증하여 모든 동영상 및 채널 데이터에 액세스할 수 있습니다. 사용자가 인증할 실제 CMS 계정은 지정된 YouTube 콘텐츠 소유자에게 연결되어야 합니다. |
요청 본문
요청 본문에 channel 리소스를 제공합니다. 이 리소스의 경우
-
다음 속성에 값을 지정해야 합니다.
id
-
다음 속성에 값을 설정할 수 있습니다.
invideoPromotion.position.type
invideoPromotion.position.cornerPosition
brandingSettings.image.bannerExternalUrl
invideoPromotion.defaultTiming.type
invideoPromotion.defaultTiming.offsetMs
invideoPromotion.items[].id.type
invideoPromotion.items[].id.videoId
invideoPromotion.items[].timing.type
invideoPromotion.items[].timing.offsetMs
업데이트 요청을 제출하고, 값이 있는 속성에 요청이 값을 지정하지 않은 경우, 속성의 기존 값은 삭제됩니다.
응답
성공하는 경우 이 메소드는 응답 본문에 channel 리소스를 반환합니다.
예
참고: 아래의 코드 샘플은 지원되는 일부 프로그래밍 언어를 나타냅니다. 지원되는 언어 목록을 보려면 클라이언트 라이브러리 문서를 참조하세요.
Java
Java 클라이언트 라이브러리를 사용하는 예입니다.
-
AddFeaturedVideo.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_addfeaturedvideo_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.*; import com.google.common.collect.Lists; import java.io.File; import java.io.IOException; import java.math.BigInteger; import java.util.List; /** * This program adds a featured video to a channel via the Invideo Programming API. * * @author Ikai Lan <ikai@google.com> */ public class AddFeaturedVideo { /** * 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 IOException { // Load client secrets. GoogleClientSecrets clientSecrets = GoogleClientSecrets.load( JSON_FACTORY, AddFeaturedVideo.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-addfeaturedvideo-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-addfeaturedvideo.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 8080 LocalServerReceiver localReceiver = new LocalServerReceiver.Builder().setPort(8080).build(); // Authorize. return new AuthorizationCodeInstalledApp(flow, localReceiver).authorize("user"); } /** * This is a very simple code sample that looks up a user's channel, then features the most recently * uploaded video in the bottom left hand corner of every single video in the channel. * * @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-addfeaturedvideo-sample").build(); // Fetch the user's channel. We also fetch the uploads playlist so we can use this later // to find the most recently uploaded video ChannelListResponse channelListResponse = youtube.channels().list("id,contentDetails") .setMine(true) .setFields("items(contentDetails/relatedPlaylists/uploads,id)") .execute(); // This assumes the user has a channel already. If the user does not have a channel, this should // throw a GoogleJsonResponseException explaining the issue Channel myChannel = channelListResponse.getItems().get(0); String channelId = myChannel.getId(); String uploadsPlaylistId = myChannel.getContentDetails().getRelatedPlaylists().getUploads(); // Fetch the most recently uploaded video PlaylistItemListResponse playlistItemListResponse = youtube.playlistItems().list("snippet") .setPlaylistId(uploadsPlaylistId) .setFields("items/snippet") .execute(); String featuredVideoId; if (playlistItemListResponse.getItems().isEmpty()) { // There are no videos on the channel. Therefore, we cannot feature a video. Exit. System.out.println("Channel contains no videos. Featuring a default video instead from the Google Developers channel."); featuredVideoId = "w4eiUiauo2w"; } else { // The latest video should be the first video in the playlist response PlaylistItem featuredVideo = playlistItemListResponse.getItems().get(0); featuredVideoId = featuredVideo.getSnippet() .getResourceId() .getVideoId(); System.out.println("Featuring video: " + featuredVideo.getSnippet().getTitle()); } // Feature this video on the channel via the Invideo programming API // This describes the position of the video. Valid positions are bottomLeft, bottomRight, topLeft and // topRight InvideoPosition invideoPosition = new InvideoPosition(); invideoPosition.setCornerPosition("bottomLeft"); invideoPosition.setType("corner"); // The allowed offsets are offsetFromEnd and offsetFromStart, with offsetMs being an offset in milliseconds InvideoTiming invideoTiming = new InvideoTiming(); invideoTiming.setOffsetMs(BigInteger.valueOf(15000l)); invideoTiming.setType("offsetFromEnd"); // Represents the type of promotion. In this case, a video with a video ID PromotedItemId promotedItemId = new PromotedItemId(); promotedItemId.setType("video"); promotedItemId.setVideoId(featuredVideoId); // Construct the Invidideo promotion InvideoPromotion invideoPromotion = new InvideoPromotion(); invideoPromotion.setPosition(invideoPosition); invideoPromotion.setTiming(invideoTiming); invideoPromotion.setItems(Lists.newArrayList(promotedItemId)); // Now let's add the invideo promotion to the channel Channel channel = new Channel(); channel.setId(channelId); channel.setInvideoPromotion(invideoPromotion); // Make the API call Channel updateChannelResponse = youtube.channels() .update("invideoPromotion", channel) .execute(); // Print out returned results. System.out.println("\n================== Updated Channel Information ==================\n"); System.out.println("\t- Channel ID: " + updateChannelResponse.getId()); InvideoPromotion promotion = updateChannelResponse.getInvideoPromotion(); System.out.println("\t- Invideo promotion video ID: " + promotion.getItems() .get(0) .getVideoId()); System.out.println("\t- Promotion position: " + promotion.getPosition().getCornerPosition()); System.out.println("\t- Promotion timing: " + promotion.getTiming().getOffsetMs() + " Offset: " + promotion.getTiming().getType()); } 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(); } } }
-
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-addfeaturedvideo-sample</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>youtube-cmdline-addfeaturedvideo-sample</name> <url>http://maven.apache.org</url> <properties> <project.youtube.version>v3-rev56-1.15.0-rc</project.youtube.version> <project.http.version>1.15.0-rc</project.http.version> <project.oauth.version>1.15.0-rc</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> <dependency> <groupId>com.google.collections</groupId> <artifactId>google-collections</artifactId> <version>1.0</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_addfeaturedvideo_sample.AddFeaturedVideo</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" } }
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.cloud.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 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.cloud.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)) # This OAuth 2.0 access scope allows for full read/write access to the # authenticated user's account. YOUTUBE_SCOPE = "https://www.googleapis.com/auth/youtube" YOUTUBE_API_SERVICE_NAME = "youtube" YOUTUBE_API_VERSION = "v3" # If offsetMs is not valid, the API will throw an error VALID_OFFSET_TYPES = ("offsetFromEnd", "offsetFromStart",) def get_authenticated_service(args): flow = flow_from_clientsecrets(CLIENT_SECRETS_FILE, scope=YOUTUBE_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 add_featured_video(youtube, options): add_video_request = youtube.channels().update( part="invideoPromotion", # You can use the API Explorer to test API requests: # https://developers.google.com/youtube/v3/docs/channels/update#try-it body={ "invideoPromotion": { "items": [{ "id": { "type": "video", "videoId": options.video_id }, "timing": { "offsetMs": options.offset_ms, "type": options.offset_type } }], }, "id": options.channel_id }).execute() if __name__ == '__main__': argparser.add_argument("--channel-id", required=True, help="Channel ID of the channel to add a featured video") argparser.add_argument("--video-id", required=True, help="Video ID to feature on your channel") argparser.add_argument("--offset-ms", help="Offset in milliseconds to show video.", default="10000") argparser.add_argument("--offset-type", choices=VALID_OFFSET_TYPES, help="Whether the offset is from the beginning or end of video playback.", default=VALID_OFFSET_TYPES[0]) args = argparser.parse_args() youtube = get_authenticated_service(args) try: add_featured_video(youtube, args) except HttpError, e: print "An HTTP error %d occurred:\n%s" % (e.resp.status, e.content) else: print "Added featured video %s to channel %s." % ( args.video_id, args.channel_id)
오류
아래 표에서는 이 메소드에 대한 호출에 응답하기 위해 API가 반환할 수 있는 오류 메시지를 식별합니다. 자세한 내용은 오류 메시지 설명서를 참조하세요.
오류 유형 | 오류 세부정보 | 설명 |
---|---|---|
badRequest |
brandingValidationError |
brandingSettings 개체의 값 중 하나를 확인하지 못했습니다. channels.list 메소드를 사용해 채널의 기존 설정을 검색하고 channels 리소스 문서의 안내에 따라 속성 값을 업데이트하세요. |
badRequest |
invalidBrandingOption |
지정된 브랜드 설정 중 하나가 존재하지 않습니다. channels.list 메소드를 사용해 유효한 값을 검색하고 channels 리소스 문서의 안내에 따라 이 값을 업데이트하세요. |
badRequest |
invalidCornerPosition |
요청 메타데이터가 프로모션 항목이 표시될 위치를 확인하기 위해 지정한 코너 위치가 잘못되었습니다. 요청이 보낸 리소스에서 invideoPromotion.position.cornerPosition 속성 값을 확인하세요. |
badRequest |
invalidItemType |
요청 메타데이터가 invideoPromotion 부분에 잘못된 항목 유형을 지정합습니다 요청이 보낸 리소스에서 invideoPromotion.items[].type 속성 값을 확인하세요. |
badRequest |
invalidPositionOffset |
요청 메타데이터가 프로모션 항목을 동영상 플레이어에 배치하는 방법을 결정하기 위해 지정한 위치 유형이 잘못되었습니다. 요청이 보낸 리소스에서 invideoPromotion.position.type 속성 값을 확인하세요. |
badRequest |
invalidTimingOffset |
요청 메타데이터가 프로모션 항목을 동영상 플레이어에 표시할 시기를 결정하기 위해 지정한 타이밍 오프셋이 잘못되었습니다. 요청이 보낸 리소스에서 invideoPromotion.timing.offsetMs 속성 값을 확인하세요. |
badRequest |
invalidTimingType |
요청 메타데이터가 프로모션 항목을 동영상 플레이어에 표시할 시기를 결정하기 위해 지정한 타이밍 메소드가 잘못되었습니다. 요청이 보낸 리소스에서 invideoPromotion.timing.type 속성 값을 확인하세요. |
forbidden |
channelForbidden |
id 매개변수에 지정된 채널이 요청을 지원하지 않거나 요청이 제대로 인증되지 않았습니다. |
notFound |
channelNotFound |
id .매개변수로 식별된 채널을 찾을 수 없거나 브랜드 옵션이 없습니다. |
notFound |
unknownChannelId |
API 요청이 업데이트하려는 채널을 찾을 수 없습니다. 채널 ID가 정확한지 확인하기 위해 요청이 보낸 channel 리소스에서 id 속성 값을 확인하세요. |
notFound |
unknownVideoId |
프로모션 항목으로 지정한 동영상 ID를 찾을 수 없습니다. |
required |
requiredCornerPosition |
요청 메타데이터는 YouTube가 플레이어에서 프로모션 항목을 표시할 위치를 결정할 수 있도록 코너 위치를 지정해야 합니다. 요청이 보내는 리소스에서 invideoPromotion.position.cornerPosition 속성 값을 설정하세요. |
required |
requiredItemType |
요청 메타데이터가 프로모션 항목의 유형을 지정해야 합니다. 요청이 보내는 리소스에서 invideoPromotion.items[].type 속성 값을 설정하세요. |
required |
requiredPositionOffset |
YouTube가 프로모션 항목을 표시할 방법을 결정할 수 있도록 요청 메타데이터가 위치 유형을 지정해야 합니다. 요청이 보내는 리소스에서 invideoPromotion.position.type 속성 값을 설정하세요. |
required |
requiredTimingOffset |
YouTube가 프로모션 항목을 표시할 시간을 결정할 수 있도록 요청 메타데이터가 타이밍 오프셋을 지정해야 합니다. 요청이 보내는 리소스에서 invideoPromotion.timing.offsetMs 속성 값을 설정하세요. |
required |
requiredTimingType |
YouTube가 프로모션 항목을 표시할 시간을 결정할 수 있도록 요청 메타데이터가 타이밍 메소드를 지정해야 합니다. 요청이 보내는 리소스에서 invideoPromotion.timing.type 속성 값을 설정하세요. |
required |
requiredVideoId |
프로모션 항목을 구분하기 위해 요청 메타데이터가 동영상 ID를 지정해야 합니다. |
직접 사용해 보세요!
API Explorer를 사용하여 실시간 데이터에서 이 메소드를 호출하고 API 요청 및 응답을 확인해 보세요.