Youtube API Get Video by ID (Python)

Mar 28, 2020

Setup

Install

pip install --upgrade google-api-python-clientpip install --upgrade google-auth-oauthlib google-auth-httplib2

Enable Youtube Data API at Google Cloud Console

Setup Credentials

  • Goto Google Cloud Console -> Credentials -> OAuth consent screen.
  • Go back to Credentials to create OAuth client ID:
    • Application type: Web application, Android, Chrome App, iOS, Other; I choose Others as I am running a local script.
    • Name: For you to identify the usage of this key
  • You will be shown client ID and secret. Click OK.
  • Click Download JSON and save the file as credentials.json.

Code

from googleapiclient.discovery import buildfrom google_auth_oauthlib.flow import InstalledAppFlowfrom google.auth.transport.requests import RequestTOKEN_FILE = 'keys/token.pickle'CREDENTIAL_FILE = 'keys/credentials.json'# setup credentialscredentials = Noneif os.path.exists(TOKEN_FILE):    with open(TOKEN_FILE, 'rb') as token:        credentials = pickle.load(token)if not credentials or not credentials.valid:    if credentials and credentials.expired and credentials.refresh_token:        credentials.refresh(Request())    else:        flow = InstalledAppFlow.from_client_secrets_file(            CREDENTIAL_FILE, SCOPES)        credentials = flow.run_local_server(port=10800)    # Save the credentials for the next run    with open(TOKEN_FILE, 'wb') as token:        pickle.dump(credentials, token)# build apiyoutube = build('youtube', 'v3', credentials=credentials)# url = 'https://www.youtube.com/watch?v=Ks-_Mh1QhMc'youtube_id = 'Ks-_Mh1QhMc'request = youtube.videos().list(    part="snippet", # ,contentDetails,statistics    id=youtube_id)if result['items']:    item = result['items'][0]    # title = item['snippet']['title']    # description = item['snippet']['description']    date = item['snippet']['publishedAt']

Sample Output

{ "kind": "youtube#videoListResponse", "etag": "\"ksCrgYQhtFrXgbHAhi9Fo5t0C2I/s1ZFhJA-_8FTYdMR6RWc51VssmM\"", "pageInfo": {  "totalResults": 1,  "resultsPerPage": 1 }, "items": [  {   "kind": "youtube#video",   "etag": "\"ksCrgYQhtFrXgbHAhi9Fo5t0C2I/KCPriZsgzpV0LDoEj-frnQJUpXc\"",   "id": "Ks-_Mh1QhMc",   "snippet": {    "publishedAt": "2012-10-01T15:27:35.000Z",    "channelId": "UCAuUUnT6oDeKwE6v1NGQxug",    "title": "Your body language may shape who you are | Amy Cuddy",    "description": "Body language affects how others see us, but it may also change how we see ourselves. Social psychologist Amy Cuddy argues that \"power posing\" -- standing in a posture of confidence, even when we don't feel confident -- can boost feelings of confidence, and might have an impact on our chances for success. (Note: Some of the findings presented in this talk have been referenced in an ongoing debate among social scientists about robustness and reproducibility. Read Amy Cuddy's response here: http://ideas.ted.com/inside-the-debate-about-power-posing-a-q-a-with-amy-cuddy/)\n\nGet TED Talks recommended just for you! Learn more at https://www.ted.com/signup.\n\nThe TED Talks channel features the best talks and performances from the TED Conference, where the world's leading thinkers and doers give the talk of their lives in 18 minutes (or less). Look for talks on Technology, Entertainment and Design -- plus science, business, global issues, the arts and more.\n\nFollow TED on Twitter: http://www.twitter.com/TEDTalks\nLike TED on Facebook: https://www.facebook.com/TED\n\nSubscribe to our channel: https://www.youtube.com/TED",    "thumbnails": {     "default": {      "url": "https://i.ytimg.com/vi/Ks-_Mh1QhMc/default.jpg",      "width": 120,      "height": 90     },     "medium": {      "url": "https://i.ytimg.com/vi/Ks-_Mh1QhMc/mqdefault.jpg",      "width": 320,      "height": 180     },     "high": {      "url": "https://i.ytimg.com/vi/Ks-_Mh1QhMc/hqdefault.jpg",      "width": 480,      "height": 360     },     "standard": {      "url": "https://i.ytimg.com/vi/Ks-_Mh1QhMc/sddefault.jpg",      "width": 640,      "height": 480     },     "maxres": {      "url": "https://i.ytimg.com/vi/Ks-_Mh1QhMc/maxresdefault.jpg",      "width": 1280,      "height": 720     }    },    "channelTitle": "TED",    "tags": [     "Amy Cuddy",     "TED",     "TEDTalk",     "TEDTalks",     "TED Talk",     "TED Talks",     "TEDGlobal",     "brain",     "business",     "psychology",     "self",     "success"    ],    "categoryId": "22",    "liveBroadcastContent": "none",    "defaultLanguage": "en",    "localized": {     "title": "Your body language may shape who you are | Amy Cuddy",     "description": "Body language affects how others see us, but it may also change how we see ourselves. Social psychologist Amy Cuddy argues that \"power posing\" -- standing in a posture of confidence, even when we don't feel confident -- can boost feelings of confidence, and might have an impact on our chances for success. (Note: Some of the findings presented in this talk have been referenced in an ongoing debate among social scientists about robustness and reproducibility. Read Amy Cuddy's response here: http://ideas.ted.com/inside-the-debate-about-power-posing-a-q-a-with-amy-cuddy/)\n\nGet TED Talks recommended just for you! Learn more at https://www.ted.com/signup.\n\nThe TED Talks channel features the best talks and performances from the TED Conference, where the world's leading thinkers and doers give the talk of their lives in 18 minutes (or less). Look for talks on Technology, Entertainment and Design -- plus science, business, global issues, the arts and more.\n\nFollow TED on Twitter: http://www.twitter.com/TEDTalks\nLike TED on Facebook: https://www.facebook.com/TED\n\nSubscribe to our channel: https://www.youtube.com/TED"    },    "defaultAudioLanguage": "en"   },   "contentDetails": {    "duration": "PT21M3S",    "dimension": "2d",    "definition": "hd",    "caption": "true",    "licensedContent": true,    "projection": "rectangular"   },   "statistics": {    "viewCount": "17766800",    "likeCount": "250426",    "dislikeCount": "4943",    "favoriteCount": "0",    "commentCount": "7973"   }  } ]}

NOTE: Get YouTube ID from URL

References:

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.