YouTube Reporting API - Data Model

अहम जानकारी: रोज़ की एपीआई रिपोर्ट और बैकफ़िल रिपोर्ट, जनरेट होने के 60 दिनों तक उपलब्ध रहती हैं. पुराने डेटा की रिपोर्ट, जनरेट होने के बाद 30 दिन तक उपलब्ध रहती हैं.

यह नीति, दुनिया भर में मौजूद सभी रिपोर्ट और रिपोर्टिंग जॉब पर लागू होती है. पूरी जानकारी के लिए, YouTube Reporting API का बदलाव का इतिहास देखें.

YouTube Reporting API, पहले से तय की गई रिपोर्ट के साथ काम करता है. इनमें किसी चैनल या कॉन्टेंट के मालिक के लिए, YouTube Analytics का पूरा डेटा मौजूद होता है. इन रिपोर्ट की मदद से, एक साथ कई ऐसे डेटा सेट डाउनलोड किए जा सकते हैं जिनके बारे में YouTube Analytics API या YouTube Studio के Analytics सेक्शन में क्वेरी की जा सकती है.

यह एपीआई, अपने-आप जनरेट होने वाली और सिस्टम से मैनेज की जाने वाली रिपोर्ट के सेट के साथ भी काम करता है. ये रिपोर्ट, कॉन्टेंट के उन मालिकों के लिए उपलब्ध होती हैं जिनके पास रिपोर्ट मेन्यू में, उनसे जुड़ी रिपोर्ट का ऐक्सेस होता है. इन रिपोर्ट में, विज्ञापन से मिलने वाले रेवेन्यू का डेटा और YouTube Premium की सदस्यता से मिलने वाले रेवेन्यू का डेटा शामिल होता है. ज़्यादा जानकारी के लिए, सिस्टम से मैनेज की जाने वाली रिपोर्ट का दस्तावेज़ देखें.

खास जानकारी

इन रिपोर्ट में रिपोर्ट फ़ील्ड को डाइमेंशन या मेट्रिक के तौर पर दिखाया जाता है:

  • डाइमेंशन ऐसे सामान्य मानदंड हैं जिनका इस्तेमाल डेटा को इकट्ठा करने के लिए किया जाता है. जैसे, कोई कार्रवाई होने की तारीख या वह देश जहां उपयोगकर्ता मौजूद थे. किसी रिपोर्ट में, डेटा की हर लाइन में डाइमेंशन वैल्यू का एक यूनीक कॉम्बिनेशन होता है.
  • मेट्रिक, उपयोगकर्ता गतिविधि, विज्ञापन की परफ़ॉर्मेंस या अनुमानित रेवेन्यू से जुड़े अलग-अलग मेज़रमेंट होती हैं. उपयोगकर्ता गतिविधि की मेट्रिक में, वीडियो को मिले व्यू की संख्या और रेटिंग (पसंद और नापसंद) जैसी चीज़ें शामिल होती हैं.

उदाहरण के लिए, चैनलों की बेसिक उपयोगकर्ता गतिविधि की रिपोर्ट में ये डाइमेंशन शामिल होते हैं:

  • day: गतिविधि होने की तारीख.
  • चैनल: गतिविधि से जुड़ा YouTube चैनल.
  • video: गतिविधि से जुड़ा YouTube वीडियो.
  • liveOrOnDemand: इस वैल्यू से पता चलता है कि दर्शक, लाइव वीडियो स्ट्रीम देख रहे थे या नहीं.
  • subscribedStatus: इस वैल्यू से पता चलता है कि दर्शकों ने चैनल की सदस्यता ली थी या नहीं.
  • country: वह देश जहां दर्शक मौजूद थे.

इस रिपोर्ट में कई मेट्रिक भी शामिल होती हैं, जैसे कि व्यू, पसंद, और averageViewDuration. रिपोर्ट को वापस पाने और इंपोर्ट करने के बाद, कोई ऐप्लिकेशन सामान्य डाइमेंशन वैल्यू के आधार पर कई अलग-अलग कैलकुलेशन कर सकता है.

उदाहरण के लिए, किसी खास तारीख पर जर्मनी में व्यू की कुल संख्या का पता लगाने के लिए, उन सभी लाइनों के व्यू मेट्रिक की वैल्यू को जोड़ें जिनमें देश कॉलम की वैल्यू DE है और दिन कॉलम की वैल्यू, YYYY-MM-DD फ़ॉर्मैट में तारीख है.

