0

I have been reading through the API docs for YouTube, but I am having a hard time figuring out how I can calculate the number of views per week of a given video in Python. Is this possible? Thanks!

stvar
  • 6,551
  • 2
  • 13
  • 28

1 Answers1

1

The YouTube Analytics and Reporting APIs does not provide a metric of the kind you need -- views per week (as far as I know).

The YouTube Data API doesn't provide the info you need -- views per week -- either, but you may well compute that yourself base on this property:

statistics.viewCount (unsigned long)
The number of times the video has been viewed.

Thus, you should call the Videos.list API endpoint, passing on to it the parameters id=VIDEO_ID and part=statistics, where VIDEO_ID is the ID of the video you're interested in.

Arrange your program to read the viewCount property weekly, for computing the views per week as needed.


In the context of Python, if you're using the Google APIs Client Library for Python, then your call to the Videos.list endpoint would look like:

from googleapiclient.discovery import build
youtube = build('youtube', 'v3', developerKey = APP_KEY)

response = youtube.videos().list(
    id = VIDEO_ID,
    part = 'statistics',
    fields = 'items(statistics(viewCount))',
    maxResults = 1
).execute()

view_count = response['items'][0]['statistics']['viewCount']

Note that the code above is simplified quite much since there's no error handling.

Also note that the code above is using the parameter fields to obtain from the endpoint only the viewCount property. (It's always good to ask from the API only the info that is really needed.)

Yet another caveat using this endpoint is the following:

Even if the official doc says that the endpoint's response contains a viewCount property of type unsigned long, the actual JSON response has the value of that property being of type string:

{
  "items": [
    {
      "statistics": {
        "viewCount": "54508"
      }
    }
  ]
}

Thus, the variable view_count above will be of type str; using it as an integer would, of course, require a conversion of form int(view_count).

Benjamin Loison
  • 3,782
  • 4
  • 16
  • 33
stvar
  • 6,551
  • 2
  • 13
  • 28