Java Code Samples

  • The YouTube Reporting API allows users to create jobs to generate bulk reports, with the ability to list available report types and create new jobs with specified names and report type IDs.

  • The YouTube Analytics API supports targeted query reports, such as retrieving the top 10 videos by view count, customizable through command-line parameters.

  • The provided Java code samples utilize the Google APIs Client Library for Java and OAuth 2.0 for authentication, supporting monetary reports access via a specific scope.

  • The code samples handle common exceptions, such as GoogleJsonResponseException, IOException, and Throwable, ensuring robustness, and prompts the user for different information such as the name of the job, or the url to download a report.

  • The code samples can list available report types, generate a reporting job, download the reports and stores them in a file named report.

The following code samples, which use the Google APIs Client Library for Java, are available for the YouTube Reporting API and YouTube Analytics API. You can download these code samples from the java folder of the YouTube APIs code sample repository on GitHub.

Bulk reports

Retrieve reports

This sample demonstrates how to retrieve reports created by a specific job. It calls the jobs.list method to retrieve reporting jobs. It then calls the reports.list method with the jobId parameter set to a specific job ID to retrieve reports created by that job. Finally, the sample prints out the download URL for each report.

/*
 * Copyright (c) 2015 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.
 */
packagecom.google.api.services.samples.youtube.cmdline.reporting;
importcom.google.api.client.auth.oauth2.Credential;
importcom.google.api.client.googleapis.json.GoogleJsonResponseException;
importcom.google.api.client.http.GenericUrl;
importcom.google.api.services.samples.youtube.cmdline.Auth;
importcom.google.api.services.youtubereporting.YouTubeReporting;
importcom.google.api.services.youtubereporting.YouTubeReporting.Media.Download;
importcom.google.api.services.youtubereporting.model.Job;
importcom.google.api.services.youtubereporting.model.ListJobsResponse;
importcom.google.api.services.youtubereporting.model.ListReportsResponse;
importcom.google.api.services.youtubereporting.model.Report;
importcom.google.common.collect.Lists;
importjava.io.BufferedReader;
importjava.io.ByteArrayOutputStream;
importjava.io.File;
importjava.io.FileOutputStream;
importjava.io.IOException;
importjava.io.InputStreamReader;
importjava.util.List;
importjavax.print.attribute.standard.Media;
/**
 * This sample retrieves reports created by a specific job by:
 *
 * 1. Listing the jobs using the "jobs.list" method.
 * 2. Retrieving reports using the "reports.list" method.
 *
 * @author Ibrahim Ulukaya
 */