YouTube Analytics से रिपोर्ट पाना

एपीआई की मदद से चैनल और कॉन्टेंट के मालिक की रिपोर्ट पाने का तरीका यहां बताया गया है. उन रिपोर्ट को वापस पाने का तरीका जानने के लिए, सिस्टम से मैनेज की जाने वाली रिपोर्ट दस्तावेज़ देखें.

पहला चरण: अनुमति देने वाले क्रेडेंशियल वापस पाना

YouTube Reporting API के सभी अनुरोधों को अनुमति मिलना ज़रूरी है. अनुमति देने वाली गाइड में, अनुमति देने वाले टोकन वापस पाने के लिए, OAuth 2.0 प्रोटोकॉल का इस्तेमाल करने का तरीका बताया गया है.

YouTube Reporting API के अनुरोध, अनुमति देने के इन दायरों का इस्तेमाल करते हैं:

स्कोप
https://www.googleapis.com/auth/yt-analytics.readonly अपने YouTube कॉन्टेंट की YouTube Analytics रिपोर्ट देखें. इस दायरे की मदद से, उपयोगकर्ता गतिविधि की मेट्रिक को ऐक्सेस किया जा सकता है. जैसे, व्यू की संख्या और रेटिंग की संख्या.
https://www.googleapis.com/auth/yt-analytics-monetary.readonly अपने YouTube कॉन्टेंट के लिए YouTube Analytics की पैसे से जुड़ी रिपोर्ट देखना. इस स्कोप से, उपयोगकर्ता गतिविधि की मेट्रिक के साथ-साथ अनुमानित रेवेन्यू और विज्ञापन की परफ़ॉर्मेंस मेट्रिक का ऐक्सेस मिलता है.

दूसरा चरण: जिस रिपोर्ट को वापस पाना है उसकी पहचान करना

एपीआई के reportTypes.list तरीके का इस्तेमाल करके, ऐसी रिपोर्ट की सूची फिर से पाएं जिन्हें चैनल या कॉन्टेंट के मालिक के लिए जनरेट किया जा सकता है. यह तरीका, रिपोर्ट आईडी और नामों की सूची दिखाता है. उन रिपोर्ट के लिए id प्रॉपर्टी वैल्यू कैप्चर करें जो आपको जनरेट करनी हैं. उदाहरण के लिए, चैनलों के लिए बेसिक उपयोगकर्ता गतिविधि की रिपोर्ट का आईडी channel_basic_a1 है.

रिपोर्ट के नाम, चैनल की रिपोर्ट और कॉन्टेंट के मालिक की रिपोर्ट के बारे में जानकारी देने वाले दस्तावेज़ में भी देखे जा सकते हैं.

तीसरा चरण: रिपोर्टिंग जॉब बनाना

YouTube आपकी रिपोर्ट तब तक जनरेट नहीं करता, जब तक उस रिपोर्ट के लिए कोई रिपोर्टिंग जॉब नहीं बनाया जाता. (इसलिए, ये रिपोर्ट सिर्फ़ उन चैनलों और कॉन्टेंट मालिकों के लिए जनरेट की जाती हैं जो असल में उन्हें वापस पाना चाहते हैं.)

रिपोर्टिंग जॉब बनाने के लिए, एपीआई के jobs.create तरीके का इस्तेमाल करें. अनुरोध के मुख्य हिस्से में ये वैल्यू सेट करें:

  • reportTypeId प्रॉपर्टी की वैल्यू को उस रिपोर्ट आईडी पर सेट करें जिसे आपने दूसरे चरण में वापस पाया है.
  • name प्रॉपर्टी की वैल्यू को उस नाम पर सेट करें जिसे आपको रिपोर्ट के साथ जोड़ना है.

jobs.create तरीके के लिए एपीआई से मिले रिस्पॉन्स में एक Job रिसॉर्स शामिल होता है. यह रिसॉर्स, ID के बारे में बताता है, जो जॉब की खास तौर पर पहचान करता है. जॉब बनाए जाने के बाद 48 घंटों के अंदर रिपोर्ट वापस पाना शुरू किया जा सकता है और पहली उपलब्ध रिपोर्ट उस दिन के लिए होगी, जिस दिन आपने जॉब शेड्यूल किया था.

