Home > Enterprise >  Not sure of the Print Structure with YouTube v3 API
Not sure of the Print Structure with YouTube v3 API

Time:11-20

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

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,contentDetails,statistics&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?

CodePudding user response:

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,contentDetails,statistics&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.

  • Related