publicclass RetrieveReports{
/**
 * Define a global instance of a YouTube Reporting object, which will be used to make
 * YouTube Reporting API requests.
 */
privatestaticYouTubeReportingyoutubeReporting;
/**
 * Retrieve reports.
 *
 * @param args command line args (not used).
 */
publicstaticvoidmain(String[]args){
/*
 * This OAuth 2.0 access scope allows for read access to the YouTube Analytics monetary reports for
 * authenticated user's account. Any request that retrieves earnings or ad performance metrics must
 * use this scope.
 */
List<String>scopes=Lists.newArrayList("https://www.googleapis.com/auth/yt-analytics-monetary.readonly");
try{
// Authorize the request.
Credentialcredential=Auth.authorize(scopes,"retrievereports");
// This object is used to make YouTube Reporting API requests.
youtubeReporting=newYouTubeReporting.Builder(Auth.HTTP_TRANSPORT,Auth.JSON_FACTORY,credential)
.setApplicationName("youtube-cmdline-retrievereports-sample").build();
if(listReportingJobs()){
if(retrieveReports(getJobIdFromUser())){
downloadReport(getReportUrlFromUser());
}
}
}catch(GoogleJsonResponseExceptione){
System.err.println("GoogleJsonResponseException code: "+e.getDetails().getCode()
+" : "+e.getDetails().getMessage());
e.printStackTrace();
}catch(IOExceptione){
System.err.println("IOException: "+e.getMessage());
e.printStackTrace();
}catch(Throwablet){
System.err.println("Throwable: "+t.getMessage());
t.printStackTrace();
}
}
/**
 * Lists reporting jobs. (jobs.listJobs)
 * @return true if at least one reporting job exists
 * @throws IOException
 */
privatestaticbooleanlistReportingJobs()throwsIOException{
// Call the YouTube Reporting API's jobs.list method to retrieve reporting jobs.
ListJobsResponsejobsListResponse=youtubeReporting.jobs().list().execute();
List<Job>jobsList=jobsListResponse.getJobs();
if(jobsList==null||jobsList.isEmpty()){
System.out.println("No jobs found.");
returnfalse;
}else{
// Print information from the API response.
System.out.println("\n================== Reporting Jobs ==================\n");
for(Jobjob:jobsList){
System.out.println(" - Id: "+job.getId());
System.out.println(" - Name: "+job.getName());
System.out.println(" - Report Type Id: "+job.getReportTypeId());
System.out.println("\n-------------------------------------------------------------\n");
}
}
returntrue;
}
/**
 * Lists reports created by a specific job. (reports.listJobsReports)
 *
 * @param jobId The ID of the job.
 * @throws IOException
 */
privatestaticbooleanretrieveReports(StringjobId)
throwsIOException{
// Call the YouTube Reporting API's reports.list method
// to retrieve reports created by a job.
ListReportsResponsereportsListResponse=youtubeReporting.jobs().reports().list(jobId).execute();
List<Report>reportslist=reportsListResponse.getReports();
if(reportslist==null||reportslist.isEmpty()){
System.out.println("No reports found.");
returnfalse;
}else{
// Print information from the API response.
System.out.println("\n============= Reports for the job "+jobId+" =============\n");
for(Reportreport:reportslist){
System.out.println(" - Id: "+report.getId());
System.out.println(" - From: "+report.getStartTime());
System.out.println(" - To: "+report.getEndTime());
System.out.println(" - Download Url: "+report.getDownloadUrl());
System.out.println("\n-------------------------------------------------------------\n");
}
}
returntrue;
}
/**
 * Download the report specified by the URL. (media.download)
 *
 * @param reportUrl The URL of the report to be downloaded.
 * @throws IOException
 */
privatestaticbooleandownloadReport(StringreportUrl)
throwsIOException{
// Call the YouTube Reporting API's media.download method to download a report.
Downloadrequest=youtubeReporting.media().download("");
FileOutputStreamfop=newFileOutputStream(newFile("report"));
request.getMediaHttpDownloader().download(newGenericUrl(reportUrl),fop);
returntrue;
}
/*
 * Prompt the user to enter a job id for report retrieval. Then return the id.
 */
privatestaticStringgetJobIdFromUser()throwsIOException{
Stringid="";
System.out.print("Please enter the job id for the report retrieval: ");
BufferedReaderbReader=newBufferedReader(newInputStreamReader(System.in));
id=bReader.readLine();
System.out.println("You chose "+id+" as the job Id for the report retrieval.");
returnid;
}
/*
 * Prompt the user to enter a URL for report download. Then return the URL.
 */
privatestaticStringgetReportUrlFromUser()throwsIOException{
Stringurl="";
System.out.print("Please enter the report URL to download: ");
BufferedReaderbReader=newBufferedReader(newInputStreamReader(System.in));
url=bReader.readLine();
System.out.println("You chose "+url+" as the URL to download.");
returnurl;
}}

Create a reporting job

This sample demonstrates how to create a reporting job. It calls the reportTypes.list method to retrieve a list of available report types. It then calls the jobs.create method to create a new reporting job.

/*
 * Copyright (c) 2015 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.
 */
packagecom.google.api.services.samples.youtube.cmdline.reporting;
importcom.google.api.client.auth.oauth2.Credential;
importcom.google.api.client.googleapis.json.GoogleJsonResponseException;
importcom.google.api.services.samples.youtube.cmdline.Auth;
importcom.google.api.services.youtubereporting.YouTubeReporting;
importcom.google.api.services.youtubereporting.model.Job;
importcom.google.api.services.youtubereporting.model.ListReportTypesResponse;
importcom.google.api.services.youtubereporting.model.ReportType;
importcom.google.common.collect.Lists;
importjava.io.BufferedReader;
importjava.io.IOException;
importjava.io.InputStreamReader;
importjava.util.List;
/**
 * This sample creates a reporting job by:
 *
 * 1. Listing the available report types using the "reportTypes.list" method.
 * 2. Creating a reporting job using the "jobs.create" method.
 *
 * @author Ibrahim Ulukaya
 */