उदाहरण के लिए, अगर आपने 1 सितंबर को कोई काम शेड्यूल किया है, तो 1 सितंबर की रिपोर्ट 3 सितंबर को तैयार होगी. 2 सितंबर की रिपोर्ट 4 सितंबर को पोस्ट की जाएगी. इसके बाद, यह रिपोर्ट आगे भी जारी की जाएगी.

चौथा चरण: जॉब आईडी वापस पाना

ध्यान दें: अगर आपके ऐप्लिकेशन ने तीसरे चरण में दिए गए जॉब आईडी को सेव किया है, तो इस चरण को छोड़ा जा सकता है.

शेड्यूल की गई जॉब की सूची वापस पाने के लिए, jobs.list तरीके को कॉल करें. दिखाए गए हर Job संसाधन में मौजूद reportTypeId प्रॉपर्टी से पता चलता है कि जॉब से जनरेट की गई रिपोर्ट किस तरह की है. आपके ऐप्लिकेशन को अगले चरण में उसी संसाधन से id प्रॉपर्टी की वैल्यू चाहिए.

पांचवां चरण: रिपोर्ट के डाउनलोड किए गए यूआरएल को वापस पाना

जॉब के लिए बनाई गई रिपोर्ट की सूची दोबारा पाने के लिए jobs.reports.list तरीके को कॉल करें. अनुरोध में, jobId पैरामीटर को उस रिपोर्ट के जॉब आईडी पर सेट करें जिसे आपको वापस पाना है.

सलाह: createdAfter पैरामीटर का इस्तेमाल करके बताएं कि एपीआई को सिर्फ़ तय समय के बाद बनाई गई रिपोर्ट दिखानी चाहिए. इस पैरामीटर का इस्तेमाल यह पक्का करने के लिए किया जा सकता है कि एपीआई सिर्फ़ ऐसी रिपोर्ट दिखाता है जिन्हें आपने पहले से प्रोसेस नहीं किया है.

एपीआई के रिस्पॉन्स में उस काम के लिए, Report संसाधनों की एक सूची शामिल है. हर संसाधन एक रिपोर्ट से संबंधित होता है, जिसमें 24 घंटे की खास अवधि का डेटा मौजूद होता है. ध्यान दें कि YouTube, डाउनलोड की जा सकने वाली रिपोर्ट उन दिनों के लिए जनरेट करता है जिनमें कोई डेटा उपलब्ध नहीं था. उन रिपोर्ट में हेडर लाइन होती है, लेकिन उनमें अतिरिक्त डेटा नहीं होता.

  • संसाधन की startTime और endTime प्रॉपर्टी उस समयावधि की पहचान करती हैं जिसमें रिपोर्ट का डेटा शामिल होता है.
  • संसाधन की downloadUrl प्रॉपर्टी, उस यूआरएल की पहचान करती है जिससे रिपोर्ट फ़ेच की जा सकती है.
  • संसाधन की createTime प्रॉपर्टी, रिपोर्ट जनरेट होने की तारीख और समय की जानकारी देती है. आपके ऐप्लिकेशन को यह वैल्यू स्टोर करनी चाहिए. साथ ही, इसका इस्तेमाल यह तय करने के लिए करना चाहिए कि पहले से डाउनलोड की गई रिपोर्ट में बदलाव हुआ है या नहीं.

छठा चरण: रिपोर्ट डाउनलोड करना

रिपोर्ट को फिर से पाने के लिए, पांचवे चरण में मिले downloadUrl को एचटीटीपी GET अनुरोध भेजें.

डाउनलोड अनुरोधों पर gzip संपीड़न सक्षम करके, आप रिपोर्ट डाउनलोड करने के लिए आवश्यक बैंडविड्थ को कम कर सकते हैं. हालांकि, आपके ऐप्लिकेशन को एपीआई रिस्पॉन्स को कंप्रेस करने में ज़्यादा समय लग सकता है, लेकिन नेटवर्क के कम संसाधनों का इस्तेमाल करने का फ़ायदा, आम तौर पर लागत से ज़्यादा होता है.

gzip-कोड में बदला गया जवाब पाने के लिए, Accept-Encoding एचटीटीपी अनुरोध के हेडर को gzip पर सेट करें, जैसा कि इस उदाहरण में दिखाया गया है:

Accept-Encoding: gzip

रिपोर्ट प्रोसेस करना

सबसे सही तरीके

