The YouTube API allows developers to integrate YouTube functionality into their own applications. The API provides methods for searching videos, managing playlists, uploading videos, and more.
In this article, we'll look at how to query the YouTube API v3 using the Python Requests library. Requests allows us to make HTTP requests in Python in a simple and Pythonic way.
Overview
Getting an API Key
To query the YouTube API, you'll need an API key:
- Go to the Google Cloud Console
- Create a new project
- Enable the YouTube Data API v3
- Create an API key credential and note down the key
This key authenticates all our API requests.
Constructing the Request
The YouTube API has a REST endpoint for the videos resource:
https://www.googleapis.com/youtube/v3/videos
We can specify parameters on this endpoint to filter and sort results. For example, to search for Python tutorial videos ordered by viewCount:
https://www.googleapis.com/youtube/v3/search?part=snippet&maxResults=25&order=viewCount&q=python+tutorial&key=[YOUR_API_KEY]
Let's break this down:
See the documentation for other supported parameters.
Sending the Request with Python
We can send this request and process the response in Python with Requests:
import requests
API_KEY = "[YOUR_API_KEY]"
search_url = "https://www.googleapis.com/youtube/v3/search"
params = {
"part" : "snippet",
"maxResults" : 25,
"order" : "viewCount",
"q" : "python tutorial",
"key" : API_KEY
}
r = requests.get(search_url, params=params)
print(r.text)
This prints out the raw JSON response body. We can transform this into a Python dict with:
import json
results = json.loads(r.text)
And access values like:
print(results["items"][0]["snippet"]["title"])
Which prints the title of the top video.
Next Steps
This covers the basics of querying the YouTube API with Python Requests!
Some next things to try:
The API has a vast range of capabilities for building YouTube applications. The documentation is a key reference for exploring further.