publicclass CreateReportingJob{
/**
 * Define a global instance of a YouTube Reporting object, which will be used to make
 * YouTube Reporting API requests.
 */
privatestaticYouTubeReportingyoutubeReporting;
/**
 * Create a reporting job.
 *
 * @param args command line args (not used).
 */
publicstaticvoidmain(String[]args){
/*
 * This OAuth 2.0 access scope allows for read access to the YouTube Analytics monetary reports for
 * authenticated user's account. Any request that retrieves earnings or ad performance metrics must
 * use this scope.
 */
List<String>scopes=Lists.newArrayList("https://www.googleapis.com/auth/yt-analytics-monetary.readonly");
try{
// Authorize the request.
Credentialcredential=Auth.authorize(scopes,"createreportingjob");
// This object is used to make YouTube Reporting API requests.
youtubeReporting=newYouTubeReporting.Builder(Auth.HTTP_TRANSPORT,Auth.JSON_FACTORY,credential)
.setApplicationName("youtube-cmdline-createreportingjob-sample").build();
// Prompt the user to specify the name of the job to be created.
Stringname=getNameFromUser();
if(listReportTypes()){
createReportingJob(getReportTypeIdFromUser(),name);
}
}catch(GoogleJsonResponseExceptione){
System.err.println("GoogleJsonResponseException code: "+e.getDetails().getCode()
+" : "+e.getDetails().getMessage());
e.printStackTrace();
}catch(IOExceptione){
System.err.println("IOException: "+e.getMessage());
e.printStackTrace();
}catch(Throwablet){
System.err.println("Throwable: "+t.getMessage());
t.printStackTrace();
}
}
/**
 * Lists report types. (reportTypes.listReportTypes)
 * @return true if at least one report type exists
 * @throws IOException
 */
privatestaticbooleanlistReportTypes()throwsIOException{
// Call the YouTube Reporting API's reportTypes.list method to retrieve report types.
ListReportTypesResponsereportTypesListResponse=youtubeReporting.reportTypes().list()
.execute();
List<ReportType>reportTypeList=reportTypesListResponse.getReportTypes();
if(reportTypeList==null||reportTypeList.isEmpty()){
System.out.println("No report types found.");
returnfalse;
}else{
// Print information from the API response.
System.out.println("\n================== Report Types ==================\n");
for(ReportTypereportType:reportTypeList){
System.out.println(" - Id: "+reportType.getId());
System.out.println(" - Name: "+reportType.getName());
System.out.println("\n-------------------------------------------------------------\n");
}
}
returntrue;
}
/**
 * Creates a reporting job. (jobs.create)
 *
 * @param reportTypeId Id of the job's report type.
 * @param name name of the job.
 * @throws IOException
 */
privatestaticvoidcreateReportingJob(StringreportTypeId,Stringname)
throwsIOException{
// Create a reporting job with a name and a report type id.
Jobjob=newJob();
job.setReportTypeId(reportTypeId);
job.setName(name);
// Call the YouTube Reporting API's jobs.create method to create a job.
JobcreatedJob=youtubeReporting.jobs().create(job).execute();
// Print information from the API response.
System.out.println("\n================== Created reporting job ==================\n");
System.out.println(" - ID: "+createdJob.getId());
System.out.println(" - Name: "+createdJob.getName());
System.out.println(" - Report Type Id: "+createdJob.getReportTypeId());
System.out.println(" - Create Time: "+createdJob.getCreateTime());
System.out.println("\n-------------------------------------------------------------\n");
}
/*
 * Prompt the user to enter a name for the job. Then return the name.
 */
privatestaticStringgetNameFromUser()throwsIOException{
Stringname="";
System.out.print("Please enter the name for the job [javaTestJob]: ");
BufferedReaderbReader=newBufferedReader(newInputStreamReader(System.in));
name=bReader.readLine();
if(name.length() < 1){
// If nothing is entered, defaults to "javaTestJob".
name="javaTestJob";
}
System.out.println("You chose "+name+" as the name for the job.");
returnname;
}
/*
 * Prompt the user to enter a report type id for the job. Then return the id.
 */
privatestaticStringgetReportTypeIdFromUser()throwsIOException{
Stringid="";
System.out.print("Please enter the reportTypeId for the job: ");
BufferedReaderbReader=newBufferedReader(newInputStreamReader(System.in));
id=bReader.readLine();
System.out.println("You chose "+id+" as the report type Id for the job.");
returnid;
}
}

Targeted query reports

Retrieve top 10 videos by view count

This sample calls the API's reports.query method to retrieve YouTube Analytics data. By default, the report retrieves the top 10 videos based on viewcounts, and it returns several metrics for those videos, sorting the results in reverse order by viewcount. By setting command line parameters, you can use the same code to retrieve other reports as well.

/*
 * Copyright (c) 2015 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.
 */
packagecom.google.api.services.samples.youtube.cmdline.reporting;
importcom.google.api.client.auth.oauth2.Credential;
importcom.google.api.client.googleapis.json.GoogleJsonResponseException;
importcom.google.api.services.samples.youtube.cmdline.Auth;
importcom.google.api.services.youtubereporting.YouTubeReporting;
importcom.google.api.services.youtubereporting.model.Job;
importcom.google.api.services.youtubereporting.model.ListReportTypesResponse;
importcom.google.api.services.youtubereporting.model.ReportType;
importcom.google.common.collect.Lists;
importjava.io.BufferedReader;
importjava.io.IOException;
importjava.io.InputStreamReader;
importjava.util.List;
/**
 * This sample creates a reporting job by:
 *
 * 1. Listing the available report types using the "reportTypes.list" method.
 * 2. Creating a reporting job using the "jobs.create" method.
 *
 * @author Ibrahim Ulukaya
 */