YouTube Reporting API का इस्तेमाल करने वाले ऐप्लिकेशन को हमेशा, इन तरीकों का पालन करना चाहिए:

  • रिपोर्ट के कॉलम का क्रम तय करने के लिए, रिपोर्ट की हेडर लाइन का इस्तेमाल करें. उदाहरण के लिए, अगर आपको लगता है कि रिपोर्ट की जानकारी में, आपकी सूची में शामिल पहली मेट्रिक व्यू होगी, तो उसे रिपोर्ट में दिखाई जाने वाली पहली मेट्रिक मानकर न मानें. इसके बजाय, रिपोर्ट की हेडर लाइन का इस्तेमाल करके यह तय करें कि किस कॉलम में वह डेटा है.

  • एक ही रिपोर्ट को बार-बार प्रोसेस करने से बचने के लिए, अपनी डाउनलोड की गई रिपोर्ट का रिकॉर्ड रखें. नीचे दी गई सूची में, ऐसा करने के कुछ तरीके बताए गए हैं.

    • reports.list तरीके को कॉल करते समय, किसी तय तारीख के बाद बनाई गई रिपोर्ट को वापस पाने के लिए, createdAfter पैरामीटर का इस्तेमाल करें. (पहली बार रिपोर्ट फिर से पाने पर createdAfter पैरामीटर छोड़ दें.)

      हर बार रिपोर्ट को पाने और उन्हें प्रोसेस करने पर, उन रिपोर्ट के बनाए जाने की तारीख और समय के टाइमस्टैंप को सेव करें. इसके बाद, reports.list तरीके पर लगातार होने वाले हर कॉल पर createdAfter पैरामीटर की वैल्यू अपडेट करें. इससे यह पक्का किया जा सकेगा कि हर बार एपीआई को कॉल करने पर, सिर्फ़ नई रिपोर्ट वापस पाई जा रही हैं. इनमें, बैकफ़िल किए गए डेटा वाली नई रिपोर्ट भी शामिल हैं.

      सुरक्षा के तौर पर, किसी रिपोर्ट को वापस पाने से पहले, यह पक्का करें कि रिपोर्ट का आईडी आपके डेटाबेस में पहले से मौजूद तो नहीं है.

    • हर उस रिपोर्ट का आईडी स्टोर करें जिसे आपने डाउनलोड और प्रोसेस किया है. आपके पास अतिरिक्त जानकारी भी सेव करने का विकल्प होता है. जैसे, हर रिपोर्ट जनरेट होने की तारीख और समय या रिपोर्ट की startTime और endTime जानकारी, दोनों को मिलाकर उस अवधि की पहचान की जा सकती है जिसके लिए रिपोर्ट में डेटा मौजूद है. ध्यान रखें कि हर काम में कई रिपोर्ट हो सकती हैं, क्योंकि हर रिपोर्ट में 24 घंटे का डेटा होता है.

      रिपोर्ट आईडी का इस्तेमाल करके, ऐसी रिपोर्ट की पहचान करें जिन्हें अब भी डाउनलोड और इंपोर्ट करना है. हालांकि, अगर दो नई रिपोर्ट में startTime और endTime प्रॉपर्टी की वैल्यू एक जैसी है, तो रिपोर्ट को सिर्फ़ नई createTime वैल्यू के साथ इंपोर्ट करें.

  • रिपोर्ट में YouTube के संसाधनों से जुड़े आईडी शामिल होते हैं. इन संसाधनों के लिए अतिरिक्त मेटाडेटा पाने के लिए, YouTube Data API का इस्तेमाल किया जा सकता है. जैसा कि YouTube API सेवाओं के डेवलपर के लिए बनी नीतियों (सेक्शन III.E.4.b से III.E.4.d तक) में बताया गया है, एपीआई क्लाइंट को 30 दिनों के बाद उस एपीआई से सेव किए गए संसाधन मेटाडेटा को मिटाना या रीफ़्रेश करना होगा.

रिपोर्ट की खास बातें

