Youtube API V3 Information

Asked

Viewed 1,595 times

4

Youtube disabled the V2 API and the new API (V3) is much more complicated to pick up information about videos.

How can I get the following video information from the v3 API:

  • Title of the video.
  • Video duration (in seconds).

How can I get this information?

  • In what language? Any one?

  • Can be Python or PHP.

2 answers

5

I confess that I never worked with the Youtube API, so I decided to take a look at the documentation.

Basically, Google prevents you from returning unnecessary data and divided the request process into 2 parameters:

  • part is responsible for returning a requested resource. Resources video can be check in: Video features
  • field is responsible for filtering this feature, being able to return only specific fields that you needs. You can understand more about them in: 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 became more extensive):

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;

1

To take the title and duration in the parameter part= it is necessary to pass the snippet and contentDetails, should look 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>\"",
  "pageInfo": {
    "totalResults": 1,
    "resultsPerPage": 1
  },
  "items": [
    {
      "kind": "youtube#video",
      "etag": "\"<etag>\"",
      "id": "<id>",
      "snippet": {
        "publishedAt": "2012-10-01T15:27:35.000Z",
        "channelId": "UCAuUUnT6oDeKwE6v1NGQxug",
        "title": "foo bar baz titulo",
        "description": "foo bar descrição",
        "thumbnails": {
          "default": {
            "url": "https://i.ytimg.com/vi/<id>/default.jpg",
            "width": 120,
            "height": 90
          },
          "medium": {
            "url": "https://i.ytimg.com/vi/<id>/mqdefault.jpg",
            "width": 320,
            "height": 180
          },
          "high": {
            "url": "https://i.ytimg.com/vi/<id>/hqdefault.jpg",
            "width": 480,
            "height": 360
          },
          "standard": {
            "url": "https://i.ytimg.com/vi/<id>/sddefault.jpg",
            "width": 640,
            "height": 480
          },
          "maxres": {
            "url": "https://i.ytimg.com/vi/<id>/maxresdefault.jpg",
            "width": 1280,
            "height": 720
          }
        },
        "channelTitle": "FOOBARBAZ",
        "tags": [
          "foo",
          "bar",
          "baz"
        ],
        "categoryId": "22",
        "liveBroadcastContent": "none",
        "defaultLanguage": "en",
        "localized": {
          "title": "foo bar baz titulo",
          "description": "foo bar descrição"
        },
        "defaultAudioLanguage": "en"
      },
      "contentDetails": {
        "duration": "PT21M3S",
        "dimension": "2d",
        "definition": "hd",
        "caption": "true",
        "licensedContent": true,
        "projection": "rectangular"
      }
    }
  ]
}

then you can use file_get_contents (if HTTP is allowed on your server) or curl, example:

$id = '<id do video>';
$api_key = '<sua chave>';

$url = 'https://www.googleapis.com/youtube/v3/videos?id=' . $id . '&part=snippet,contentDetails&key=' . $api_key;

$resposta = file_get_contents($url);

if ($resposta) {
    $api_data = json_decode($resposta);
} else {
    die('Falha na resposta');
}

foreach ($api_data->items as $video) {
    echo 'Titulo: ', $video->title, '<br>';
    echo 'Titulo: ', $video->description, '<br>';
    echo 'Duração: ', $video->contentDetails->duration, '<br>';
}

As stated in the reply, the time is formatted in ISO 8601, so you can use DateInterval to easily convert to the desired output format, example:

$di = new DateInterval($video->contentDetails->duration);
echo $di->format('%H:%I:%S');

In the foreach:

foreach ($api_data->items as $video) {

    $di = new DateInterval($video->contentDetails->duration);

    echo 'Titulo: ', $video->title, '<br>';
    echo 'Titulo: ', $video->description, '<br>';
    echo 'Duração: ', $di->format('%H:%I:%S'), '<br>';

}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.