publicclass CreateReportingJob{
/**
 * Define a global instance of a YouTube Reporting object, which will be used to make
 * YouTube Reporting API requests.
 */
privatestaticYouTubeReportingyoutubeReporting;
/**
 * Create a reporting job.
 *
 * @param args command line args (not used).
 */
publicstaticvoidmain(String[]args){
/*
 * This OAuth 2.0 access scope allows for read access to the YouTube Analytics monetary reports for
 * authenticated user's account. Any request that retrieves earnings or ad performance metrics must
 * use this scope.
 */
List<String>scopes=Lists.newArrayList("https://www.googleapis.com/auth/yt-analytics-monetary.readonly");
try{
// Authorize the request.
Credentialcredential=Auth.authorize(scopes,"createreportingjob");
// This object is used to make YouTube Reporting API requests.
youtubeReporting=newYouTubeReporting.Builder(Auth.HTTP_TRANSPORT,Auth.JSON_FACTORY,credential)
.setApplicationName("youtube-cmdline-createreportingjob-sample").build();
// Prompt the user to specify the name of the job to be created.
Stringname=getNameFromUser();
if(listReportTypes()){
createReportingJob(getReportTypeIdFromUser(),name);
}
}catch(GoogleJsonResponseExceptione){
System.err.println("GoogleJsonResponseException code: "+e.getDetails().getCode()
+" : "+e.getDetails().getMessage());
e.printStackTrace();
}catch(IOExceptione){
System.err.println("IOException: "+e.getMessage());
e.printStackTrace();
}catch(Throwablet){
System.err.println("Throwable: "+t.getMessage());
t.printStackTrace();
}
}
/**
 * Lists report types. (reportTypes.listReportTypes)
 * @return true if at least one report type exists
 * @throws IOException
 */
privatestaticbooleanlistReportTypes()throwsIOException{
// Call the YouTube Reporting API's reportTypes.list method to retrieve report types.
ListReportTypesResponsereportTypesListResponse=youtubeReporting.reportTypes().list()
.execute();
List<ReportType>reportTypeList=reportTypesListResponse.getReportTypes();
if(reportTypeList==null||reportTypeList.isEmpty()){
System.out.println("No report types found.");
returnfalse;
}else{
// Print information from the API response.
System.out.println("\n================== Report Types ==================\n");
for(ReportTypereportType:reportTypeList){
System.out.println(" - Id: "+reportType.getId());
System.out.println(" - Name: "+reportType.getName());
System.out.println("\n-------------------------------------------------------------\n");
}
}
returntrue;
}
/**
 * Creates a reporting job. (jobs.create)
 *
 * @param reportTypeId Id of the job's report type.
 * @param name name of the job.
 * @throws IOException
 */
privatestaticvoidcreateReportingJob(StringreportTypeId,Stringname)
throwsIOException{
// Create a reporting job with a name and a report type id.
Jobjob=newJob();
job.setReportTypeId(reportTypeId);
job.setName(name);
// Call the YouTube Reporting API's jobs.create method to create a job.
JobcreatedJob=youtubeReporting.jobs().create(job).execute();
// Print information from the API response.
System.out.println("\n================== Created reporting job ==================\n");
System.out.println(" - ID: "+createdJob.getId());
System.out.println(" - Name: "+createdJob.getName());
System.out.println(" - Report Type Id: "+createdJob.getReportTypeId());
System.out.println(" - Create Time: "+createdJob.getCreateTime());
System.out.println("\n-------------------------------------------------------------\n");
}
/*
 * Prompt the user to enter a name for the job. Then return the name.
 */
privatestaticStringgetNameFromUser()throwsIOException{
Stringname="";
System.out.print("Please enter the name for the job [javaTestJob]: ");
BufferedReaderbReader=newBufferedReader(newInputStreamReader(System.in));
name=bReader.readLine();
if(name.length() < 1){
// If nothing is entered, defaults to "javaTestJob".
name="javaTestJob";
}
System.out.println("You chose "+name+" as the name for the job.");
returnname;
}
/*
 * Prompt the user to enter a report type id for the job. Then return the id.
 */
privatestaticStringgetReportTypeIdFromUser()throwsIOException{
Stringid="";
System.out.print("Please enter the reportTypeId for the job: ");
BufferedReaderbReader=newBufferedReader(newInputStreamReader(System.in));
id=bReader.readLine();
System.out.println("You chose "+id+" as the report type Id for the job.");
returnid;
}
}

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2026年04月13日 UTC.