एपीआई रिपोर्ट, .csv (कॉमा लगाकर अलग की गई वैल्यू) वाली ऐसी फ़ाइलें होती हैं जिनमें नीचे दी गई विशेषताएं होती हैं:

  • हर रिपोर्ट में 24 घंटे की खास अवधि का डेटा शामिल होता है, जो पैसिफ़िक समय के मुताबिक रात 12:00 बजे से रात 11:59 बजे तक होता है. इसलिए, किसी भी रिपोर्ट में day डाइमेंशन वैल्यू हमेशा एक जैसी होती है.

  • रिपोर्ट हर दिन अपडेट होती हैं.

  • YouTube, डाउनलोड की जा सकने वाली रिपोर्ट उन दिनों के लिए जनरेट करता है जब कोई डेटा उपलब्ध नहीं था. उन रिपोर्ट में एक हेडर लाइन होगी, लेकिन उसमें अतिरिक्त डेटा नहीं होगा.

  • एपीआई रिपोर्ट, जनरेट होने के बाद 60 दिनों तक उपलब्ध रहती हैं. हालांकि, नए रिपोर्टिंग जॉब के लिए जनरेट किए गए पुराने डेटा को छोड़कर. रिपोर्ट को 60 दिनों से ज़्यादा पुरानी होने के बाद ऐक्सेस नहीं किया जा सकता. ऐसी रिपोर्ट जो पहले ही 60 दिन से ज़्यादा पुरानी हैं.
  • पुराना डेटा वाली रिपोर्ट, जनरेट होने के बाद 30 दिन तक उपलब्ध रहती हैं. ऐतिहासिक डेटा वाली रिपोर्ट को 30 दिन से ज़्यादा पुराना होने के बाद ऐक्सेस नहीं किया जा सकता.
  • रिपोर्ट का डेटा फ़िल्टर नहीं किया गया है. चैनल की रिपोर्ट में, चैनल के वीडियो या प्लेलिस्ट का पूरा डेटा शामिल होता है. हालांकि, इस रिपोर्ट में, मिटाए गए रिसॉर्स के बारे में नीचे दिया गया अपवाद भी है. इसी तरह, कॉन्टेंट के मालिक की रिपोर्ट में, कॉन्टेंट के मालिक के चैनलों (वीडियो, प्लेलिस्ट, विज्ञापन की परफ़ॉर्मेंस वगैरह) का पूरा डेटा शामिल होता है. हालांकि, इसमें ये अपवाद शामिल होते हैं.

    हालांकि, रिपोर्ट का डेटा फ़िल्टर नहीं किया जाता है, लेकिन रिपोर्ट में YouTube के ऐसे संसाधनों की जानकारी मौजूद नहीं होती जिन्हें रिपोर्ट जनरेट होने की तारीख से कम से कम 30 दिन पहले मिटाया गया था.

  • रिपोर्ट का डेटा क्रम से नहीं लगाया गया है.

  • रिपोर्ट में बिना मेट्रिक वाली पंक्तियां हटा दी जाती हैं. दूसरे शब्दों में, जिन लाइनों में कोई मेट्रिक नहीं होती उन्हें रिपोर्ट से बाहर रखा जाता है. उदाहरण के लिए, अगर किसी खास दिन अल्बानिया में किसी वीडियो को नहीं देखा गया है, तो उस दिन की रिपोर्ट में अल्बानिया के लिए लाइनें नहीं होंगी.

  • रिपोर्ट में मेट्रिक के लिए सारांश डेटा देने वाली पंक्तियां नहीं होतीं, जैसे किसी चैनल के सभी वीडियो को देखे जाने की कुल संख्या. इन कुल वैल्यू को रिपोर्ट में दी गई वैल्यू के कुल योग के तौर पर कैलकुलेट किया जा सकता है. हालांकि, हो सकता है कि इस कुल वैल्यू में, मिटाए गए वीडियो की मेट्रिक शामिल न हों, जैसा कि ऊपर बताया गया है. वीडियो की कुल संख्या जानने के लिए, YouTube Analytics API का भी इस्तेमाल किया जा सकता है. YouTube Analytics API कुल वैल्यू दिखाता है, जिनमें मिटाए गए संसाधनों की मेट्रिक शामिल होती हैं. भले ही, उन संसाधनों के बारे में एपीआई से मिले रिस्पॉन्स में साफ़ तौर पर जानकारी न दी गई हो.

डेटा बैकफ़िल करना

