Question :
Youtube has disabled API V2 and the new API (V3) is much more complicated to get information about videos.
How can I get the following information from a video in the v3 API:
- Video title.
- Duration of the video (in seconds).
How can I get this information?
Answer :
I confess that I have never worked with the Youtube API, so I decided to give it a thorough look at the documentation.
Basically, Google prevents you from returning unnecessary data and split the request process into 2 parameters:
-
part
is responsible for returning a requested resource. The resources
video can be checked at: Video Features -
field
is responsible for filtering
this feature, and can only return specific fields that you
needs. You can learn more about them at: Understanding the fields parameter
Based on this, I developed a code in Python 3 that I believe solves what you want (it would be possible to simplify the code, but for the purpose of explaining what is being done, I broke it in parts and got longer):
import requests
import re
import json
GOOGLE_API_KEY = "XXXXXXXXXXXXXX" # Coloque sua API Key da Google
VIDEO_ID = "7lCDEYXw3mM" # Coloque o ID do seu vídeo
FIELDS = "items(snippet(title),contentDetails(duration))" # Fields que será responsável por retornar apenas a informação que você deseja (título e duração)
PART = "snippet,contentDetails" # Part que retornará os recursos que você precisa
# URL completa
url = "https://www.googleapis.com/youtube/v3/videos?id=" + VIDEO_ID + "&key=" + GOOGLE_API_KEY + "&fields=" + FIELDS + "&part=" + PART
# Padrão ISO 8601 usado para converter a duração
# http://en.wikipedia.org/wiki/ISO_8601#Durations
# Lógica feita por 9000: http://stackoverflow.com/users/223424/9000
ISO_8601_period_rx = re.compile(
'P' # Designa um período de tempo
'(?:(?P<weeks>d+)W)?' # Semanas
'(?:(?P<days>d+)D)?' # Dias
'(?:T' # Parte relacionada com o tempo inicia-se em T
'(?:(?P<hours>d+)H)?' # Horas
'(?:(?P<minutes>d+)M)?' # Minutos
'(?:(?P<seconds>d+)S)?' # Segundos
')?' # Fim
)
# Método para imprimir o título e duração
# Você pode utilizar as variáveis 'title' e 'duration' no que preferir
def getYoutubeTitleAndDuration():
# Fazendo uma requisição na URL e recebendo os dados em formato JSON
response = requests.get(url)
json_data = json.loads(response.text)
# Percorrendo as listas e dicionários para obter título e duração
title = json_data['items'][0]['snippet']['title']
duration = getDurationInSeconds(json_data['items'][0]['contentDetails']['duration'])
# Imprimindo os dados obtidos
print("Titulo: " + title)
print("Duração em segundos: " + str(duration))
def getDurationInSeconds(duration):
# Obtendo a duração e convertendo em um dicionário
time = ISO_8601_period_rx.match(duration).groupdict()
# Usado na conversão da duração para segundos
MINUTE_IN_SECONDS = 60
HOUR_IN_SECONDS = 60 * MINUTE_IN_SECONDS
DAY_IN_SECONDS = 24 * HOUR_IN_SECONDS
WEEK_IN_SECONDS = 7 * DAY_IN_SECONDS
# Percorrendo o dicionário e transformando os valores None em 0
# Isso evita que exceções sejam lançadas durante a conversão
for key,value in time.items():
if value is None:
time[key] = 0
# Obtendo cada dado do dicionário
weeks = (int(time['weeks']))
days = (int(time['days']))
hours = (int(time['hours']))
minutes = (int(time['minutes']))
seconds = (int(time['seconds']))
# Retornando o valor convertido em segundos
return (weeks * WEEK_IN_SECONDS) + (days * DAY_IN_SECONDS) + (hours * HOUR_IN_SECONDS) + (minutes * MINUTE_IN_SECONDS) + seconds;
To get the title and duration in the parameter part=
it is necessary to pass snippet
and contentDetails
, something like:
https://www.googleapis.com/youtube/v3/videos?id={ID DO VIDEO}&part=snippet,contentDetails&key={YOUR_API_KEY}
It will return something like:
{
"kind": "youtube#videoListResponse",
"etag": ""<
etag>
"""",