Bu değişikliğin şu anda Temmuz 2018'de yürürlüğe girmesi planlanmaktadır ve yeni politika tüm raporlar ve raporlama işlerine dünya genelinde uygulanmaktadır. Bu değişiklikle ilgili tüm ayrıntılar için API'nın düzeltme geçmişine göz atın.
YouTube Reporting API, bir kanal veya içerik sahibi için kapsamlı YouTube Analytics verileri içeren önceden tanımlanmış raporları destekler. Bu raporlar, YouTube Analytics API ile veya İçerik Stüdyosu'nun Analytics bölümünde sorgulayabileceğiniz toplu veri kümelerini indirmenize olanak tanır.
Genel bakış
Bu raporlardaki rapor alanları boyut veya metrik olarak nitelendirilir:
- Boyutlar, verileri toplamak için kullanılan yaygın işlemlerdir (ör. işlemin gerçekleştiği tarih veya kullanıcıların bulunduğu ülke). Bir raporda, her veri satırının boyut değerlerinin benzersiz bir kombinasyonu vardır.
- Metrikler; kullanıcı etkinliği, reklam performansı veya tahmini gelirle ilgili ayrı ölçümlerdir. Kullanıcı etkinliği metrikleri video görüntüleme sayısı ve puanları (beğenme ve beğenmeme sayısı) gibi şeyleri içerir.
Örneğin, kanallarla ilgili temel kullanıcı etkinliği raporu aşağıdaki boyutları içerir:
- date: Etkinliğin gerçekleştiği tarih.
- channel_id: Etkinlikle ilişkilendirilen YouTube kanalı.
- video_id: Etkinlikle ilişkilendirilen YouTube videosu.
- live_or_on_optional: İzleyicilerin canlı video yayınları izleyip izlemediğini gösteren değer.
- subscribed_status: İzleyicilerin kanala abone olup olmadığını belirten bir değerdir.
- ülke_kodu: İzleyicilerin bulunduğu ülke.
Raporda görüntüleme sayısı, beğeni ve Ortalama_görüntü_süresi_saniye gibi çok sayıda metrik de yer alır. Bir uygulama, raporu alıp içe aktardıktan sonra, yaygın boyut değerlerine dayalı olarak birçok farklı hesaplama yapabilir.
YouTube Analytics raporlarını alma
1. Adım: Yetkilendirme kimlik bilgilerini alın
Tüm YouTube Reporting API istekleri yetkilendirilmelidir. Yetkilendirme kılavuzunda, yetkilendirme jetonlarını almak için OAuth 2.0 protokolünün nasıl kullanılacağı açıklanmaktadır.
YouTube Reporting API isteklerinde aşağıdaki yetkilendirme kapsamları kullanılır:
Nişan dürbünleri | |
---|---|
https://www.googleapis.com/auth/yt-analytics.readonly | YouTube içeriğiniz için YouTube Analytics raporlarını görüntüleyin. Bu kapsam, görüntüleme sayısı ve puan sayısı gibi kullanıcı etkinliği metriklerine erişim sağlar. |
https://www.googleapis.com/auth/yt-analytics-monetary.readonly | YouTube içeriğiniz için YouTube Analytics mali raporlarını görüntüleyin. Bu kapsam, kullanıcı etkinliği metriklerine ve tahmini gelir ile reklam performansı metriklerine erişim sağlar. |
2. Adım: Alınacak raporu tanımlayın
Kanal veya içerik sahibi için oluşturulabilecek raporların listesini almak üzere API'nin reportTypes.list
yöntemini çağırın. Yöntem, rapor kimlikleri ve adlarının bir listesini döndürür. Oluşturulmasını istediğiniz raporlar için id
özellik değerini yakalayın. Örneğin, kanallar için temel kullanıcı etkinliği raporunun kimliği channel_basic_a1
'dir.
Rapor adlarını, desteklenen kanal raporlarını ve içerik sahibi raporlarını tanımlayan dokümanlarda da bulabilirsiniz.
3. Adım: Raporlama işi oluşturma
YouTube, söz konusu rapor için bir raporlama işi oluşturana kadar raporunuzu oluşturmaya başlamaz. (Bu nedenle, raporlar yalnızca onları almak isteyen kanallar ve içerik sahipleri için oluşturulur.)
Raporlama işi oluşturmak için API'nin jobs.create
yöntemini çağırın. İstek gövdesinde aşağıdaki değerleri ayarlayın:
reportTypeId
özelliğinin değerini 2. adımda aldığınız rapor kimliğine ayarlayın.name
özelliğinin değerini, raporla ilişkilendirmek istediğiniz ada ayarlayın.
jobs.create
yöntemine API yanıtı, işi benzersiz şekilde tanımlayan ID
öğesini belirten bir Job
kaynağı içeriyor. Raporu, işi oluşturulduğu andan itibaren 48 saat içinde almaya başlayabilirsiniz. Mevcut ilk rapor, işi planladığınız gün için olacaktır.
Örneğin, 1 Eylül 2015 tarihinde bir iş planlarsanız, 1 Eylül 2015 raporu 3 Eylül 2015 tarihinde hazır olacaktır. 2 Eylül 2015 raporu 4 Eylül 2015 tarihinde vs. yayınlanacak.
4. Adım: İş kimliğini alın
Not: Uygulamanız 3. adımda döndürülen iş kimliğini depoladıysa bu adımı atlayabilirsiniz.
Planlanmış işlerin listesini almak için jobs.list
yöntemini çağırın. Döndürülen her Job
kaynağındaki reportTypeId
özelliği, işin oluşturduğu rapor türünü tanımlar. Uygulamanız bir sonraki adımda aynı kaynaktan alınan id
özellik değerine sahip olmalıdır.
5. Adım: Raporun indirme URL'sini alın
İş için oluşturulan raporların listesini almak için jobs.reports.list
yöntemini çağırın. İstekte, almak istediğiniz raporun iş kimliğine jobId
parametresini ayarlayın.
İpucu: API'nin yalnızca belirli bir süre sonra oluşturulan raporları döndürmesi gerektiğini belirtmek için createdAfter
parametresini kullanın. Bu parametre, API'nin yalnızca henüz işlemediğiniz raporları döndürmesini sağlamak için kullanılabilir.
API yanıtı, bu iş için Report
kaynakların listesini içerir. Her kaynak, 24 saatlik benzersiz bir döneme ait verileri içeren bir raporu ifade eder. YouTube'da hiçbir verinin mevcut olmadığı günler için indirilebilir raporlar üretildiğini unutmayın. Bu raporlarda başlık satırı bulunur ancak ek veriler bulunmaz.
- Kaynağın
startTime
veendTime
özellikleri, rapor verilerinin kapsadığı dönemi tanımlar. - Kaynağın
downloadUrl
özelliği, raporun getirilebileceği URL'yi tanımlar. - Kaynağın
createTime
özelliği, raporun oluşturulduğu tarihi ve saati belirtir. Uygulamanız bu değeri saklamalı ve daha önce indirilen raporların değişip değişmediğini belirlemek için kullanmalıdır.
6. Adım: Raporu indirin
Raporu almak için 5. adımda elde ettiğiniz downloadUrl
öğesine bir HTTP GET isteği gönderin.
Raporları indirmek için gereken bant genişliğini, indirme isteklerinde gzip sıkıştırmayı etkinleştirerek azaltabilirsiniz. Uygulamanız, API yanıtlarını açmak için ek CPU süresine ihtiyaç duyacak olsa da daha az ağ kaynağı kullanma avantajı, genellikle bu maliyetten daha değerlidir.
gzip kodlu bir yanıt almak için Accept-Encoding
HTTP istek başlığını aşağıdaki örnekte gösterildiği gibi gzip
olarak ayarlayın:
Accept-Encoding: gzip
Raporları işleme
En iyi uygulamalar
YouTube Reporting API'yi kullanan uygulamalar her zaman şu uygulamaları takip etmelidir:
-
Rapor sütunlarının sıralamasını belirlemek için raporun başlık satırını kullanın. Örneğin, raporların bir raporun açıklamasında listelenen ilk metrik olması nedeniyle, söz konusu raporda döndürülen ilk metrik olacağını varsaymayın. Bunun yerine, hangi verilerin bu verileri içerdiğini belirlemek için raporun başlık satırını kullanın.
-
Aynı raporun tekrar tekrar işlenmesini önlemek için indirdiğiniz raporların kaydını tutun. Aşağıdaki listede bunu yapmanın birkaç yolu önerilmiştir.
-
reports.list
yöntemini çağırırken, yalnızca belirli bir tarihten sonra oluşturulan raporları almak için createAfter parametresini kullanın. (Raporları ilk kez aldığınızdacreatedAfter
parametresini girmeyin.)Raporları alırken ve başarılı bir şekilde işlerken her zaman bu raporların en yenisinin oluşturulduğu tarihe ve saate karşılık gelen zaman damgasını depolayın. Daha sonra, API'yi her çağırdığınızda doldurulan verilerle yeni raporlar da dahil olmak üzere yalnızca yeni raporları aldığınızdan emin olmak için art arda yapılan her
reports.list
yöntemine yapılancreatedAfter
parametre değerini güncelleyin.Önlem olarak, bir raporu almadan önce raporun kimliğinin henüz veritabanınızda listelenmediğinden emin olun.
-
İndirdiğiniz ve işlediğiniz her rapor için kimliği saklayın. Ayrıca, tarih ve saat gibi, her raporun oluşturulduğu zamanı veya raporun
startTime
ileendTime
gibi ek bilgileri saklayabilirsiniz. Bu veriler, raporun veri içerdiği dönemi tanımlar. Her raporda 24 saatlik bir veriler bulunduğu için her işin muhtemelen çok sayıda raporu olacağını unutmayın.İndirmeniz ve içe aktarmanız gereken raporları tanımlamak için rapor kimliğini kullanın. Bununla birlikte, iki yeni rapor aynı
startTime
veendTime
özellik değerlerine sahipse raporu yalnızca daha yenicreateTime
değeriyle içe aktarın.
-
-
Raporlar YouTube kaynaklarıyla ilişkili kimlikler içerir ve bu kaynaklarla ilgili ek meta verileri almak için YouTube Data API'yi kullanabilirsiniz. YouTube API Hizmetleri Geliştirici Politikaları'nda belirtildiği üzere (III.E.4.b ile III.E.4.d bölümleri arasında), API istemcilerinin depolanan API meta verilerini 30 gün sonra silmeleri veya yenilemeleri gerekir.
Rapor özellikleri
API raporları, aşağıdaki özelliklere sahip, sürümü .csv
olan (virgülle ayrılmış değerler) dosyalardır:
-
Her raporda, Pasifik saatiyle 00:00 ile 23:59 arasında geçerli olan benzersiz bir 24 saatlik döneme ait veriler yer alır. Dolayısıyla belirli bir raporda tarih boyut değeri her zaman aynıdır.
-
Raporlar günlük olarak güncellenir.
-
YouTube, hiçbir verinin mevcut olmadığı günler için indirilebilir raporlar oluşturur. Bu raporlar bir başlık satırı içerir ancak ek veriler içermez.
-
Önemli: Yakında yapılacak bir politika değişikliği, YouTube Reporting API raporlarını alabileceğiniz süreyi etkilemektedir. Temmuz 2018'de yürürlüğe girmesi planlanan bu değişiklik, tüm raporlar ve raporlama işleri için tüm dünyada geçerli olacaktır.
- Değişiklikten önce, API raporları, oluşturulduktan sonraki 180 gün boyunca kullanılabilir.
- Değişiklikten sonra, API raporları, yeni raporlama işleri için oluşturulan geçmiş veriler hariç, oluşturulduktan sonraki 60 gün boyunca kullanılabilecektir. Politika değişikliği yürürlüğe girdiğinde 60 günden eski raporlara artık erişilemez.
- Değişiklikten sonra, geçmiş verileri içeren raporlara oluşturuldukları andan itibaren 30 gün boyunca erişebileceksiniz. Politika değişikliği yürürlüğe girdiğinde, geçmiş verileri içeren ve 30 günden eski olan raporlara artık erişilemez.
-
Rapor verileri filtrelenmez. Bu nedenle kanal raporunda, bir kanaldaki videoların veya oynatma listelerinin tüm verileri yer alır. Silinen kaynaklarla ilgili aşağıdaki paragrafta belirtilenler istisnadır. Benzer şekilde, içerik sahibi raporu, şu istisnayla içerik sahibinin kanallarına ait tüm verileri (videolar, oynatma listeleri, reklam performansı vb.) içerir.
Rapor verileri filtrelenmese de 1 Haziran 2018 veya sonrasında bir döneme ait veriler içeren raporlar, raporun oluşturulduğu tarihten en az 30 gün önce silinmiş YouTube kaynaklarına herhangi bir referans içermez.
-
Rapor verileri sıralanmamış.
-
Raporlarda, metriği olmayan satırlar çıkarılır. Diğer bir deyişle, metriği olmayan satırlar rapordan hariç tutulur. Örneğin, bir video Arnavutluk'ta belirli bir günde hiç görüntüleme içermiyorsa bu güne ait rapor Arnavutluk satırlarını içermez.
-
Raporlar, bir kanalın tüm videolarının toplam görüntüleme sayısı gibi metriklerle ilgili özet veriler sunan satırlar içermez. Bu toplam değerleri rapordaki değerlerin toplamı olarak hesaplayabilirsiniz, ancak bu toplam, yukarıda belirtildiği gibi silinmiş videoların metriklerini içermeyebilir. Toplam sayıyı almak için YouTube Analytics API'yi de kullanabilirsiniz. YouTube Analytics API, silinmiş kaynaklar için metrikler içeren toplam değerleri döndürür. Ancak bu kaynaklar API yanıtlarında açıkça belirtilmemiş olsa da.
Dolgu verileri
Dolgu verileri, daha önce yayınlanan bir grubun yerini alan bir veri kümesini belirtir. Bir dolgu veri raporu mevcut olduğunda, uygulamanız yeni raporu almalı ve depolanan verilerinizi düzeltilmiş veri kümesiyle eşleşecek şekilde güncellemelidir. Örneğin, uygulamanız raporda yer alan dönem için önceki verileri silebilir ve ardından yeni veri kümesini içe aktarabilir.
YouTube'un dolgu verileri varsa yeni bir rapor kimliği ile yeni bir rapor oluşturulur. Bu durumda raporun startTime
ve endTime
özellik değerleri, daha önce kullanılabilir olan ve daha önce indirmiş olabileceğiniz bir raporun başlangıç ve bitiş zamanlarıyla eşleşir.
1 Haziran 2018 veya sonrasında bir döneme ait verileri içeren dolgu raporları, raporun oluşturulduğu tarihten en az 30 gün önce silinmiş YouTube kaynaklarına herhangi bir referans içermez.
Geçmiş verileri
Yeni bir raporlama işi planladığınızda YouTube, işi oluşturduğunuz tarihten önceki bir dönemi kapsayan geçmiş raporlar oluşturur. Dolayısıyla, bu dokümanda geçmiş veriler, raporlama işi planlanmadan önceki bir döneme ait verileri içeren bir raporu ifade eder.
Önemli: Yaklaşan bir politika değişikliği, geçmiş rapor verilerinin oluşturulacağı süreyi etkiler. Temmuz 2018'de yürürlüğe girmesi planlanan bu değişiklik, tüm raporlar ve raporlama işleri için tüm dünyada geçerli olacaktır.
- Politika değişikliğinden önce YouTube yeni bir raporlama işi planladığınızda, işi oluşturduğunuz tarihten önceki 180 günlük dönemi kapsayan raporlar oluşturur.
- Politika değişikliğinden sonra yeni bir raporlama işi planladığınızda YouTube, o günden itibaren raporları oluşturur ve işi oluşturduğunuz tarihten önceki 30 günlük dönemi kapsar.
Geçmiş raporlar, kullanıma sunulur sunulmaz yayınlanır. Genellikle tüm iş verileri birkaç iş günü içinde yayınlanır. Rapor özellikleri bölümünde açıklandığı gibi, Temmuz 2018'de yürürlüğe girmesi planlanan bir politika değişikliğinden sonra, geçmiş verileri içeren raporlar, oluşturuldukları andan itibaren 30 gün boyunca kullanılabilir olacaktır. Geçmiş olmayan verileri içeren raporlara politika değişikliğinden sonraki 60 gün boyunca erişilebilir.
Veri anonimleştirme
YouTube izleyicilerinin anonim olmasını sağlamak için bazı boyutlardaki değerler yalnızca aynı satırdaki bir metrik belirli bir eşiği karşılıyorsa döndürülür.
Örneğin, kanallar için video trafiği kaynak raporunda her satır traffic_source_type ve traffic_source_detail gibi çeşitli boyutlar içerir. Her satırda görüntüleme sayısı gibi çeşitli metrikler de bulunur. Bir YouTube aramasından kaynaklanan trafiği açıklayan satırlarda, traffic_source_detail boyutu trafiğe yönlendiren arama terimini tanımlar.
Bu örnekte aşağıdaki kurallar geçerlidir:
-
Trafik kaynağı raporu, sorgu terimini (traffic_source_detail) yalnızca belirli bir günde belirli bir videonun en az belirli bir sayıda görüntülemesini sağlamışsa tanımlar. Bu durumda, views metriği, video_id bir araya getirilmiş boyuttur ve traffic_source_detail anonimleştirilmiş boyuttur.
-
Rapor, görüntüleme sayısı eşiğini karşılamayan tüm traffic_source_detail değerlerine ait metrikleri toplayan ek bir satır içerir. Söz konusu satırda, bu sorgu terimleriyle ilişkilendirilen toplam görüntüleme sayısı raporlanır ancak terimlerin kendisi tanımlanmaz.
Aşağıdaki tablolarda bu kurallar gösterilmektedir. İlk tabloda trafik kaynağı raporu oluşturmak için YouTube'un kullanacağı varsayımsal bir ham veri grubu, ikinci tabloda ise raporun kendisi yer alır. Bu örnekte, görüntüleme sayısı eşiği 10'dur. Yani, rapor yalnızca belirli bir günde belirli bir videonun en az 10 kez izlenmesine neden olan arama terimini tanımlar. (Gerçek eşikler değişebilir.)
Bir video için ham YouTube arama trafiği verileri
Aşağıdaki verilerin, belirli bir günde belirli bir videoya gelen YouTube arama trafiğini açıkladığını varsayalım.
arama terimi | görüntüleme | dakika cinsinden tahmini izleme süresi |
---|---|---|
gangnam stili | 100 | 200 |
psy | 15 | 25 |
psy gangnam | 9 | 15 |
oppa gangnam | 5 | 8 |
at dansı | 2 | 5 |
Örnek trafik kaynağı raporu
Aşağıdaki tabloda, YouTube'un önceki bölümde bulunan ham veriler için oluşturacağı trafik kaynağı raporundan bir alıntı gösterilmektedir. (Asıl raporda daha fazla boyut ve metrik bulunabilir.) Bu örnekte, rapor yalnızca en az 10 görüntüleme sağlayan arama terimlerini tanımlar. Gerçek eşikler değiştirilebilir.
Raporun üçüncü satırında trafficSourceDetail
boyut değeri NULL
şeklindedir. views
ve estimatedMinutesWatched
metrikleri, 10'dan az görüntüleme oluşturan üç arama terimi için toplam görüntüleme sayısını ve dakikasını içerir.
trafikKaynak Ayrıntısı | görüntüleme | Tahmini Dakika İzlenenler |
---|---|---|
gangnam stili | 100 | 200 |
psy | 15 | 25 |
BOŞ | 16 | 28 |
Anonimleştirmeye uygun boyutlar
Aşağıdaki tabloda, ilişkili metrik değerleri belirli bir eşiği karşılamıyorsa anonimleştirilmiş boyut değerleri gösterilmektedir. Her durumda, metriğin değeri başka bir boyutun üzerinde toplanır. Örneğin, metrik görüntüleme sayısı ve toplama boyutu video_id ise video değeri belirli bir sayıda izlenmediği sürece boyut değeri anonimleştirilir.
Metrik | Boyutları birleştirme | Anonimleştirilmiş boyut | Anonimleştirilmiş değer |
---|---|---|---|
abone_edindi | kanal_kimliği | ülke_kodu | ZZ |
abone_edindi | kanal_kimliği | il_kodu | US-ZZ |
abone_kaybı | kanal_kimliği | ülke_kodu | ZZ |
abone_kaybı | kanal_kimliği | il_kodu | US-ZZ |
yorumlar | video_id [video_kimliği] | ülke_kodu | ZZ |
yorumlar | video_id [video_kimliği] | il_kodu | US-ZZ |
beğenme | video_id [video_kimliği] | ülke_kodu | ZZ |
beğenme | video_id [video_kimliği] | il_kodu | US-ZZ |
beğenmeme | video_id [video_kimliği] | ülke_kodu | ZZ |
beğenmeme | video_id [video_kimliği] | il_kodu | US-ZZ |
görüntüleme | video_id [video_kimliği] | yaş_grubu | NULL |
görüntüleme | video_id [video_kimliği] | cinsiyet | NULL |
görüntüleme | video_id ve traffic_source_detail | trafik_kaynak_ayrıntıları | NULL |
Kanala abone sayısı | kanal_kimliği | subscribed_status | NULL |
Kod örnekleri
Aşağıdaki kod örnekleri, bir raporlama işi oluşturmak ve ardından bu iş için rapor almak üzere API'nin nasıl kullanılacağını gösterir. Her dil için iki kod örneği sağlanmıştır:
-
İlk kod örneğinde, mevcut rapor türlerinin bir listesinin nasıl alınacağı ve ardından yeni bir raporlama işinin nasıl oluşturulacağı gösterilmektedir.
-
İkinci kod örneği, belirli bir iş için nasıl rapor alınacağını gösterir. Raporları, iş oluşturulduktan sonraki 48 saat içinde almaya başlayabilirsiniz.
Not: Aşağıdaki kod örnekleri, desteklenen tüm programlama dillerini temsil etmeyebilir. Desteklenen dillerin listesi için istemci kitaplıkları dokümanlarına bakın.
Java
Aşağıdaki örneklerde Java istemci kitaplığı kullanılmaktadır:
1. Örnek: Raporlama işi oluşturma
Aşağıdaki kod örneği, kullanılabilir rapor türlerinin listesini almak için reportTypes.list
yöntemini çağırır. Ardından, yeni bir raporlama işi oluşturmak için jobs.create
yöntemini çağırır.
/* * 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. */ package com.google.api.services.samples.youtube.cmdline.reporting; import com.google.api.client.auth.oauth2.Credential; import com.google.api.client.googleapis.json.GoogleJsonResponseException; import com.google.api.services.samples.youtube.cmdline.Auth; import com.google.api.services.youtubereporting.YouTubeReporting; import com.google.api.services.youtubereporting.model.Job; import com.google.api.services.youtubereporting.model.ListReportTypesResponse; import com.google.api.services.youtubereporting.model.ReportType; import com.google.common.collect.Lists; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.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 */ public class CreateReportingJob { /** * Define a global instance of a YouTube Reporting object, which will be used to make * YouTube Reporting API requests. */ private static YouTubeReporting youtubeReporting; /** * Create a reporting job. * * @param args command line args (not used). */ public static void main(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. Credential credential = Auth.authorize(scopes, "createreportingjob"); // This object is used to make YouTube Reporting API requests. youtubeReporting = new YouTubeReporting.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. String name = getNameFromUser(); if (listReportTypes()) { createReportingJob(getReportTypeIdFromUser(), name); } } 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(); } } /** * Lists report types. (reportTypes.listReportTypes) * @return true if at least one report type exists * @throws IOException */ private static boolean listReportTypes() throws IOException { // Call the YouTube Reporting API's reportTypes.list method to retrieve report types. ListReportTypesResponse reportTypesListResponse = youtubeReporting.reportTypes().list() .execute(); List<ReportType> reportTypeList = reportTypesListResponse.getReportTypes(); if (reportTypeList == null || reportTypeList.isEmpty()) { System.out.println("No report types found."); return false; } else { // Print information from the API response. System.out.println("\n================== Report Types ==================\n"); for (ReportType reportType : reportTypeList) { System.out.println(" - Id: " + reportType.getId()); System.out.println(" - Name: " + reportType.getName()); System.out.println("\n-------------------------------------------------------------\n"); } } return true; } /** * Creates a reporting job. (jobs.create) * * @param reportTypeId Id of the job's report type. * @param name name of the job. * @throws IOException */ private static void createReportingJob(String reportTypeId, String name) throws IOException { // Create a reporting job with a name and a report type id. Job job = new Job(); job.setReportTypeId(reportTypeId); job.setName(name); // Call the YouTube Reporting API's jobs.create method to create a job. Job createdJob = 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. */ private static String getNameFromUser() throws IOException { String name = ""; System.out.print("Please enter the name for the job [javaTestJob]: "); BufferedReader bReader = new BufferedReader(new InputStreamReader(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."); return name; } /* * Prompt the user to enter a report type id for the job. Then return the id. */ private static String getReportTypeIdFromUser() throws IOException { String id = ""; System.out.print("Please enter the reportTypeId for the job: "); BufferedReader bReader = new BufferedReader(new InputStreamReader(System.in)); id = bReader.readLine(); System.out.println("You chose " + id + " as the report type Id for the job."); return id; } }
2. Örnek: Rapor alma
Kod örneği, raporlama işlerinin listesini almak için jobs.list
yöntemini çağırır. Daha sonra, jobId
parametresini belirli bir iş kimliğine ayarlayarak, söz konusu iş tarafından oluşturulan raporları almak için reports.list
yöntemini çağırır. Son olarak örnek, her raporun indirme URL'sini yazdırır.
/* * 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. */ package com.google.api.services.samples.youtube.cmdline.reporting; import com.google.api.client.auth.oauth2.Credential; import com.google.api.client.googleapis.json.GoogleJsonResponseException; import com.google.api.client.http.GenericUrl; import com.google.api.services.samples.youtube.cmdline.Auth; import com.google.api.services.youtubereporting.YouTubeReporting; import com.google.api.services.youtubereporting.YouTubeReporting.Media.Download; import com.google.api.services.youtubereporting.model.Job; import com.google.api.services.youtubereporting.model.ListJobsResponse; import com.google.api.services.youtubereporting.model.ListReportsResponse; import com.google.api.services.youtubereporting.model.Report; import com.google.common.collect.Lists; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.List; import javax.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 */ public class RetrieveReports { /** * Define a global instance of a YouTube Reporting object, which will be used to make * YouTube Reporting API requests. */ private static YouTubeReporting youtubeReporting; /** * Retrieve reports. * * @param args command line args (not used). */ public static void main(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. Credential credential = Auth.authorize(scopes, "retrievereports"); // This object is used to make YouTube Reporting API requests. youtubeReporting = new YouTubeReporting.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, credential) .setApplicationName("youtube-cmdline-retrievereports-sample").build(); if (listReportingJobs()) { if(retrieveReports(getJobIdFromUser())) { downloadReport(getReportUrlFromUser()); } } } 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(); } } /** * Lists reporting jobs. (jobs.listJobs) * @return true if at least one reporting job exists * @throws IOException */ private static boolean listReportingJobs() throws IOException { // Call the YouTube Reporting API's jobs.list method to retrieve reporting jobs. ListJobsResponse jobsListResponse = youtubeReporting.jobs().list().execute(); List<Job> jobsList = jobsListResponse.getJobs(); if (jobsList == null || jobsList.isEmpty()) { System.out.println("No jobs found."); return false; } else { // Print information from the API response. System.out.println("\n================== Reporting Jobs ==================\n"); for (Job job : 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"); } } return true; } /** * Lists reports created by a specific job. (reports.listJobsReports) * * @param jobId The ID of the job. * @throws IOException */ private static boolean retrieveReports(String jobId) throws IOException { // Call the YouTube Reporting API's reports.list method // to retrieve reports created by a job. ListReportsResponse reportsListResponse = youtubeReporting.jobs().reports().list(jobId).execute(); List<Report> reportslist = reportsListResponse.getReports(); if (reportslist == null || reportslist.isEmpty()) { System.out.println("No reports found."); return false; } else { // Print information from the API response. System.out.println("\n============= Reports for the job " + jobId + " =============\n"); for (Report report : 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"); } } return true; } /** * Download the report specified by the URL. (media.download) * * @param reportUrl The URL of the report to be downloaded. * @throws IOException */ private static boolean downloadReport(String reportUrl) throws IOException { // Call the YouTube Reporting API's media.download method to download a report. Download request = youtubeReporting.media().download(""); FileOutputStream fop = new FileOutputStream(new File("report")); request.getMediaHttpDownloader().download(new GenericUrl(reportUrl), fop); return true; } /* * Prompt the user to enter a job id for report retrieval. Then return the id. */ private static String getJobIdFromUser() throws IOException { String id = ""; System.out.print("Please enter the job id for the report retrieval: "); BufferedReader bReader = new BufferedReader(new InputStreamReader(System.in)); id = bReader.readLine(); System.out.println("You chose " + id + " as the job Id for the report retrieval."); return id; } /* * Prompt the user to enter a URL for report download. Then return the URL. */ private static String getReportUrlFromUser() throws IOException { String url = ""; System.out.print("Please enter the report URL to download: "); BufferedReader bReader = new BufferedReader(new InputStreamReader(System.in)); url = bReader.readLine(); System.out.println("You chose " + url + " as the URL to download."); return url; }}
PHP
Aşağıdaki örneklerde PHP istemci kitaplığı kullanılmaktadır.
1. Örnek: Raporlama işi oluşturma
Aşağıdaki kod örneği, kullanılabilir rapor türlerinin listesini almak için reportTypes.list
yöntemini çağırır. Ardından, yeni bir raporlama işi oluşturmak için jobs.create
yöntemini çağırır.
<?php /** * 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 */ /** * 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 Cloud Console }} <{{ https://cloud.google.com/console }}> * 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); /* * 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. */ $client->setScopes('https://www.googleapis.com/auth/yt-analytics-monetary.readonly'); $redirect = filter_var('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'], FILTER_SANITIZE_URL); $client->setRedirectUri($redirect); // YouTube Reporting object used to make YouTube Reporting API requests. $youtubeReporting = new Google_Service_YouTubeReporting($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()) { // This code executes if the user enters a name in the form // and submits the form. Otherwise, the page displays the form above. try { if (empty(listReportTypes($youtubeReporting, $htmlBody))) { $htmlBody .= sprintf('<p>No report types found.</p>'); } else if ($_GET['reportTypeId']){ createReportingJob($youtubeReporting, $_GET['reportTypeId'], $_GET['jobName'], $htmlBody); } } 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; } /** * Creates a reporting job. (jobs.create) * * @param Google_Service_YouTubereporting $youtubeReporting YouTube Reporting service object. * @param string $reportTypeId Id of the job's report type. * @param string $name name of the job. * @param $htmlBody - html body. */ function createReportingJob(Google_Service_YouTubeReporting $youtubeReporting, $reportTypeId, $name, &$htmlBody) { # Create a reporting job with a name and a report type id. $reportingJob = new Google_Service_YouTubeReporting_Job(); $reportingJob->setReportTypeId($reportTypeId); $reportingJob->setName($name); // Call the YouTube Reporting API's jobs.create method to create a job. $jobCreateResponse = $youtubeReporting->jobs->create($reportingJob); $htmlBody .= "<h2>Created reporting job</h2><ul>"; $htmlBody .= sprintf('<li>"%s" for reporting type "%s" at "%s"</li>', $jobCreateResponse['name'], $jobCreateResponse['reportTypeId'], $jobCreateResponse['createTime']); $htmlBody .= '</ul>'; } /** * Returns a list of report types. (reportTypes.listReportTypes) * * @param Google_Service_YouTubereporting $youtubeReporting YouTube Reporting service object. * @param $htmlBody - html body. */ function listReportTypes(Google_Service_YouTubeReporting $youtubeReporting, &$htmlBody) { // Call the YouTube Reporting API's reportTypes.list method to retrieve report types. $reportTypes = $youtubeReporting->reportTypes->listReportTypes(); $htmlBody .= "<h3>Report Types</h3><ul>"; foreach ($reportTypes as $reportType) { $htmlBody .= sprintf('<li>id: "%s", name: "%s"</li>', $reportType['id'], $reportType['name']); } $htmlBody .= '</ul>'; return $reportTypes; } ?> <!doctype html> <html> <head> <title>Create a reporting job</title> </head> <body> <form method="GET"> <div> Job Name: <input type="text" id="jobName" name="jobName" placeholder="Enter Job Name"> </div> <br> <div> Report Type Id: <input type="text" id="reportTypeId" name="reportTypeId" placeholder="Enter Report Type Id"> </div> <br> <input type="submit" value="Create!"> </form> <?=$htmlBody?> </body> </html>
2. Örnek: Rapor alma
Kod örneği, raporlama işlerinin listesini almak için jobs.list
yöntemini çağırır. Daha sonra, jobId
parametresini belirli bir iş kimliğine ayarlayarak, söz konusu iş tarafından oluşturulan raporları almak için reports.list
yöntemini çağırır. Son olarak örnek, her raporun indirme URL'sini yazdırır.
<?php /** * This sample supports the following use cases: * * 1. Retrieve reporting jobs by content owner: * Ex: php retrieve_reports.php --contentOwner=="CONTENT_OWNER_ID" * Ex: php retrieve_reports.php --contentOwner=="CONTENT_OWNER_ID" --includeSystemManaged==True * 2. Retrieving list of downloadable reports for a particular job: * Ex: php retrieve_reports.php --contentOwner=="CONTENT_OWNER_ID" --jobId="JOB_ID" * 3. Download a report: * Ex: php retrieve_reports.php --contentOwner=="CONTENT_OWNER_ID" --downloadUrl="DOWNLOAD_URL" --outputFile="report.txt" */ /** * 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.2.0" in "' . __DIR__ .'"'); } require_once __DIR__ . '/vendor/autoload.php'; session_start(); define('CREDENTIALS_PATH', '~/.credentials/youtube-php.json'); $longOptions = array( 'contentOwner::', 'downloadUrl::', 'includeSystemManaged::', 'jobId::', 'outputFile::', ); $options = getopt('', $longOptions); $CONTENT_OWNER_ID = ($options['contentOwner'] ? $options['contentOwner'] : ''); $DOWNLOAD_URL = (array_key_exists('downloadUrl', $options) ? $options['downloadUrl'] : ''); $INCLUDE_SYSTEM_MANAGED = (array_key_exists('includeSystemManaged', $options) ? $options['includeSystemManaged'] : ''); $JOB_ID = (array_key_exists('jobId', $options) ? $options['jobId'] : ''); $OUTPUT_FILE = (array_key_exists('outputFile', $options) ? $options['outputFile'] : ''); /* * You can obtain an OAuth 2.0 client ID and client secret from the * {{ Google Cloud Console }} <{{ https://cloud.google.com/console }}> * 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. */ function getClient() { $client = new Google_Client(); $client->setAuthConfigFile('client_secrets_php.json'); $client->addScope( 'https://www.googleapis.com/auth/yt-analytics-monetary.readonly'); $client->setRedirectUri('urn:ietf:wg:oauth:2.0:oob'); $client->setAccessType('offline'); // Load previously authorized credentials from a file. $credentialsPath = expandHomeDirectory(CREDENTIALS_PATH); if (file_exists($credentialsPath)) { $accessToken = json_decode(file_get_contents($credentialsPath), true); } else { // Request authorization from the user. $authUrl = $client->createAuthUrl(); printf('Open the following link in your browser:\n%s\n', $authUrl); print 'Enter verification code: '; $authCode = trim(fgets(STDIN)); // Exchange authorization code for an access token. $accessToken = $client->authenticate($authCode); $refreshToken = $client->getRefreshToken(); // Store the credentials to disk. if(!file_exists(dirname($credentialsPath))) { mkdir(dirname($credentialsPath), 0700, true); } file_put_contents($credentialsPath, json_encode($accessToken)); printf('Credentials saved to %s\n', $credentialsPath); //fclose($fp); } $client->setAccessToken($accessToken); // Refresh the token if it's expired. if ($client->isAccessTokenExpired()) { $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken()); file_put_contents($credentialsPath, json_encode($client->getAccessToken())); } return $client; } /** * Expands the home directory alias '~' to the full path. * @param string $path the path to expand. * @return string the expanded path. */ function expandHomeDirectory($path) { $homeDirectory = getenv('HOME'); if (empty($homeDirectory)) { $homeDirectory = getenv('HOMEDRIVE') . getenv('HOMEPATH'); } return str_replace('~', realpath($homeDirectory), $path); } /** * Returns a list of reporting jobs. (jobs.listJobs) * * @param Google_Service_YouTubereporting $youtubeReporting YouTube Reporting service object. * @param string $onBehalfOfContentOwner A content owner ID. */ function listReportingJobs(Google_Service_YouTubeReporting $youtubeReporting, $onBehalfOfContentOwner = '', $includeSystemManaged = False) { $reportingJobs = $youtubeReporting->jobs->listJobs( array('onBehalfOfContentOwner' => $onBehalfOfContentOwner, 'includeSystemManaged' => $includeSystemManaged)); print ('REPORTING JOBS' . PHP_EOL . '**************' . PHP_EOL); foreach ($reportingJobs as $job) { print($job['reportTypeId'] . ':' . $job['id'] . PHP_EOL); } print(PHP_EOL); } /** * Lists reports created by a specific job. (reports.listJobsReports) * * @param Google_Service_YouTubereporting $youtubeReporting YouTube Reporting service object. * @param string $jobId The ID of the job. * @param string $onBehalfOfContentOwner A content owner ID. */ function listReportsForJob(Google_Service_YouTubeReporting $youtubeReporting, $jobId, $onBehalfOfContentOwner = '') { $reports = $youtubeReporting->jobs_reports->listJobsReports($jobId, array('onBehalfOfContentOwner' => $onBehalfOfContentOwner)); print ('DOWNLOADABLE REPORTS' . PHP_EOL . '********************' . PHP_EOL); foreach ($reports['reports'] as $report) { print('Created: ' . date('d M Y', strtotime($report['createTime'])) . ' (' . date('d M Y', strtotime($report['startTime'])) . ' to ' . date('d M Y', strtotime($report['endTime'])) . ')' . PHP_EOL . ' ' . $report['downloadUrl'] . PHP_EOL . PHP_EOL); } } /** * Download the report specified by the URL. (media.download) * * @param Google_Service_YouTubereporting $youtubeReporting YouTube Reporting service object. * @param string $reportUrl The URL of the report to be downloaded. * @param string $outputFile The file to write the report to locally. * @param $htmlBody - html body. */ function downloadReport(Google_Service_YouTubeReporting $youtubeReporting, $reportUrl, $outputFile) { $client = $youtubeReporting->getClient(); // Setting the defer flag to true tells the client to return a request that // can be called with ->execute(); instead of making the API call immediately. $client->setDefer(true); // Call YouTube Reporting API's media.download method to download a report. $request = $youtubeReporting->media->download('', array('alt' => 'media')); $request = $request->withUri(new \GuzzleHttp\Psr7\Uri($reportUrl)); $responseBody = ''; try { $response = $client->execute($request); $responseBody = $response->getBody(); } catch (Google_Service_Exception $e) { $responseBody = $e->getTrace()[0]['args'][0]->getResponseBody(); } file_put_contents($outputFile, $responseBody); $client->setDefer(false); } // Define an object that will be used to make all API requests. $client = getClient(); // YouTube Reporting object used to make YouTube Reporting API requests. $youtubeReporting = new Google_Service_YouTubeReporting($client); if ($CONTENT_OWNER_ID) { if (!$DOWNLOAD_URL && !$JOB_ID) { listReportingJobs($youtubeReporting, $CONTENT_OWNER_ID, $INCLUDE_SYSTEM_MANAGED); } else if ($JOB_ID) { listReportsForJob($youtubeReporting, $JOB_ID, $CONTENT_OWNER_ID); } else if ($DOWNLOAD_URL && $OUTPUT_FILE) { downloadReport($youtubeReporting, $DOWNLOAD_URL, $OUTPUT_FILE); } } ?>
Python
Aşağıdaki örneklerde Python istemci kitaplığı kullanılmaktadır.
1. Örnek: Raporlama işi oluşturma
Aşağıdaki kod örneği, kullanılabilir rapor türlerinin listesini almak için reportTypes.list
yöntemini çağırır. Ardından, yeni bir raporlama işi oluşturmak için jobs.create
yöntemini çağırır.
#!/usr/bin/python # Create a reporting job for the authenticated user's channel or # for a content owner that the user's account is linked to. # Usage example: # python create_reporting_job.py --name='<name>' # python create_reporting_job.py --content-owner='<CONTENT OWNER ID>' # python create_reporting_job.py --content-owner='<CONTENT_OWNER_ID>' --report-type='<REPORT_TYPE_ID>' --name='<REPORT_NAME>' import argparse import os import google.oauth2.credentials import google_auth_oauthlib.flow from googleapiclient.discovery import build from googleapiclient.errors import HttpError from google_auth_oauthlib.flow import InstalledAppFlow # 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 Cloud Console }} at # {{ https://cloud.google.com/console }}. # 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_secret.json' # 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. SCOPES = ['https://www.googleapis.com/auth/yt-analytics-monetary.readonly'] API_SERVICE_NAME = 'youtubereporting' API_VERSION = 'v1' # Authorize the request and store authorization credentials. def get_authenticated_service(): flow = InstalledAppFlow.from_client_secrets_file(CLIENT_SECRETS_FILE, SCOPES) credentials = flow.run_console() return build(API_SERVICE_NAME, API_VERSION, credentials = credentials) # Remove keyword arguments that are not set. def remove_empty_kwargs(**kwargs): good_kwargs = {} if kwargs is not None: for key, value in kwargs.iteritems(): if value: good_kwargs[key] = value return good_kwargs # Call the YouTube Reporting API's reportTypes.list method to retrieve report types. def list_report_types(youtube_reporting, **kwargs): # Provide keyword arguments that have values as request parameters. kwargs = remove_empty_kwargs(**kwargs) results = youtube_reporting.reportTypes().list(**kwargs).execute() reportTypes = results['reportTypes'] if 'reportTypes' in results and results['reportTypes']: reportTypes = results['reportTypes'] for reportType in reportTypes: print 'Report type id: %s\n name: %s\n' % (reportType['id'], reportType['name']) else: print 'No report types found' return False return True # Call the YouTube Reporting API's jobs.create method to create a job. def create_reporting_job(youtube_reporting, report_type_id, **kwargs): # Provide keyword arguments that have values as request parameters. kwargs = remove_empty_kwargs(**kwargs) reporting_job = youtube_reporting.jobs().create( body=dict( reportTypeId=args.report_type, name=args.name ), **kwargs ).execute() print ('Reporting job "%s" created for reporting type "%s" at "%s"' % (reporting_job['name'], reporting_job['reportTypeId'], reporting_job['createTime'])) # Prompt the user to enter a report type id for the job. Then return the id. def get_report_type_id_from_user(): report_type_id = raw_input('Please enter the reportTypeId for the job: ') print ('You chose "%s" as the report type Id for the job.' % report_type_id) return report_type_id # Prompt the user to set a job name def prompt_user_to_set_job_name(): job_name = raw_input('Please set a name for the job: ') print ('Great! "%s" is a memorable name for this job.' % job_name) return job_name if __name__ == '__main__': parser = argparse.ArgumentParser() # The 'name' option specifies the name that will be used for the reporting job. parser.add_argument('--content-owner', default='', help='ID of content owner for which you are retrieving jobs and reports.') parser.add_argument('--include-system-managed', default=False, help='Whether the API response should include system-managed reports') parser.add_argument('--name', default='', help='Name for the reporting job. The script prompts you to set a name ' + 'for the job if you do not provide one using this argument.') parser.add_argument('--report-type', default=None, help='The type of report for which you are creating a job.') args = parser.parse_args() youtube_reporting = get_authenticated_service() try: # Prompt user to select report type if they didn't set one on command line. if not args.report_type: if list_report_types(youtube_reporting, onBehalfOfContentOwner=args.content_owner, includeSystemManaged=args.include_system_managed): args.report_type = get_report_type_id_from_user() # Prompt user to set job name if not set on command line. if not args.name: args.name = prompt_user_to_set_job_name() # Create the job. if args.report_type: create_reporting_job(youtube_reporting, args, onBehalfOfContentOwner=args.content_owner) except HttpError, e: print 'An HTTP error %d occurred:\n%s' % (e.resp.status, e.content)
2. Örnek: Rapor alma
Kod örneği, raporlama işlerinin listesini almak için jobs.list
yöntemini çağırır. Daha sonra, jobId
parametresini belirli bir iş kimliğine ayarlayarak, söz konusu iş tarafından oluşturulan raporları almak için reports.list
yöntemini çağırır. Son olarak örnek, her raporun indirme URL'sini yazdırır.
#!/usr/bin/python ### # # This script retrieves YouTube Reporting API reports. Use cases: # 1. If you specify a report URL, the script downloads that report. # 2. Otherwise, if you specify a job ID, the script retrieves a list of # available reports for that job and prompts you to select a report. # Then it retrieves that report as in case 1. # 3. Otherwise, the list retrieves a list of jobs for the user or, # if specified, the content owner that the user is acting on behalf of. # Then it prompts the user to select a job, and then executes case 2 and # then case 1. # Usage examples: # python retrieve_reports.py --content_owner_id=<CONTENT_OWNER_ID> --local_file=<LOCAL_FILE> # python retrieve_reports.py --content_owner_id=<CONTENT_OWNER_ID> --job_id=<JOB_ID> --local_file=<LOCAL_FILE> # python retrieve_reports.py --content_owner_id=<CONTENT_OWNER_ID> --report_url=<REPORT_URL> --local_file=<LOCAL_FILE> # ### import argparse import os import google.oauth2.credentials import google_auth_oauthlib.flow from googleapiclient.discovery import build from googleapiclient.errors import HttpError from googleapiclient.http import MediaIoBaseDownload from google_auth_oauthlib.flow import InstalledAppFlow from io import FileIO # 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 Cloud Console }} at # {{ https://cloud.google.com/console }}. # 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_secret.json' # This OAuth 2.0 access scope allows for read access to YouTube Analytics # monetary reports for the authenticated user's account. Any request that # retrieves earnings or ad performance metrics must use this scope. SCOPES = ['https://www.googleapis.com/auth/yt-analytics-monetary.readonly'] API_SERVICE_NAME = 'youtubereporting' API_VERSION = 'v1' # Authorize the request and store authorization credentials. def get_authenticated_service(): flow = InstalledAppFlow.from_client_secrets_file(CLIENT_SECRETS_FILE, SCOPES) credentials = flow.run_console() return build(API_SERVICE_NAME, API_VERSION, credentials = credentials) # Remove keyword arguments that are not set. def remove_empty_kwargs(**kwargs): good_kwargs = {} if kwargs is not None: for key, value in kwargs.iteritems(): if value: good_kwargs[key] = value return good_kwargs # Call the YouTube Reporting API's jobs.list method to retrieve reporting jobs. def list_reporting_jobs(youtube_reporting, **kwargs): # Only include the onBehalfOfContentOwner keyword argument if the user # set a value for the --content_owner argument. kwargs = remove_empty_kwargs(**kwargs) # Retrieve the reporting jobs for the user (or content owner). results = youtube_reporting.jobs().list(**kwargs).execute() if 'jobs' in results and results['jobs']: jobs = results['jobs'] for job in jobs: print ('Reporting job id: %s\n name: %s\n for reporting type: %s\n' % (job['id'], job['name'], job['reportTypeId'])) else: print 'No jobs found' return False return True # Call the YouTube Reporting API's reports.list method to retrieve reports created by a job. def retrieve_reports(youtube_reporting, **kwargs): # Only include the onBehalfOfContentOwner keyword argument if the user # set a value for the --content_owner argument. kwargs = remove_empty_kwargs(**kwargs) # Retrieve available reports for the selected job. results = youtube_reporting.jobs().reports().list( **kwargs ).execute() if 'reports' in results and results['reports']: reports = results['reports'] for report in reports: print ('Report dates: %s to %s\n download URL: %s\n' % (report['startTime'], report['endTime'], report['downloadUrl'])) # Call the YouTube Reporting API's media.download method to download the report. def download_report(youtube_reporting, report_url, local_file): request = youtube_reporting.media().download( resourceName=' ' ) request.uri = report_url fh = FileIO(local_file, mode='wb') # Stream/download the report in a single request. downloader = MediaIoBaseDownload(fh, request, chunksize=-1) done = False while done is False: status, done = downloader.next_chunk() if status: print 'Download %d%%.' % int(status.progress() * 100) print 'Download Complete!' # Prompt the user to select a job and return the specified ID. def get_job_id_from_user(): job_id = raw_input('Please enter the job id for the report retrieval: ') print ('You chose "%s" as the job Id for the report retrieval.' % job_id) return job_id # Prompt the user to select a report URL and return the specified URL. def get_report_url_from_user(): report_url = raw_input('Please enter the report URL to download: ') print ('You chose "%s" to download.' % report_url) return report_url if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--content_owner', default='', help='ID of content owner for which you are retrieving jobs and reports') parser.add_argument('--job_id', default=None, help='ID of the job for which you are retrieving reports. If not ' + 'provided AND report_url is also not provided, then the script ' + 'calls jobs.list() to retrieve a list of jobs.') parser.add_argument('--report_url', default=None, help='URL of the report to retrieve. If not specified, the script ' + 'calls reports.list() to retrieve a list of reports for the ' + 'selected job.') parser.add_argument('--local_file', default='yt_report.txt', help='The name of the local file where the downloaded report will be written.') args = parser.parse_args() youtube_reporting = get_authenticated_service() try: # If the user has not specified a job ID or report URL, retrieve a list # of available jobs and prompt the user to select one. if not args.job_id and not args.report_url: if list_reporting_jobs(youtube_reporting, onBehalfOfContentOwner=args.content_owner): args.job_id = get_job_id_from_user() # If the user has not specified a report URL, retrieve a list of reports # available for the specified job and prompt the user to select one. if args.job_id and not args.report_url: retrieve_reports(youtube_reporting, jobId=args.job_id, onBehalfOfContentOwner=args.content_owner) args.report_url = get_report_url_from_user() # Download the selected report. if args.report_url: download_report(youtube_reporting, args.report_url, args.local_file) except HttpError, e: print 'An HTTP error %d occurred:\n%s' % (e.resp.status, e.content)