बैकफ़िल डेटा, ऐसे डेटा सेट की जगह लेता है जो पहले डिलीवर किए गए सेट की जगह लेता है. बैकफ़िल डेटा रिपोर्ट उपलब्ध होने पर, आपके ऐप्लिकेशन को नई रिपोर्ट फिर से हासिल करनी होगी. साथ ही, आपके सेव किए गए डेटा को अपडेट किए गए डेटा सेट के मुताबिक अपडेट करना होगा. उदाहरण के लिए, आपका ऐप्लिकेशन, रिपोर्ट में शामिल समयावधि के पिछले डेटा को मिटाकर नया डेटा सेट इंपोर्ट कर सकता है.

अगर YouTube के पास डेटा बैकफ़िल है, तो वह नए रिपोर्ट आईडी के साथ एक नई रिपोर्ट जनरेट करता है. ऐसे में, रिपोर्ट की startTime और endTime प्रॉपर्टी की वैल्यू, उस रिपोर्ट के शुरू और खत्म होने के समय से मेल खाएगी जो पहले उपलब्ध थी और जिसे आपने पहले डाउनलोड किया था.

बैकफ़िल रिपोर्ट में, YouTube के संसाधनों की ऐसी कोई पहचान फ़ाइल नहीं होती जिसे रिपोर्ट जनरेट होने की तारीख से कम से कम 30 दिन पहले मिटाया गया हो.

पुराना डेटा

रिपोर्टिंग का कोई नया जॉब शेड्यूल करने पर, YouTube उस दिन के बाद से ऐतिहासिक रिपोर्ट जनरेट करता है. साथ ही, जॉब को बनाए जाने से पहले की 30 दिनों की अवधि की रिपोर्ट जनरेट करता है. इसलिए, इस दस्तावेज़ में पुराने डेटा का मतलब उस रिपोर्ट से है जिसमें रिपोर्टिंग जॉब को शेड्यूल करने से पहले की किसी समयावधि का डेटा शामिल है.

ऐतिहासिक रिपोर्ट उपलब्ध होते ही उन्हें पोस्ट कर दिया जाता है. आम तौर पर, किसी काम के लिए सारा पुराना डेटा कुछ दिनों में पोस्ट कर दिया जाता है. जैसा कि रिपोर्ट की विशेषताएं सेक्शन में बताया गया है, पुराने डेटा वाली रिपोर्ट जनरेट होने के बाद 30 दिनों तक उपलब्ध रहती हैं. गैर-ऐतिहासिक डेटा वाली रिपोर्ट 60 दिनों तक उपलब्ध रहती हैं.

डेटा की पहचान छिपाना

YouTube दर्शकों की पहचान छिपाने के लिए, कुछ डाइमेंशन के लिए वैल्यू सिर्फ़ तब दिखाई जाती हैं, जब एक ही लाइन में कोई मेट्रिक तय की गई सीमा को पूरा करती हो.

उदाहरण के लिए, चैनलों के वीडियो के ट्रैफ़िक सोर्स की रिपोर्ट की हर लाइन में कई डाइमेंशन होते हैं. इनमें trafficSourceType और trafficSourceDetail शामिल होते हैं. हर लाइन में कई तरह की मेट्रिक भी होती हैं. इनमें व्यू भी शामिल होते हैं. YouTube खोज से मिले ट्रैफ़िक का ब्यौरा देने वाली लाइनों में, trafficSourceDetail डाइमेंशन उस खोज के लिए शब्द की पहचान करता है जिससे ट्रैफ़िक मिला.

इस उदाहरण में, नीचे दिए गए नियम लागू होते हैं:

  • ट्रैफ़िक सोर्स रिपोर्ट, क्वेरी के लिए इस्तेमाल किए गए शब्द (trafficSourceDetail) की पहचान सिर्फ़ तब करती है, जब इसकी वजह से किसी खास दिन पर किसी वीडियो को एक तय संख्या में व्यू मिले हों. इस मामले में, व्यू मेट्रिक है, वीडियो एग्रीगेट करने वाला डाइमेंशन है, और trafficSourceDetail पहचान छिपाने वाला डाइमेंशन है.

  • इस रिपोर्ट में एक और लाइन शामिल होती है, जो उन सभी trafficSourceDetail वैल्यू की मेट्रिक इकट्ठा करती है जो व्यू की संख्या के लिए तय की गई सीमा को पूरा नहीं करती. वह पंक्ति उन क्वेरी शब्दों से जुड़े व्यू की कुल संख्या को रिपोर्ट करती है, लेकिन शब्दों की पहचान नहीं करती.

