JavaScript 코드 샘플
컬렉션을 사용해 정리하기
내 환경설정을 기준으로 콘텐츠를 저장하고 분류하세요.
아래 코드 샘플에서는 JavaScript용 Google API 클라이언트 라이브러리를 사용합니다. 이 샘플은 GitHub의 YouTube API 코드 샘플 저장소의 javascript
폴더에서 다운로드할 수 있습니다.
코드는 https://www.googleapis.com/auth/yt-analytics.readonly
범위에 액세스할 수 있는 사용자 권한을 요청합니다.
return gapi.auth2.getAuthInstance()
.signIn({scope: "https://www.googleapis.com/auth/yt-analytics.readonly"})
...
애플리케이션에서 다른 범위에 대한 액세스 권한을 요청해야 할 수도 있습니다. 예를 들어 YouTube Analytics API와 YouTube Data API를 호출하는 애플리케이션은 사용자가 YouTube 계정에 대한 액세스 권한도 부여해야 할 수 있습니다. 승인 개요에서는 YouTube 분석 API를 호출하는 애플리케이션에서 일반적으로 사용되는 범위를 식별합니다.
일일 채널 통계 가져오기
이 예에서는 YouTube 분석 API를 호출하여 승인된 사용자의 채널에 대한 2017년의 일일 조회수와 기타 측정항목을 가져옵니다. 이 샘플에서는 Google API JavaScript 클라이언트 라이브러리를 사용합니다.
승인 사용자 인증 정보 설정
이 샘플을 처음으로 로컬에서 실행하기 전에 프로젝트의 승인 사용자 인증 정보를 설정해야 합니다.
- Google API 콘솔에서 프로젝트를 만들거나 선택합니다.
- 프로젝트에서 YouTube 분석 API를 사용 설정합니다.
- 사용자 인증 정보 페이지 상단에서 OAuth 동의 화면 탭을 선택합니다. 이메일 주소를 선택하고, 아직 설정되지 않은 경우 제품 이름을 입력한 다음 저장 버튼을 클릭합니다.
- 사용자 인증 정보 페이지에서 사용자 인증 정보 만들기 버튼을 클릭하고 OAuth 클라이언트 ID를 선택합니다.
- 애플리케이션 유형으로 웹 애플리케이션을 선택합니다.
- '승인된 JavaScript 원본' 필드에 코드 샘플을 제공할 URL을 입력합니다. 예를 들어
http://localhost:8000
또는 http://yourserver.example.com
와 같은 이름을 사용할 수 있습니다. '승인된 리디렉션 URI' 필드는 비워두어도 됩니다.
- 만들기 버튼을 클릭하여 사용자 인증 정보 만들기를 마칩니다.
- 대화상자를 닫기 전에 클라이언트 ID를 복사합니다. 이 ID는 코드 샘플에 입력해야 합니다.
샘플의 로컬 사본 만들기
그런 다음 샘플을 로컬 파일에 저장합니다. 샘플에서 다음 줄을 찾아 YOUR_CLIENT_ID를 승인 사용자 인증 정보를 설정할 때 획득한 클라이언트 ID로 바꿉니다.
gapi.auth2.init({client_id: 'YOUR_CLIENT_ID'});
코드 실행
이제 샘플을 실제로 테스트할 준비가 되었습니다.
- 웹브라우저에서 로컬 파일을 열고 브라우저에서 디버깅 콘솔을 엽니다. 버튼 두 개가 표시된 페이지가 표시됩니다.
- 승인 및 로드 버튼을 클릭하여 사용자 승인 흐름을 시작합니다. 앱이 채널 데이터를 가져오도록 승인하면 브라우저의 콘솔에 다음 줄이 출력됩니다.
Sign-in successful
GAPI client loaded for API
- 위의 선 대신 오류 메시지가 표시되면 프로젝트에 설정한 승인된 리디렉션 URI에서 스크립트를 로드하고 있는지, 위의 설명대로 클라이언트 ID를 코드에 넣었는지 확인합니다.
- 실행 버튼을 클릭하여 API를 호출합니다. 브라우저의 콘솔에
response
객체가 출력됩니다. 이 객체에서 result
속성은 API 데이터가 포함된 객체에 매핑됩니다.
샘플 코드
<script src="https://apis.google.com/js/api.js"></script>
<script>
function authenticate() {
return gapi.auth2.getAuthInstance()
.signIn({scope: "https://www.googleapis.com/auth/yt-analytics.readonly"})
.then(function() { console.log("Sign-in successful"); },
function(err) { console.error("Error signing in", err); });
}
function loadClient() {
return gapi.client.load("https://youtubeanalytics.googleapis.com/$discovery/rest?version=v2")
.then(function() { console.log("GAPI client loaded for API"); },
function(err) { console.error("Error loading GAPI client for API", err); });
}
// Make sure the client is loaded and sign-in is complete before calling this method.
function execute() {
return gapi.client.youtubeAnalytics.reports.query({
"ids": "channel==MINE",
"startDate": "2017-01-01",
"endDate": "2017-12-31",
"metrics": "views,estimatedMinutesWatched,averageViewDuration,averageViewPercentage,subscribersGained",
"dimensions": "day",
"sort": "day"
})
.then(function(response) {
// Handle the results here (response.result has the parsed body).
console.log("Response", response);
},
function(err) { console.error("Execute error", err); });
}
gapi.load("client:auth2", function() {
gapi.auth2.init({client_id: 'YOUR_CLIENT_ID'});
});
</script>
<button onclick="authenticate().then(loadClient)">authorize and load</button>
<button onclick="execute()">execute</button>
달리 명시되지 않는 한 이 페이지의 콘텐츠에는 Creative Commons Attribution 4.0 라이선스에 따라 라이선스가 부여되며, 코드 샘플에는 Apache 2.0 라이선스에 따라 라이선스가 부여됩니다. 자세한 내용은 Google Developers 사이트 정책을 참조하세요. 자바는 Oracle 및/또는 Oracle 계열사의 등록 상표입니다.
최종 업데이트: 2025-08-21(UTC)
[null,null,["최종 업데이트: 2025-08-21(UTC)"],[[["\u003cp\u003eThis sample code uses the Google APIs Client Library for JavaScript to retrieve daily views and other metrics for a YouTube channel for the 2017 calendar year, utilizing the YouTube Analytics API.\u003c/p\u003e\n"],["\u003cp\u003eThe code requests user permission to access the \u003ccode\u003ehttps://www.googleapis.com/auth/yt-analytics.readonly\u003c/code\u003e scope to read YouTube Analytics data.\u003c/p\u003e\n"],["\u003cp\u003eSetting up authorization credentials in the Google API Console is required, including creating an OAuth client ID, enabling the YouTube Analytics API, and entering authorized JavaScript origins.\u003c/p\u003e\n"],["\u003cp\u003eThe sample requires replacing \u003ccode\u003e<var translate="no">YOUR_CLIENT_ID</var>\u003c/code\u003e with the client ID obtained from the Google API Console in order to run.\u003c/p\u003e\n"],["\u003cp\u003eTo run the code, users must authorize the application, load the API client, and execute the API query by clicking buttons in the browser, with successful operations and responses being logged in the browser's console.\u003c/p\u003e\n"]]],["The code uses the Google APIs Client Library for JavaScript to retrieve YouTube channel statistics. It requires user authorization for the `https://www.googleapis.com/auth/yt-analytics.readonly` scope. Users need to create authorization credentials in the Google API Console, enabling the YouTube Analytics API. The client ID must be added to the code sample, which is loaded from a specified URL. Upon running, the code allows authorization and data retrieval, displaying daily channel metrics (views, watch time, etc.) for 2017.\n"],null,["# JavaScript Code Samples\n\nThe code sample below uses the [Google APIs Client Library for JavaScript](/api-client-library/javascript). You can download this sample from the `javascript` folder of the [YouTube APIs code sample repository on GitHub](https://github.com/youtube/api-samples).\n\nThe code requests the user's permission to access the `https://www.googleapis.com/auth/yt-analytics.readonly` scope. \n\n```\nreturn gapi.auth2.getAuthInstance()\n .signIn({scope: \"https://www.googleapis.com/auth/yt-analytics.readonly\"})\n ...\n```\n\nYour application might also need to request access to other scopes. For example, an application that calls the YouTube Analytics API and the YouTube Data API might need users to also grant access to their YouTube accounts. The [authorization overview](/youtube/reporting/guides/authorization#identify-access-scopes) identifies scopes typically used in applications that call the YouTube Analytics API.\n\nRetrieve daily channel statistics\n---------------------------------\n\nThis example calls the YouTube Analytics API to retrieve daily views and other metrics for the authorizing user's channel for the 2017 calendar year. The sample uses the [Google APIs JavaScript client library](/api-client-library/javascript).\n\n### Set up authorization credentials\n\nBefore running this sample locally for the first time, you need to set up authorization credentials for your project:\n\n1. Create or select a project in the [Google API Console](https://console.cloud.google.com/).\n2. Enable the [YouTube Analytics API](https://console.developers.google.com/apis/library/youtubeanalytics.googleapis.com) for your project.\n3. At the top of the [Credentials](https://console.developers.google.com/apis/credentials) page, select the **OAuth consent screen** tab. Select an Email address, enter a Product name if not already set, and click the Save button.\n4. On the [Credentials](https://console.developers.google.com/apis/credentials) page, click the **Create credentials** button and select **Oauth client ID**.\n5. Select the application type Web application.\n6. In the Authorized JavaScript origins field, enter the URL from which you will be serving the code sample. For example, you could use something like `http://localhost:8000` or `http://yourserver.example.com`. You can leave the Authorized redirect URIs field blank.\n7. Click the **Create** button to finish creating your credentials.\n8. Before closing the dialog box, copy the client ID, which you will need to put into the code sample.\n\n### Make a local copy of the sample\n\nThen, save the sample to a local file. In the sample, find the following line and replace \u003cvar translate=\"no\"\u003eYOUR_CLIENT_ID\u003c/var\u003e with the client ID you obtained when setting up your authorization credentials. \n\n```\ngapi.auth2.init({client_id: 'YOUR_CLIENT_ID'});\n```\n\n### Run the code\n\nNow, you are ready to actually test the sample:\n\n1. Open the local file from a web browser, and open the debugging console in the browser. You should see a page that displays two buttons.\n2. Click the **authorize and load** button to launch the user authorization flow. If you authorize the app to retrieve your channel data, you should see the following lines print to the console in the browser: \n\n ```\n Sign-in successful\n GAPI client loaded for API\n ```\n3. If you see an error message instead of the lines above, confirm that you are loading the script from the authorized redirect URI that you set up for your project and that you put your client ID into the code as described above.\n4. Click the **execute** button to call the API. You should see a `response` object print to the console in the browser. In that object, the `result` property maps to an object that contains the API data.\n\n### Sample code\n\n```javascript\n\u003cscript src=\"https://apis.google.com/js/api.js\"\u003e\u003c/script\u003e\n\u003cscript\u003e\n function authenticate() {\n return gapi.auth2.getAuthInstance()\n .signIn({scope: \"https://www.googleapis.com/auth/yt-analytics.readonly\"})\n .then(function() { console.log(\"Sign-in successful\"); },\n function(err) { console.error(\"Error signing in\", err); });\n }\n function loadClient() {\n return gapi.client.load(\"https://youtubeanalytics.googleapis.com/$discovery/rest?version=v2\")\n .then(function() { console.log(\"GAPI client loaded for API\"); },\n function(err) { console.error(\"Error loading GAPI client for API\", err); });\n }\n // Make sure the client is loaded and sign-in is complete before calling this method.\n function execute() {\n return gapi.client.youtubeAnalytics.reports.query({\n \"ids\": \"channel==MINE\",\n \"startDate\": \"2017-01-01\",\n \"endDate\": \"2017-12-31\",\n \"metrics\": \"views,estimatedMinutesWatched,averageViewDuration,averageViewPercentage,subscribersGained\",\n \"dimensions\": \"day\",\n \"sort\": \"day\"\n })\n .then(function(response) {\n // Handle the results here (response.result has the parsed body).\n console.log(\"Response\", response);\n },\n function(err) { console.error(\"Execute error\", err); });\n }\n gapi.load(\"client:auth2\", function() {\n gapi.auth2.init({client_id: 'YOUR_CLIENT_ID'});\n });\n\u003c/script\u003e\n\u003cbutton onclick=\"authenticate().then(loadClient)\"\u003eauthorize and load\u003c/button\u003e\n\u003cbutton onclick=\"execute()\"\u003eexecute\u003c/button\u003e\nhttps://github.com/youtube/api-samples/blob/07263305b59a7c3275bc7e925f9ce6cabf774022/javascript/yt_analytics_v2.html\n```"]]