Authorization process of YouTube Data API
Do not miss this exclusive book on Binary Tree Problems. Get it now for free.
Reading time: 45 minutes | Coding time: 10 minutes
In this article, we will go through the Authorization process of YouTube Data API and understand the use of various tokens like client secret key, authorization token, refresh token and much more. It use OAuth2.
The sub-topics we covered are:
- Getting Youtube Data API key
- Understanding Refresh Tokens
- Client Side WorkFlow of tokens
- Server Side WorkFlow of tokens
- Python demo using API key and using OAuth Authentication
Youtube data API or simply YouTube API is an API service by Google to let us interact with the youtube.com servers directly. YouTube data API is basically used to directly interact with the YouTube services through some API . You can use it to upload videos, manage playlists or simply comment or like a video or you can also use it for searching for content you can search for videos channels playlists.
YouTube data API also provides many functionalities which are not available directly on the YouTube website But they can be achieved by using the YouTube Data API.
-
The methods of Youtube API accepts various parameters which are used to cusotmize the requests according to needs.
-
There are Youtube API libraries for almost all programming languages but in this case we will be using python.
Read the Documentation of Youtube Data API from here
Getting Youtube Data API key
To start with, we will need to have a google account and obtain credentials (i.e. API key) on the to access the Youtube Data API, following these steps:
- In order to create an API key you need to have a Google developers console project so in order to create that you have to simply go to the url console.developers.google.com
- log in with your Google account.
- Click “create a new project”
- Fill out the form, and click “Create”
- click on enable and it is enabling the API for the Youtube API project
- In the next page, click on “API key” and select the restrictions use wish to put on the api access. Basically select youtube data api v3 because we only need to access this api
- Scroll down and click “Create”. Then copy your “API Key”.
There are two types of Youtube Data API Credentials: API Key and OAuth.
OAuth provides you with Client Id and a Secret Key in the form of a JSON file.
OAuth is generally used where authorization is required like in the case of retrieving liked videos of a user.
So for the rest cases where authorization is not required like searching for the videos using a keyword or for searching for the related videos etc we will be using API Key. Basically whatever task that can be done on youtube.com without logging into the google account.
Understanding Refresh Tokens
- Refresh token is a special type of token used in Restful API's. It is a long life token that is used only for authorisation server.
- Typically we can use access tokens against multiple resources. This means if this access token is a bearer token and the authorisation server was hacked so that it were controlled by an attacker, the access token can be reused against other resources and the attacker can now get the resources.
- Refresh token is generated to solve this problem as it's a long lifetime token, that's only used against authorization server. Since it's only used against the authorization server the risk of it being stolen is substantially lower the client can use it against the token endpoint to get a new access token. It's like refreshing the access token that's why it is called refresh token.
Generating refresh tokens for Youtube Data API
- The first thing we'll do is browse to https://developers.google.com/oauthplayground/ .The OAuth playground is a tool hosted on Google developer site that lets developers see authorization flow step by step and see how API calls are made at the HTTP layer
- We will generate a live refresh token that we can exchange for access tokens to make YouTube data API
- We need to configure the OAuth playground to use our client secret and client ID. We can find our client ID and client secret from the Google API console
- Click the Settings button and check the boxes using use your own off credentials and make sure the access type is set to offline because this is what we need to ensure that we receive a long-lived refresh token and not a short-lived access token.
- We present it with two fields - one for client ID and one for client secret.
- Copy-paste the values over from the API console there's one more thing we need to set up.
- Let's click on edit settings if we haven't set this yet .
- Click update and now let's go back off to playground and select the api's authorize.
- Select the YouTube analytics API a read-only scope and the YouTube data API v3 .
- Now, click authorize api's will be forwarded to a page we'll need to grant access if we're in charge multiple channels will first be presented with an
- account picker.
- Click accept and continue we now have an authorization code which we can use six change for a refresh token and access token.
- Click exchange authorization code for tokens.
- The Oauth playground will populate the refresh token and access token fields after making the API call .
- We can start using these immediately but the value wants to save our scripts is in the Refresh token field as we can see the access token will expire in about one hour the official Google API clients will all handle obtaining an access token for us as long as we supply a client ID, client secrets and refresh token.
Client Side WorkFlow of tokens
- The user is first redirected to Google's OAuth 2.0 server to start the authentication process.
- The user is asked for permission whether to grant the application, the requested access. The user can then consent or refuse to grant access to your application.
- If the user approves the access request, then the response contains an authorization code otherwise, the response contains an error message saying access denied.
- The authorization code can be exchanged for an access token which can be used to access the youtube user data.
- After obtaining an access token, our application can use that token to authorize API requests for a user account.
- When we use the refresh token for the authorization to obtain an access token, the access token represents the combined authorization and can be used for any of its scopes.
- OAuth handles the refresh tokens internally by exchanging it for access tokens for authorization. Refresh tokens are long life tokens so we can maintain the user session for a longer time.
Server Side WorkFlow of tokens
- The Google OAuth server authenticates the user and obtains consent from us for our application to access the requested scopes. The response is sent back to our application using the redirect URL you specified.
- The OAuth server receives our application's access request by using the URL (Scope) specified in the request and sends a response accordingly.
- The OAuth server uses the client secret mechanism as a means of authorizing a client, the application requesting an access token exchanges the client secret for the access token.The client secret must be kept confidential as it can be used to authenticate as a person and access the data. Only once the Users are authenticated (proven that they are whom they say they are), they are granted access to the API.
- After the OAuth server receives the authorisation code contained in our client secret json file, it can exchange the authorization code for an access token.
- Example of responses from the Google OAuth server:
An error response:
https://oauth2.example.com/auth?error=access_denied
An authorization code response:
https://oauth2.example.com/auth?code=4/P7q7W91a-oMsCeLvIaQm6bTrgtp7
Dependency required
The next thing that we are going to need so you can use the Google API Python client for directly sending the request to the YouTube data API through some already written functions so what I'm going to do is I'm just gonna make a very simple pip
command
Following dependency is required to access the youtube api. Install it using the command given below.
pip install google-api-python-client
Google API Python client is actually a Python client for dealing with the Google API and we're going to use that for interacting with the YouTube data API.
Google API Python client is the standard library for python to handle youtube data API related tasks.
Code 1 : Using API Key
Now what we are going to do is from APIclient.discovery, import build function. Build is actually a very interesting function which will simply create the resource object in the Google API Python client which can be used to interact with any Google API.
Assign the api key which you have copied from the google developer's console to a variable, say api_key.
from apiclient.discovery import build
api_key="XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
Now, we will create a youtube resource object. For doing that we have to just use build function. We have to just name the API that we want to interact with so let's say I want to interact with the YouTube API so youtube and we can also provide which version of the API will interact with. In this case we are using version 3 of the youtube data api to interact. We will also pass the developer key that is the api_key as the parameter. The api key acts as the credential for accessing the api.
youtube = build('youtube', 'v3', developerKey=api_key)
Youtube is actually a resource object which can be used for interacting with the YouTube Data API. This is how we can set a project for starting to interact with the YouTube Data API. We can call various functions using youtube resource object to access and use various functionalities of the Youtube Data API.
Code 2 : Using OAuth Authentication
If you are trying to deal with some protected resources some private resources of a user for example the permission of a user to like a video or comment on a video so for that kind of cases we need a better authentication framework and that's why we have something called OAuth 2.0. Oauth 2.0 is an authentication framework which provides a flow to the applications through which they can gain limited access to a user's protected resources. First we are going to import all the dependencies used.
Build is the same as used in the above case.InstalledAppFlow is a function that lets us specify the scope and client secret for the Oauth authenticcation to access the youtube data API.
from apiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
We will request user content consent so that the user can access so that app can access the users data so for that we need the oath client ID .This is basically allowing us to be able to use the OAuth flow for our application so for that we can simply select our application type as other because we are using a simple Python script and let me name it as "youtube_api" to create it. This client secret we just created. In order to use them you have to just click on this download button you can simply download a JSON file or for a client secret and then you have to simply put it in your project folder. Now we'll specify the client secret file path to access it and the scope URL to specify the scopeof the application.
client secret is a json format file used for providing details of the user to process the authentication. The structure of the client secret json is as follows -
Client Secret File example:
{
"installed":{
"client_id":"XXXXXXXXXXXXXXXXXXX",
"project_id":"youtubeapi-264219",
"auth_uri":"https://accounts.google.com/o/oauth2/auth",
"token_uri":"https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs",
"client_secret":"XXXXXXXXXXXXXXXXXXX",
"redirect_uris":[
"urn:ietf:wg:oauth:2.0:oob",
"http://localhost"
]
}
}
CLIENT_SECRET_FILE = '/client_secret_1.json'
SCOPES = ['https://www.googleapis.com/auth/youtube']
Now it's time to run the authentication flow so for that first of all, we create the flow object and now we will run the flow and we will be getting the credentials once that flow is complete and finally we will create a YouTube resource object by using the build function. We have to specify that we need to use version 3. Now we'll be giving the credentials so reusing the credentials argument for creating this youtube resource . Let us run it so we got a URL to visit so we are going to click on this URL to authorize this application .
flow = InstalledAppFlow.from_client_secrets_file(CLIENT_SECRET_FILE, SCOPES)
credentials = flow.run_console()
youtube = build('youtube', 'v3', credentials=credentials)
To perform a demo we will be liking a video using our authenticated google account.We will pass the youtube video id which can be found in the youtube video URL. For example in this case i have taken url of this video: https://www.youtube.com/watch?v=YbJOTdZBX1g. We can pass 'like','dislike' or 'none' as the value of rating parameter to perform the respective tasks.
Now we will execute the script to send a request to the youtube server to like ths particular video.
youtube.videos().rate(rating='like', id='YbJOTdZBX1g').execute()
Sign up for FREE 3 months of Amazon Music. YOU MUST NOT MISS.