इन टेबल में, इन नियमों को दिखाया गया है. पहली टेबल में रॉ डेटा का एक काल्पनिक सेट होता है, जिसका इस्तेमाल YouTube ट्रैफ़िक सोर्स की रिपोर्ट जनरेट करने के लिए करेगा. दूसरी टेबल में, रिपोर्ट को ही शामिल किया जाता है. इस उदाहरण में, व्यू की संख्या का थ्रेशोल्ड 10 है. इसका मतलब है कि रिपोर्ट, खोज के लिए इस्तेमाल हुए किसी शब्द की पहचान सिर्फ़ तब करती है, जब किसी खास दिन पर किसी वीडियो को कम से कम 10 व्यू मिले हों. (असल थ्रेशोल्ड में बदलाव किया जा सकता है.)

किसी वीडियो के लिए, YouTube Search के ट्रैफ़िक का रॉ डेटा

मान लें कि नीचे दिए गए डेटा में, किसी खास दिन पर किसी खास वीडियो पर आने वाले YouTube Search से मिले ट्रैफ़िक की जानकारी दी गई है.

खोज के लिए शब्द व्यू देखे जाने के अनुमानित मिनट
गैंगनैम स्टाइल 100 200
साई 15 25
साई गैंगनैम 9 15
ओपा गंगनाम 5 8
घुड़सवारी डांस 2 5

ट्रैफ़िक सोर्स की रिपोर्ट का सैंपल

यहां दी गई टेबल में, ट्रैफ़िक सोर्स की रिपोर्ट का वह हिस्सा दिखाया गया है जिसे YouTube, पिछले सेक्शन के रॉ डेटा के लिए जनरेट करेगा. (असल रिपोर्ट में ज़्यादा डाइमेंशन और मेट्रिक शामिल होंगी.) इस उदाहरण में, रिपोर्ट, खोज के लिए इस्तेमाल हुए शब्दों की पहचान सिर्फ़ तब करती है, जब उनकी वजह से कम से कम 10 व्यू मिले हों. असल थ्रेशोल्ड में बदलाव हो सकता है.

रिपोर्ट की तीसरी लाइन में, trafficSourceDetail डाइमेंशन की वैल्यू NULL है. views और estimatedMinutesWatched मेट्रिक में, खोज के लिए इस्तेमाल हुए तीन ऐसे शब्दों के लिए मिले कुल व्यू और देखने के कुल मिनट शामिल होते हैं जिनसे 10 से कम व्यू जनरेट हुए.

trafficSourceDetail व्यू estimatedMinutesWatched
गैंगनैम स्टाइल 100 200
साई 15 25
शून्य 16 28

डाइमेंशन की पहचान छिपाई जा सकती है

अगर मेट्रिक की वैल्यू तय की गई सीमा को पूरा नहीं करती हैं, तो यहां दी गई टेबल में उन डाइमेंशन वैल्यू की पहचान की गई है जिनकी पहचान छिपाई गई है. हर मामले में, मेट्रिक की वैल्यू दूसरे डाइमेंशन के ऊपर एग्रीगेट की जाती है. उदाहरण के लिए, अगर मेट्रिक व्यू है और एग्रीगेट किया जा रहा डाइमेंशन वीडियो है, तो डाइमेंशन वैल्यू में पहचान छिपा दी जाती है. ऐसा तब तक होता है, जब तक वीडियो को तय संख्या में नहीं देखा जाता.

मेट्रिक डाइमेंशन को एग्रीगेट करना पहचान छिपाने वाला डाइमेंशन पहचान छिपाने वाली वैल्यू
subscribersGained चैनल country ZZ
subscribersGained चैनल province US-ZZ
subscribersLost चैनल country ZZ
subscribersLost चैनल province US-ZZ
टिप्पणियां वीडियो country ZZ
टिप्पणियां वीडियो province US-ZZ
पसंद वीडियो country ZZ
पसंद वीडियो province US-ZZ
नापसंद वीडियो country ZZ
नापसंद वीडियो province US-ZZ
व्यू वीडियो ageGroup NULL
व्यू वीडियो लिंग NULL
व्यू video और trafficSourceDetail trafficSourceDetail NULL
चैनल के सदस्यों की संख्या चैनल subscribedStatus NULL

कोड सैंपल

