Complete the steps described in the rest of this page, and in a few minutes you'll have a simple Python command-line application that makes requests to the YouTube Data API.
The sample code used in this guide retrieves thechannel
resource
for the GoogleDevelopers YouTube channel and prints some basic information from
that resource.
Note that this guide presents two ways to authorize requests:
- The installed application flow shows how to authorize requests in an app that is distributed to individual devices. Such apps can access Google APIs while the user is present at the app or when the app is running in the background.
- The web application flow shows how to obtain authorization in a server-side web server application. A properly authorized web server application can access an API while the user interacts with the application or after the user has left the application.
Prerequisites
To run this quickstart, you'll need:
- Python 2.6 or greater.
- The pip package management tool.
- Access to the internet and a web browser.
- A Google account.
Step 1: Turn on the YouTube Data API
-
Use this wizard to create or select a project in the Google Developers Console and automatically turn on the API. Click Continue, then Go to credentials.
-
On the Add credentials to your project page, click the Cancel button.
-
At the top of the page, select the OAuth consent screen tab. Select an Email address, enter a Product name if not already set, and click the Save button.
-
Select the Credentials tab, click the Create credentials button and select OAuth client ID.
-
Select the application type Other, enter the name "YouTube Data API Quickstart", and click the Create button.
-
Click OK to dismiss the resulting dialog.
-
Click the
(Download JSON) button to the right of the client ID. -
Move the downloaded file to your working directory and rename it
client_secret.json
.
-
Use this wizard to create or select a project in the Google Developers Console and automatically turn on the API. Click Continue, then Go to credentials.
-
On the Add credentials to your project page, click the Cancel button.
-
At the top of the page, select the OAuth consent screen tab. Select an Email address, enter a Product name if not already set, and click the Save button.
-
Select the Credentials tab, click the Create credentials button and select OAuth client ID.
-
Select the application type Web application and enter the name "YouTube Data API Quickstart". Under Authorized redirect URIs, add
http://localhost:8090/oauth2callback
, which is the default redirect URL used in this code sample.You can specify a different redirect URI. If you do, then you may also need to change the sample code to launch the web server at an address other than
http://localhost:8090
and/or to specify a callback endpoint other thanoauth2callback
. -
Click the Create button.
-
Click the
(Download JSON) button to the right of the client ID. -
Move the downloaded file to your working directory and rename it
client_secret.json
.
Step 2: Install the Google APIs Client Library for Python
Run the following command to install the library using pip:
pip install --upgrade google-api-python-client
See the library's installation page for alternative installation options.
Step 3: Install additional libraries
-
Install the
google-auth
,google-auth-oauthlib
, andgoogle-auth-httplib2
libraries.google-auth
is the Google authentication and authorization library for Python. The other two libraries provide oauthlib integration and anhttplib2
transport forgoogle-auth
.pip install --upgrade google-auth google-auth-oauthlib google-auth-httplib2
-
Install the
google-auth
,google-auth-oauthlib
, andgoogle-auth-httplib2
libraries.google-auth
is the Google authentication and authorization library for Python. The other two libraries provide oauthlib integration and anhttplib2
transport forgoogle-auth
.pip install --upgrade google-auth google-auth-oauthlib google-auth-httplib2
-
Install the Flask web application framework.
pip install --upgrade flask
-
Install the
requests
HTTP library.pip install --upgrade requests
Step 4: Set up the sample
Create a file named quickstart.py
in your working directory and paste the
appropriate code sample from the tabs below into that file.
# Sample Python code for user authorization import os import google.oauth2.credentials from googleapiclient.discovery import build from googleapiclient.errors import HttpError from google_auth_oauthlib.flow import InstalledAppFlow # The CLIENT_SECRETS_FILE variable specifies the name of a file that contains # the OAuth 2.0 information for this application, including its client_id and # client_secret. CLIENT_SECRETS_FILE = "client_secret.json" # This OAuth 2.0 access scope allows for full read/write access to the # authenticated user's account and requires requests to use an SSL connection. SCOPES = ['https://www.googleapis.com/auth/youtube.force-ssl'] API_SERVICE_NAME = 'youtube' API_VERSION = 'v3' def get_authenticated_service(): flow = InstalledAppFlow.from_client_secrets_file(CLIENT_SECRETS_FILE, SCOPES) credentials = flow.run_console() return build(API_SERVICE_NAME, API_VERSION, credentials = credentials) def channels_list_by_username(service, **kwargs): results = service.channels().list( **kwargs ).execute() print('This channel\'s ID is %s. Its title is %s, and it has %s views.' % (results['items'][0]['id'], results['items'][0]['snippet']['title'], results['items'][0]['statistics']['viewCount'])) if __name__ == '__main__': # When running locally, disable OAuthlib's HTTPs verification. When # running in production *do not* leave this option enabled. os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1' service = get_authenticated_service() channels_list_by_username(service, part='snippet,contentDetails,statistics', forUsername='GoogleDevelopers')
# -*- coding: utf-8 -*- import os import flask import google.oauth2.credentials import google_auth_oauthlib.flow import googleapiclient.discovery # The CLIENT_SECRETS_FILE variable specifies the name of a file that contains # the OAuth 2.0 information for this application, including its client_id and # client_secret. CLIENT_SECRETS_FILE = "client_secret.json" # This OAuth 2.0 access scope allows for full read/write access to the # authenticated user's account and requires requests to use an SSL connection. SCOPES = ['https://www.googleapis.com/auth/youtube.force-ssl'] API_SERVICE_NAME = 'youtube' API_VERSION = 'v3' app = flask.Flask(__name__) # Note: A secret key is included in the sample so that it works, but if you # use this code in your application please replace this with a truly secret # key. See http://flask.pocoo.org/docs/0.12/quickstart/#sessions. app.secret_key = 'REPLACE ME - this value is here as a placeholder.' @app.route('/') def index(): if 'credentials' not in flask.session: return flask.redirect('authorize') # Load the credentials from the session. credentials = google.oauth2.credentials.Credentials( **flask.session['credentials']) client = googleapiclient.discovery.build( API_SERVICE_NAME, API_VERSION, credentials=credentials) return channels_list_by_username(client, part='snippet,contentDetails,statistics', forUsername='GoogleDevelopers') @app.route('/authorize') def authorize(): # Create a flow instance to manage the OAuth 2.0 Authorization Grant Flow # steps. flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file( CLIENT_SECRETS_FILE, scopes=SCOPES) flow.redirect_uri = flask.url_for('oauth2callback', _external=True) authorization_url, state = flow.authorization_url( # This parameter enables offline access which gives your application # both an access and refresh token. access_type='offline', # This parameter enables incremental auth. include_granted_scopes='true') # Store the state in the session so that the callback can verify that # the authorization server response. flask.session['state'] = state return flask.redirect(authorization_url) @app.route('/oauth2callback') def oauth2callback(): # Specify the state when creating the flow in the callback so that it can # verify the authorization server response. state = flask.session['state'] flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file( CLIENT_SECRETS_FILE, scopes=SCOPES, state=state) flow.redirect_uri = flask.url_for('oauth2callback', _external=True) # Use the authorization server's response to fetch the OAuth 2.0 tokens. authorization_response = flask.request.url flow.fetch_token(authorization_response=authorization_response) # Store the credentials in the session. # ACTION ITEM for developers: # Store user's access and refresh tokens in your data store if # incorporating this code into your real app. credentials = flow.credentials flask.session['credentials'] = { 'token': credentials.token, 'refresh_token': credentials.refresh_token, 'token_uri': credentials.token_uri, 'client_id': credentials.client_id, 'client_secret': credentials.client_secret, 'scopes': credentials.scopes } return flask.redirect(flask.url_for('index')) def channels_list_by_username(client, **kwargs): response = client.channels().list( **kwargs ).execute() return flask.jsonify(**response) if __name__ == '__main__': # When running locally, disable OAuthlib's HTTPs verification. When # running in production *do not* leave this option enabled. os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1' app.run('localhost', 8090, debug=True)
Step 5: Run the sample
Run the sample using the following command:
python quickstart.py
-
The sample attempts to open a new window or tab in your default
browser. If this fails, copy the URL from the console and manually
open it in your browser.
If you are not already logged into your Google account, you will be prompted to log in. If you are logged into multiple Google accounts, you will be asked to select one account to use for the authorization. - Click the Accept button.
-
The sample proceeds automatically. If it runs successfully, it prints a statement similar to the one below in the terminal window where you ran the script:
This channel's ID is UC_x5XG1OV2P6uZZ5FSM9Ttw. Its title is Google Developers, and it has 122432415 views.
You may close the browser window/tab where you authorized the sample.
-
The sample launches a web server at
http://localhost:8090
. (If you changed theapp.run
command in the sample, the web server launches at the address that you specified.) -
In your browser, go to
http://localhost:8090/
or whichever web server address you specified in theapp.run
command. You should be redirected to the/authorize
endpoint on your web server. (If you aren't redirected, you can hit that endpoint directly.)If you aren't already logged into your Google account, you will be prompted to log in. If you are logged into multiple Google accounts, you will be asked to select one account to use for the authorization.
-
Click the Accept button.
-
The sample proceeds and redirects you back to the index page (e.g.
http://localhost:8090
). If it runs successfully, the web page displays a formatted JSON object showing the channel resource for the GoogleDevelopers YouTube channel.
Notes
- If you are using the installed app flow, authorization credentials are not stored in this sample code, so subsequent executions will prompt for reauthorization.
- If you are using the web application flow, authorization credentials may be
temporarily stored in the Flask session object. If you get an
google.auth.exceptions.RefreshError
when loading the index page, you need to refresh your credentials.
Further reading
- Google Developers Console help documentation
- Google APIs Client for Python documentation
- YouTube Data API PyDoc documentation
- YouTube Data API reference documentation
Troubleshooting
Errors
AttributeError: 'Module_six_moves_urllib_parse' object has no attribute 'urlparse'
This error can occur in Mac OSX where the default installation of the "six"
module (a dependency of this library) is loaded before the one that pip
installed. To fix the issue, add pip's install location to the PYTHONPATH
system environment variable:
-
Determine pip's install location with the following command:
pip show six | grep "Location:" | cut -d " " -f2
-
Add the following line to your
~/.bashrc
file, replacing<pip_install_path>
with the value determined above:export PYTHONPATH=$PYTHONPATH:<pip_install_path>
-
Reload your
~/.bashrc
file in any open terminal windows using the following command:source ~/.bashrc
google.auth.exceptions.RefreshError
This error may occur in the web application flow if you try to load the index
page (e.g. http://localhost:8090
) but you do not have active authorization
credentials stored in the Flask session.
To refresh your authorization credentials, go to the /authorize
endpoint
on your web server (e.g. http://localhost:8090/authorize
).
Warnings
You might see the following warnings in your terminal window if you are using Python 2 versions:
InsecurePlatformWarning
SNIMissingWarning
See the urllib3 library documentation for more information about these warnings.