การเปลี่ยนแปลงนี้วางแผนที่จะมีผลบังคับใช้ในเดือนกรกฎาคม 2018 และนโยบายใหม่จะใช้กับทั่วโลกในรายงานและรายงานการรายงานทั้งหมด ดูรายละเอียดทั้งหมดเกี่ยวกับการเปลี่ยนแปลงนี้ได้จากประวัติการแก้ไข API
YouTube Reporting API รองรับรายงานที่กําหนดไว้ล่วงหน้าซึ่งมีชุดข้อมูล YouTube Analytics ที่ครอบคลุมสําหรับช่องหรือเจ้าของเนื้อหา รายงานเหล่านี้ช่วยให้คุณสามารถดาวน์โหลดชุดข้อมูลจํานวนมากที่คุณสามารถค้นหาด้วย YouTube Analytics API หรือในส่วน Analytics ของ Creator Studio
ภาพรวม
ช่องในรายงานในรายงานเหล่านี้อยู่ในรูปแบบมิติข้อมูลหรือเมตริก
- มิติข้อมูลเป็นเกณฑ์ทั่วไปที่ใช้รวบรวมข้อมูล เช่น วันที่ที่เกิดการดําเนินการ หรือประเทศที่ผู้ใช้อยู่ ในรายงาน ข้อมูลแต่ละแถวจะมีชุดค่าผสมของค่ามิติข้อมูลที่ไม่ซ้ํากัน
- เมตริก คือการวัดผลที่เกี่ยวข้องกับกิจกรรมของผู้ใช้ ประสิทธิภาพโฆษณา หรือรายได้โดยประมาณ เมตริกกิจกรรมของผู้ใช้ ได้แก่ จํานวนการดูและการให้คะแนนวิดีโอ (การกดชอบและไม่ชอบ)
เช่น รายงานกิจกรรมของผู้ใช้พื้นฐานสําหรับช่องจะมีมิติข้อมูลต่อไปนี้
- date: วันที่ที่กิจกรรมเกิดขึ้น
- channel_id: ช่อง YouTube ที่เชื่อมโยงกับกิจกรรม
- video_id: วิดีโอ YouTube ที่เชื่อมโยงกับกิจกรรม
- live_or_on_Demand: ค่าที่บ่งบอกว่าผู้ชมดูสตรีมวิดีโอแบบสดหรือไม่
- subscribed_status: ค่าที่บ่งบอกว่าผู้ชมได้ติดตามช่องหรือไม่
- country_code: ประเทศที่ผู้ชมอาศัยอยู่
รายงานยังมีเมตริกจํานวนมาก เช่น ยอดดู การกดชอบ และค่าเฉลี่ยระยะเวลาการดู_วินาที หลังจากดึงข้อมูลและนําเข้ารายงานแล้ว แอปพลิเคชันอาจสร้างการคํานวณที่หลากหลายโดยอิงจากค่ามิติข้อมูลทั่วไป
การเรียกดูรายงาน YouTube Analytics
ขั้นตอนที่ 1: เรียกดูข้อมูลเข้าสู่ระบบการให้สิทธิ์
คําขอ API การรายงานของ YouTube ทั้งหมดต้องได้รับอนุญาต โปรดดูคู่มือการให้สิทธิ์ซึ่งอธิบายวิธีใช้โปรโตคอล OAuth 2.0 เพื่อเรียกข้อมูลโทเค็นการให้สิทธิ์
คําขอ API การรายงานของ YouTube ใช้ขอบเขตการให้สิทธิ์ต่อไปนี้
กล้องติดปืน | |
---|---|
https://www.googleapis.com/auth/yt-analytics.readonly | ดูรายงาน YouTube Analytics สําหรับเนื้อหา YouTube ของคุณ ขอบเขตนี้จะช่วยให้เข้าถึงเมตริกกิจกรรมของผู้ใช้ เช่น จํานวนการดูและการให้คะแนน |
https://www.googleapis.com/auth/yt-analytics-monetary.readonly | ดูรายงานทางการเงินของ YouTube Analytics สําหรับเนื้อหา YouTube ของคุณ ขอบเขตนี้จะทําให้คุณเข้าถึงเมตริกกิจกรรมของผู้ใช้และเมตริกรายได้โดยประมาณและประสิทธิภาพของโฆษณาได้ |
ขั้นตอนที่ 2: ระบุรายงานที่จะดึงข้อมูล
เรียกใช้เมธอด reportTypes.list
ของ API เพื่อเรียกรายการรายงานที่สามารถสร้างขึ้นสําหรับช่องหรือเจ้าของเนื้อหา เมธอดนี้จะแสดงรายการรหัสและชื่อรายงาน บันทึกค่าพร็อพเพอร์ตี้ id
สําหรับรายงานที่ต้องการสร้าง เช่น รหัสของรายงานกิจกรรมของผู้ใช้พื้นฐานสําหรับช่องคือ channel_basic_a1
นอกจากนี้ คุณยังดูชื่อรายงานได้ในเอกสารประกอบซึ่งกําหนดรายงานช่องที่รองรับและรายงานเจ้าของเนื้อหา
ขั้นตอนที่ 3: สร้างงานการรายงาน
YouTube จะไม่เริ่มสร้างรายงานของคุณจนกว่าคุณจะสร้างงานการรายงานสําหรับรายงานนั้น (ดังนั้น รายงานจึงสร้างขึ้นสําหรับช่องและเจ้าของเนื้อหาที่ต้องการเรียกข้อมูลจริงๆ เท่านั้น)
หากต้องการสร้างงานการรายงาน ให้เรียกใช้เมธอด jobs.create
ของ API กําหนดค่าต่อไปนี้ในส่วนเนื้อหาของคําขอ
- ตั้งค่าพร็อพเพอร์ตี้
reportTypeId
เป็นรหัสรายงานที่ดึงมาในขั้นตอนที่ 2 - ตั้งค่าพร็อพเพอร์ตี้
name
เป็นชื่อที่คุณต้องการเชื่อมโยงกับรายงาน
การตอบกลับ API สําหรับเมธอด jobs.create
มีทรัพยากร Job
ซึ่งระบุ ID
ที่ระบุงานที่ไม่ซ้ํากัน คุณจะเริ่มเรียกข้อมูลรายงานได้ภายใน 48 ชั่วโมงหลังจากสร้างงาน และรายงานฉบับแรกที่มีอยู่จะเป็นวันที่คุณกําหนดเวลางานนั้น
ตัวอย่างเช่น หากคุณกําหนดเวลางานในวันที่ 1 กันยายน 2015 รายงานของวันที่ 1 กันยายน 2015 ก็จะพร้อมในวันที่ 3 กันยายน 2015 รายงานสําหรับวันที่ 2 กันยายน 2015 จะโพสต์ในวันที่ 4 กันยายน 2015 เป็นต้น
ขั้นตอนที่ 4: ดึงข้อมูลรหัสงาน
หมายเหตุ: หากแอปพลิเคชันของคุณจัดเก็บรหัสงานที่แสดงผลในขั้นตอนที่ 3 ให้ข้ามขั้นตอนนี้
เรียกใช้เมธอด jobs.list
เพื่อเรียกข้อมูลรายการงานที่กําหนดเวลาไว้ พร็อพเพอร์ตี้ reportTypeId
ในทรัพยากร Job
ที่แสดงผลแต่ละรายการจะระบุประเภทของรายงานที่งานนั้นสร้าง แอปพลิเคชันของคุณต้องมีค่าพร็อพเพอร์ตี้ id
จากทรัพยากรเดียวกันในขั้นตอนต่อไปนี้
ขั้นตอนที่ 5: เรียกดู URL การดาวน์โหลดของรายงาน
เรียกใช้เมธอด jobs.reports.list
เพื่อดึงรายการรายงานที่สร้างขึ้นสําหรับงานนี้ ในคําขอ ให้ตั้งค่าพารามิเตอร์ jobId
เป็นรหัสงานของรายงานที่คุณต้องการเรียกข้อมูล
เคล็ดลับ: ใช้พารามิเตอร์ createdAfter
เพื่อระบุว่า API ควรส่งคืนเฉพาะรายงานที่สร้างขึ้นหลังจากเวลาที่ระบุเท่านั้น พารามิเตอร์นี้ใช้เพื่อให้ API แสดงผลเฉพาะรายงานที่คุณยังไม่ได้รับการประมวลผล
การตอบกลับ API มีรายการทรัพยากร Report
สําหรับงานนั้น ทรัพยากรแต่ละรายการหมายถึงรายงานที่มีข้อมูลในช่วงเวลา 24 ชั่วโมงที่ไม่ซ้ํากัน โปรดทราบว่า YouTube จะสร้างรายงานที่ดาวน์โหลดได้สําหรับวันที่ไม่มีข้อมูล รายงานเหล่านี้มีแถวส่วนหัวแต่ไม่มีข้อมูลเพิ่มเติม
- พร็อพเพอร์ตี้
startTime
และendTime
ของทรัพยากรจะระบุระยะเวลาที่ข้อมูลของรายงานครอบคลุม - พร็อพเพอร์ตี้
downloadUrl
ของทรัพยากรจะระบุ URL ที่ดึงข้อมูลรายงานได้ - พร็อพเพอร์ตี้
createTime
ของทรัพยากรจะระบุวันที่และเวลาที่สร้างรายงาน แอปพลิเคชันของคุณควรจัดเก็บค่านี้ไว้ และใช้เพื่อระบุว่ารายงานที่ดาวน์โหลดก่อนหน้านี้มีการเปลี่ยนแปลงหรือไม่
ขั้นตอนที่ 6: ดาวน์โหลดรายงาน
ส่งคําขอ HTTP GET ไปยัง downloadUrl
ที่ได้รับในขั้นตอนที่ 5 เพื่อดึงรายงาน
คุณสามารถลดแบนด์วิดท์ที่จําเป็นในการดาวน์โหลดรายงานด้วยการเปิดใช้การบีบอัด gzip ในคําขอดาวน์โหลด แม้ว่าแอปพลิเคชันจะต้องใช้เวลา CPU มากขึ้นในการบีบอัดการตอบสนองของ API แต่การใช้ทรัพยากรเครือข่ายน้อยลงมักมีน้ําหนักเกินต้นทุนนั้นมีประโยชน์มาก
หากต้องการได้รับการตอบกลับที่เข้ารหัสแบบ gzip ให้ตั้งค่าส่วนหัวของคําขอ HTTP Accept-Encoding
เป็น gzip
ดังที่แสดงในตัวอย่างต่อไปนี้
Accept-Encoding: gzip
รายงานการประมวลผล
แนวทางปฏิบัติแนะนำ
แอปพลิเคชันที่ใช้ YouTube Reporting API ควรทําตามแนวทางปฏิบัติต่อไปนี้เสมอ
-
ใช้แถวส่วนหัวของรายงานเพื่อกําหนดลําดับคอลัมน์ของรายงาน ตัวอย่างเช่น อย่าสมมติว่าข้อมูลพร็อพเพอร์ตี้จะเป็นเมตริกแรกที่แสดงในรายงาน เนื่องจากเป็นเมตริกแรกที่แสดงในคําอธิบายรายงาน แต่ให้ใช้แถวส่วนหัวของรายงานเพื่อดูว่าคอลัมน์ใดมีข้อมูลดังกล่าวแทน
-
เก็บบันทึกของรายงานที่คุณดาวน์โหลดเพื่อหลีกเลี่ยงการประมวลผลรายงานเดิมซ้ําๆ โดยรายการที่แนะนําจะแนะนําให้ทําดังนี้
-
เมื่อเรียกใช้เมธอด
reports.list
ให้ใช้พารามิเตอร์ createdAfter เพื่อดึงข้อมูลรายงานที่สร้างขึ้นหลังวันที่ที่กําหนดเท่านั้น (ละเว้นพารามิเตอร์createdAfter
ในครั้งแรกที่ดึงรายงาน)ทุกครั้งที่เรียกข้อมูลและประมวลผลรายงานสําเร็จ ให้จัดเก็บการประทับเวลาที่สอดคล้องกับวันที่และเวลาเมื่อมีการสร้างรายงานใหม่ที่สุด จากนั้นอัปเดตค่าพารามิเตอร์
createdAfter
ในการเรียกครั้งต่อไปด้วยเมธอดreports.list
เพื่อให้แน่ใจว่าคุณจะดึงเฉพาะรายงานใหม่ ซึ่งรวมถึงรายงานใหม่ที่มีข้อมูลที่ทดแทนใหม่ทุกครั้งที่เรียก APIก่อนที่จะเรียกข้อมูลรายงาน ให้ตรวจสอบด้วยว่าไม่มีรหัสของรายงานอยู่ในฐานข้อมูล
-
จัดเก็บรหัสของแต่ละรายงานที่คุณดาวน์โหลดและประมวลผล นอกจากนี้ คุณยังจัดเก็บข้อมูลเพิ่มเติมได้ เช่น วันที่และเวลาที่สร้างรายงานแต่ละครั้ง หรือ
startTime
และendTime
ของรายงาน ซึ่งจะระบุระยะเวลาที่รายงานมีข้อมูล โปรดทราบว่าแต่ละงานมักมีรายงานจํานวนมากเนื่องจากแต่ละรายงานมีข้อมูลตลอด 24 ชั่วโมงใช้รหัสรายงานเพื่อระบุรายงานที่คุณยังคงต้องดาวน์โหลดและนําเข้า อย่างไรก็ตาม หากรายงานใหม่ 2 รายการมีค่าพร็อพเพอร์ตี้
startTime
และendTime
เดียวกัน ให้นําเข้ารายงานที่มีค่าcreateTime
ใหม่กว่าเท่านั้น
-
-
โดยรายงานจะมีรหัสที่เชื่อมโยงกับทรัพยากรของ YouTube และคุณสามารถใช้ YouTube Data API เพื่อดึงข้อมูลเมตาเพิ่มเติมสําหรับทรัพยากรเหล่านั้นได้ ตามที่ระบุไว้ในนโยบายนักพัฒนาซอฟต์แวร์บริการ API ของ YouTube (ส่วนที่ 3.E.4.b ถึง III.E.4.d) ไคลเอ็นต์ API จะต้องลบหรือรีเฟรชข้อมูลเมตาของทรัพยากรที่จัดเก็บไว้จาก API ดังกล่าวหลังจากผ่านไป 30 วัน
ลักษณะเฉพาะของรายงาน
รายงาน API คือไฟล์เวอร์ชัน .csv
(ค่าที่คั่นด้วยคอมมา) ที่มีลักษณะต่อไปนี้
-
แต่ละรายงานมีข้อมูลสําหรับระยะเวลา 24 ชั่วโมงที่ไม่ซ้ํากัน ซึ่งมีระยะเวลาตั้งแต่ 00:00 น. ถึง 23:59 น. ตามเวลาแปซิฟิก ด้วยเหตุนี้ ในรายงานหนึ่งๆ ค่ามิติข้อมูลวันที่จึงเท่ากันเสมอ
-
รายงานจะอัปเดตทุกวัน
-
YouTube จะสร้างรายงานที่ดาวน์โหลดได้สําหรับวันที่ไม่มีข้อมูล รายงานเหล่านี้จะมีแถวส่วนหัวแต่ไม่มีข้อมูลเพิ่มเติม
-
สําคัญ: การเปลี่ยนแปลงนโยบายที่กําลังจะเกิดขึ้นจะส่งผลต่อระยะเวลาที่คุณจะเรียกข้อมูลรายงาน YouTube Reporting API ได้ ปัจจุบันการเปลี่ยนแปลงดังกล่าวมีกําหนดเวลาที่จะมีผลในเดือนกรกฎาคม 2018 และจะมีผลกับรายงานและงานการรายงานทั้งหมดทั่วโลก
- ก่อนการเปลี่ยนแปลง รายงาน API จะใช้งานได้นานถึง 180 วันนับจากวันที่สร้าง
- หลังจากการเปลี่ยนแปลง รายงาน API จะใช้งานได้เป็นเวลา 60 วันนับจากวันที่สร้าง ยกเว้นข้อมูลย้อนหลังที่สร้างขึ้นสําหรับงานการรายงานใหม่ รายงานที่มีอายุเกิน 60 วันแล้วจะไม่มีสิทธิ์เข้าถึงอีกต่อไปเมื่อการเปลี่ยนแปลงนโยบายมีผล
- หลังการเปลี่ยนแปลง รายงานที่มีข้อมูลย้อนหลังจะดูได้เป็นเวลา 30 วันนับจากวันที่สร้าง รายงานที่มีข้อมูลย้อนหลังและมีอายุเกิน 30 วันแล้ว จะไม่มีสิทธิ์เข้าถึงอีกต่อไปเมื่อการเปลี่ยนแปลงนโยบายมีผล
-
ไม่มีการกรองข้อมูลรายงาน ด้วยเหตุนี้ รายงานช่องจะมีข้อมูลทั้งหมดสําหรับวิดีโอหรือเพลย์ลิสต์ของช่อง โดยมีข้อยกเว้นในย่อหน้าต่อไปนี้ซึ่งเกี่ยวข้องกับแหล่งข้อมูลที่ลบไปแล้ว ในทํานองเดียวกัน รายงานเจ้าของเนื้อหาจะมีข้อมูลทั้งหมดสําหรับช่องของเจ้าของเนื้อหา (วิดีโอ เพลย์ลิสต์ ประสิทธิภาพของโฆษณา ฯลฯ) โดยมีข้อยกเว้นต่อไปนี้
แม้ว่าข้อมูลรายงานจะไม่ได้รับการกรอง แต่รายงานที่มีข้อมูลในช่วงระยะเวลา 1 มิถุนายน 2018 เป็นต้นไปจะไม่มีการอ้างอิงไปยังทรัพยากร YouTube ที่ถูกลบไปแล้วอย่างน้อย 30 วันก่อนวันที่สร้างรายงาน
-
ไม่ได้จัดเรียงข้อมูลรายงาน
-
รายงานจะข้ามแถวที่ไม่มีเมตริก กล่าวคือ แถวที่ไม่มีเมตริกจะไม่รวมอยู่ในรายงาน ตัวอย่างเช่น หากวิดีโอไม่มียอดดูในแอลเบเนียในวันหนึ่งๆ รายงานของวันนั้นจะไม่มีแถวสําหรับแอลเบเนีย
-
รายงานจะไม่มีแถวที่ให้ข้อมูลสรุปสําหรับเมตริก เช่น จํานวนการดูรวมสําหรับวิดีโอทั้งหมดของช่อง คุณสามารถคํานวณค่ารวมเหล่านั้นเป็นผลรวมของมูลค่าในรายงานได้ แต่ผลรวมดังกล่าวอาจไม่มีเมตริกสําหรับวิดีโอที่ลบไปแล้วตามที่ระบุไว้ข้างต้น คุณยังใช้ YouTube Analytics API เพื่อดึงจํานวนรวมของได้อีกด้วย API ของ YouTube Analytics จะแสดงค่ารวมที่มีเมตริกสําหรับทรัพยากรที่ถูกลบ แม้ว่าทรัพยากรเหล่านั้นจะไม่ได้รับการอ้างอิงอย่างชัดเจนในการตอบกลับ API
ข้อมูลโฆษณาทดแทน
ข้อมูลโฆษณาทดแทนหมายถึงชุดข้อมูลที่ใช้แทนที่ชุดโฆษณาที่แสดงก่อนหน้านี้ เมื่อมีข้อมูลโฆษณาทดแทนพร้อมใช้งาน แอปพลิเคชันของคุณควรเรียกข้อมูลรายงานใหม่และอัปเดตข้อมูลที่จัดเก็บไว้ให้ตรงกับชุดข้อมูลที่มีการแก้ไข ตัวอย่างเช่น แอปพลิเคชันของคุณอาจลบข้อมูลก่อนหน้านี้สําหรับระยะเวลาที่ครอบคลุมในรายงาน แล้วนําเข้าชุดข้อมูลใหม่
หาก YouTube มีข้อมูลโฆษณาทดแทน ระบบจะสร้างรายงานใหม่ที่มีรหัสรายงานใหม่ ในกรณีดังกล่าว ค่าพร็อพเพอร์ตี้ startTime
และ endTime
ของรายงานจะตรงกับเวลาเริ่มต้นและเวลาสิ้นสุดของรายงานที่มีอยู่ก่อนหน้านี้ และคุณอาจดาวน์โหลดไว้ก่อนหน้านี้
รายงานโฆษณาทดแทนที่มีข้อมูลในช่วงระยะเวลา 1 มิถุนายน 2018 เป็นต้นไปจะไม่มีการอ้างอิงทรัพยากรของ YouTube ที่ถูกลบไปแล้วอย่างน้อย 30 วันก่อนวันที่สร้างรายงาน
ข้อมูลประวัติ
เมื่อคุณกําหนดเวลางานการรายงานใหม่ YouTube จะสร้างรายงานข้อมูลย้อนหลังที่ครอบคลุมระยะเวลาก่อนที่คุณจะสร้างงาน ดังนั้นในเอกสารนี้ ข้อมูลย้อนหลังหมายถึงรายงานที่มีข้อมูลเป็นระยะเวลาหนึ่งก่อนที่จะมีการตั้งเวลางานการรายงาน
สําคัญ: การเปลี่ยนแปลงนโยบายที่กําลังจะเกิดขึ้นจะส่งผลต่อระยะเวลาในการสร้างข้อมูลรายงานย้อนหลัง ปัจจุบันการเปลี่ยนแปลงดังกล่าวมีกําหนดเวลาที่จะมีผลในเดือนกรกฎาคม 2018 และจะมีผลกับรายงานและงานการรายงานทั้งหมดทั่วโลก
- ก่อนการเปลี่ยนแปลงนโยบาย เมื่อคุณตั้งเวลาการรายงานงานใหม่ YouTube จะสร้างรายงานที่ครอบคลุมระยะเวลา 180 วันก่อนเวลาที่คุณสร้างงานดังกล่าว
- หลังจากเปลี่ยนแปลงนโยบาย เมื่อคุณกําหนดเวลางานการรายงานใหม่ YouTube จะสร้างรายงานจากวันดังกล่าวเป็นต้นไป และครอบคลุมระยะเวลา 30 วันก่อนเวลาที่คุณสร้างงาน
ระบบจะโพสต์รายงานข้อมูลย้อนหลังทันทีที่ทําได้ โดยปกติแล้ว ระบบจะโพสต์ข้อมูลย้อนหลังทั้งหมดสําหรับงานภายใน 2-3 วัน ตามที่อธิบายไว้ในส่วนลักษณะของรายงาน หลังจากการเปลี่ยนแปลงนโยบายที่นโยบายจะมีผลบังคับใช้ในเดือนกรกฎาคม 2018 รายงานที่มีข้อมูลย้อนหลังจะใช้ได้เป็นเวลา 30 วันนับจากวันที่สร้าง รายงานที่มีข้อมูลในอดีตจะไม่มีให้ใช้งานเป็นเวลา 60 วันหลังจากการเปลี่ยนแปลงนโยบาย
การลบข้อมูลระบุตัวบุคคล
ค่ามิติข้อมูลบางรายการจะปรากฏก็ต่อเมื่อเมตริกในแถวเดียวกันเป็นไปตามเกณฑ์ที่กําหนดเท่านั้นเพื่อให้ข้อมูลระบุตัวบุคคลของผู้ชม YouTube ไม่ได้
ตัวอย่างเช่น ในรายงานแหล่งที่มาของการเข้าชมวิดีโอสําหรับแชแนล แต่ละแถวจะมีมิติข้อมูลจํานวนมาก เช่น traffic_source_type และ traffic_source_detail และแต่ละแถวยังมีเมตริกต่างๆ ซึ่งรวมถึงยอดดู ในแถวที่อธิบายการเข้าชมที่เกิดจากการค้นหาของ YouTube มิติข้อมูล traffic_source_detail จะระบุข้อความค้นหาที่ทําให้เกิดการเข้าชม
ในตัวอย่างนี้ กฎต่อไปนี้มีผลใช้งาน
-
รายงานแหล่งที่มาของการเข้าชมจะระบุข้อความค้นหา (traffic_source_detail) เฉพาะเมื่อนําไปสู่ยอดดูวิดีโอหนึ่งๆ อย่างน้อย 1 ครั้งในวันที่หนึ่งๆ ในกรณีนี้ view คือเมตริก video_id คือมิติข้อมูลรวม และ traffic_source_detail เป็นมิติข้อมูลที่ไม่ระบุตัวตน
-
รายงานมีแถวเพิ่มเติมที่รวบรวมเมตริกสําหรับค่า traffic_source_detail ทั้งหมดที่ไม่เป็นไปตามเกณฑ์ยอดดู แถวนั้นรายงานจํานวนการดูทั้งหมดที่เชื่อมโยงกับข้อความค้นหาเหล่านั้น แต่ไม่ได้ระบุข้อความค้นหา
ตารางต่อไปนี้แสดงให้เห็นถึงกฎเหล่านี้ ตารางแรกมีชุดข้อมูลสมมติที่ YouTube จะใช้เพื่อสร้างรายงานแหล่งที่มาของการเข้าชม ส่วนตารางที่ 2 ประกอบด้วยรายงานนั้น ในตัวอย่างนี้ เกณฑ์ยอดดูคือ 10 หมายความว่ารายงานจะระบุข้อความค้นหาก็ต่อเมื่อวิดีโอมียอดดูอย่างน้อย 10 ครั้งในวันหนึ่งๆ เท่านั้น (เกณฑ์จริงอาจมีการเปลี่ยนแปลง)
ข้อมูลดิบเกี่ยวกับการเข้าชมจากการค้นหาของ YouTube สําหรับวิดีโอ
สมมติว่าข้อมูลด้านล่างอธิบายถึงการเข้าชมจากการค้นหาของ YouTube ของวิดีโอหนึ่งๆ ในวันที่เลือก
ข้อความค้นหา | ครั้ง | จำนวนนาทีที่ดูโดยประมาณ |
---|---|---|
สไตล์คังนัม | 100 | 200 |
ไซ | 15 | 25 |
แก๊ง ไซส์ | 9 | 15 |
Opp Gangnam | 5 | 8 |
ขี่ม้า | 2 | 5 |
ตัวอย่างรายงานแหล่งที่มาของการเข้าชม
ตารางต่อไปนี้แสดงข้อความที่ตัดตอนมาจากรายงานแหล่งที่มาของการเข้าชมซึ่ง YouTube จะสร้างสําหรับข้อมูลดิบในส่วนก่อนหน้า (รายงานจริงจะมีมิติข้อมูลและเมตริกมากกว่า) ในตัวอย่างนี้ รายงานจะระบุข้อความค้นหาก็ต่อเมื่อทําให้เกิดการดูอย่างน้อย 10 ครั้งเท่านั้น เกณฑ์จริงอาจเปลี่ยนแปลงได้
ในแถวที่ 3 ของรายงาน ค่ามิติข้อมูล trafficSourceDetail
คือ NULL
เมตริก views
และ estimatedMinutesWatched
ประกอบด้วยการดูแบบรวมและนาทีที่ดูของข้อความค้นหา 3 รายการที่สร้างยอดดูน้อยกว่า 10 ครั้ง
รายละเอียดแหล่งที่มาของการเข้าชม | ครั้ง | จํานวนนาทีที่ดูโดยประมาณ |
---|---|---|
สไตล์คังนัม | 100 | 200 |
ไซ | 15 | 25 |
NULL | 16 | 28 |
มิติข้อมูลที่ลบข้อมูลระบุตัวบุคคล
ตารางต่อไปนี้จะระบุค่ามิติข้อมูลที่มีการลบข้อมูลระบุตัวบุคคลหากค่าเมตริกที่เกี่ยวข้องไม่เป็นไปตามเกณฑ์ที่กําหนด ในแต่ละกรณี ค่าเมตริกจะรวมอยู่ในมิติข้อมูลอื่น เช่น หากเมตริกคือยอดดู และมิติข้อมูลรวมคือ video_id ค่ามิติข้อมูลจะเป็นแบบไม่ระบุตัวบุคคล เว้นแต่จะมีการดูวิดีโอในจํานวนครั้งที่กําหนด
เมตริก | การรวมมิติข้อมูล | มิติข้อมูลที่ลบข้อมูลระบุตัวบุคคล | ค่าที่ไม่ระบุชื่อ |
---|---|---|---|
ผู้ติดตาม_รายได้ | รหัสช่อง [channel_id] | รหัสประเทศ | ZZ |
ผู้ติดตาม_รายได้ | รหัสช่อง [channel_id] | รหัสจังหวัด | US-ZZ |
ผู้ติดตาม_สูญหาย | รหัสช่อง [channel_id] | รหัสประเทศ | ZZ |
ผู้ติดตาม_สูญหาย | รหัสช่อง [channel_id] | รหัสจังหวัด | US-ZZ |
ความคิดเห็น | รหัสวิดีโอ | รหัสประเทศ | ZZ |
ความคิดเห็น | รหัสวิดีโอ | รหัสจังหวัด | US-ZZ |
การกดชอบ | รหัสวิดีโอ | รหัสประเทศ | ZZ |
การกดชอบ | รหัสวิดีโอ | รหัสจังหวัด | US-ZZ |
ไม่ชอบ | รหัสวิดีโอ | รหัสประเทศ | ZZ |
ไม่ชอบ | รหัสวิดีโอ | รหัสจังหวัด | US-ZZ |
ยอดดู | รหัสวิดีโอ | กลุ่มอายุ [age_group] | NULL |
ยอดดู | รหัสวิดีโอ | เพศ [gender] | NULL |
ยอดดู | video_id และ traffic_source_detail | รายละเอียดแหล่งที่มาของการเข้าชม [traffic_source_detail] | NULL |
จํานวนผู้ติดตามของช่อง | รหัสช่อง [channel_id] | สถานะการสมัครใช้บริการ | NULL |
ตัวอย่างโค้ด
ตัวอย่างโค้ดต่อไปนี้สาธิตวิธีใช้ API เพื่อสร้างงานการรายงาน แล้วเรียกรายงานของงานนั้น จะมีตัวอย่างโค้ด 2 ตัวอย่างสําหรับแต่ละภาษา ได้แก่
-
ตัวอย่างโค้ดแรกแสดงวิธีเรียกข้อมูลรายการประเภทรายงานที่ใช้ได้ แล้วสร้างงานการรายงานใหม่
-
ตัวอย่างโค้ดที่ 2 แสดงวิธีเรียกข้อมูลรายงานสําหรับงานหนึ่งๆ คุณจะเริ่มเรียกข้อมูลรายงานได้ภายใน 48 ชั่วโมงหลังจากสร้างงาน
หมายเหตุ: ตัวอย่างโค้ดต่อไปนี้อาจไม่แสดงภาษาโปรแกรมที่รองรับทั้งหมด โปรดดูรายชื่อภาษาที่รองรับในเอกสารประกอบเกี่ยวกับไลบรารีของไคลเอ็นต์
Java
ตัวอย่างต่อไปนี้ใช้ไลบรารีของไคลเอ็นต์ Java
ตัวอย่างที่ 1: สร้างงานการรายงาน
ตัวอย่างโค้ดต่อไปนี้จะเรียกเมธอด 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; } }
ตัวอย่างที่ 2: ดึงรายงาน
ตัวอย่างโค้ดเรียกเมธอด jobs.list
เพื่อเรียกรายการงานการรายงาน จากนั้นเรียกเมธอด reports.list
ที่มีการตั้งค่าพารามิเตอร์ jobId
เป็นรหัสงานที่เจาะจงเพื่อดึงรายงานที่สร้างโดยงานนั้น สุดท้าย ตัวอย่างจะพิมพ์ URL การดาวน์โหลดสําหรับแต่ละรายงาน
/* * 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
ตัวอย่างที่ 1: สร้างงานการรายงาน
ตัวอย่างโค้ดต่อไปนี้จะเรียกเมธอด 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>
ตัวอย่างที่ 2: ดึงรายงาน
ตัวอย่างโค้ดเรียกเมธอด jobs.list
เพื่อเรียกรายการงานการรายงาน จากนั้นเรียกเมธอด reports.list
ที่มีการตั้งค่าพารามิเตอร์ jobId
เป็นรหัสงานที่เจาะจงเพื่อดึงรายงานที่สร้างโดยงานนั้น สุดท้าย ตัวอย่างจะพิมพ์ URL การดาวน์โหลดสําหรับแต่ละรายงาน
<?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
ตัวอย่างที่ 1: สร้างงานการรายงาน
ตัวอย่างโค้ดต่อไปนี้จะเรียกเมธอด 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)
ตัวอย่างที่ 2: ดึงรายงาน
ตัวอย่างโค้ดเรียกเมธอด jobs.list
เพื่อเรียกรายการงานการรายงาน จากนั้นเรียกเมธอด reports.list
ที่มีการตั้งค่าพารามิเตอร์ jobId
เป็นรหัสงานที่เจาะจงเพื่อดึงรายงานที่สร้างโดยงานนั้น สุดท้าย ตัวอย่างจะพิมพ์ URL การดาวน์โหลดสําหรับแต่ละรายงาน
#!/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)