नीचे दिए गए कोड सैंपल से पता चलता है कि रिपोर्टिंग जॉब बनाने के लिए, एपीआई का इस्तेमाल कैसे किया जाए और फिर उस जॉब के लिए रिपोर्ट कैसे हासिल की जाए. हर भाषा के लिए दो कोड सैंपल दिए गए हैं:

  1. पहला कोड सैंपल उपलब्ध रिपोर्ट टाइप की सूची को फिर से पाने और फिर नया रिपोर्टिंग जॉब बनाने का तरीका दिखाता है.

  2. दूसरे कोड सैंपल में, किसी खास काम के लिए रिपोर्ट पाने का तरीका बताया गया है. जॉब बनाए जाने के 48 घंटों के अंदर रिपोर्ट वापस पाना शुरू किया जा सकता है.

ध्यान दें: हो सकता है कि यहां दिए गए कोड सैंपल, इस्तेमाल की जा सकने वाली सभी प्रोग्रामिंग भाषाओं को न दिखाते हों. इस्तेमाल की जा सकने वाली भाषाओं की सूची देखने के लिए, क्लाइंट लाइब्रेरी के दस्तावेज़ देखें.

Java

नीचे दिए गए सैंपल, Java क्लाइंट लाइब्रेरी का इस्तेमाल करते हैं:

पहला उदाहरण: रिपोर्टिंग वाली जॉब बनाना

यहां दिया गया कोड सैंपल, उपलब्ध रिपोर्ट टाइप की सूची को वापस पाने के लिए reportTypes.list तरीके को कॉल करता है. इसके बाद, रिपोर्टिंग का नया जॉब बनाने के लिए, jobs.create तरीके को कॉल किया जाता है.

/*
 * 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;
    }
}

दूसरा उदाहरण: रिपोर्ट वापस पाना

रिपोर्टिंग जॉब की सूची वापस पाने के लिए, कोड सैंपल में jobs.list तरीके को कॉल किया जाता है. इसके बाद, यह jobId पैरामीटर के साथ reports.list तरीके को किसी खास जॉब आईडी पर सेट करता है, ताकि उस जॉब से बनाई गई रिपोर्ट वापस पाई जा सकें. आखिर में, सैंपल हर रिपोर्ट के डाउनलोड यूआरएल को प्रिंट करता है.

/*
 * 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

नीचे दिए गए सैंपल, PHP क्लाइंट लाइब्रेरी का इस्तेमाल करते हैं.

पहला उदाहरण: रिपोर्टिंग वाली जॉब बनाना

यहां दिया गया कोड सैंपल, उपलब्ध रिपोर्ट टाइप की सूची को वापस पाने के लिए reportTypes.list तरीके को कॉल करता है. इसके बाद, रिपोर्टिंग का नया जॉब बनाने के लिए, jobs.create तरीके को कॉल किया जाता है.

<?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>

दूसरा उदाहरण: रिपोर्ट वापस पाना

रिपोर्टिंग जॉब की सूची वापस पाने के लिए, कोड सैंपल में jobs.list तरीके को कॉल किया जाता है. इसके बाद, यह jobId पैरामीटर के साथ reports.list तरीके को किसी खास जॉब आईडी पर सेट करता है, ताकि उस जॉब से बनाई गई रिपोर्ट वापस पाई जा सकें. आखिर में, सैंपल हर रिपोर्ट के डाउनलोड यूआरएल को प्रिंट करता है.

<?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

नीचे दिए गए सैंपल, Python क्लाइंट लाइब्रेरी का इस्तेमाल करते हैं.

पहला उदाहरण: रिपोर्टिंग वाली जॉब बनाना

यहां दिया गया कोड सैंपल, उपलब्ध रिपोर्ट टाइप की सूची को वापस पाने के लिए reportTypes.list तरीके को कॉल करता है. इसके बाद, रिपोर्टिंग का नया जॉब बनाने के लिए, jobs.create तरीके को कॉल किया जाता है.

#!/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)

दूसरा उदाहरण: रिपोर्ट वापस पाना

रिपोर्टिंग जॉब की सूची वापस पाने के लिए, कोड सैंपल में jobs.list तरीके को कॉल किया जाता है. इसके बाद, यह jobId पैरामीटर के साथ reports.list तरीके को किसी खास जॉब आईडी पर सेट करता है, ताकि उस जॉब से बनाई गई रिपोर्ट वापस पाई जा सकें. आखिर में, सैंपल हर रिपोर्ट के डाउनलोड यूआरएल को प्रिंट करता है.

#!/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)