Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Not sure of the Print Structure with YouTube v3 API

So I was creating a script to list information from Google’s V3 YouTube API and I used the structure that was shown on their Site describing it, so I’m pretty sure I’m misunderstanding something.

I tried using the structure that was shown to print JUST the Video’s Title as a test

PrintStructure

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

and was expecting that to print, however it just throws an error. Error is below

Error

Here’s what I wrote below

import sys, json, requests

vidCode = input('\nVideo Code Here: ')

url = requests.get(f'https://youtube.googleapis.com/youtube/v3/videos?part=snippet%2CcontentDetails%2Cstatistics&id={vidCode}&key=(not sharing the api key, lol)')
text = url.text

data = json.loads(text)

if "kind" in data:
    print(f'Video URL: youtube.com/watch?v={vidCode}')
    print('Title: ', data['snippet.title'])
else:
    print("The video could not be found.\n")

This did not work, however if I change snippet.title to just something like etag the print is successful.

I take it this is because the Title is further down in the JSON List.

ExampleHere

I’ve also tried doing data['items'] which did work, but I also don’t want to output a massive chunk of unformatted information, it’s not pretty lol.

Another test I did was data['items.snippet.title'] to see if that was what I was missing, also no, that didn’t work.

Any idea what I’m doing wrong?

>Solution :

you need to access the keys in the dictionary separately.

import sys, json, requests

vidCode = input('\nVideo Code Here: ')

url = requests.get(f'https://youtube.googleapis.com/youtube/v3/videos?part=snippet%2CcontentDetails%2Cstatistics&id={vidCode}&key=(not sharing the api key, lol)')
text = url.text

data = json.loads(text)

if "kind" in data:
    print(f'Video URL: youtube.com/watch?v={vidCode}')
    
    print('Title: ', data['items'][0]['snippet']['title'])
else:
    print("The video could not be found.\n")

To be clear, you need to access the ‘items’ value in the dictionary which is a list, get the first item from that list, then get the ‘snippet’ sub object, then finally the title.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading