Generate Access Tokens
Learn to generate app access and user access tokens for the Twitch API.
We'll cover the following
Generate an app access token
With our client ID and secret, we finally have everything we need to generate our access tokens. Let's start with the app access token.
We'll use the OAuth client credential grant flow to get our app access token. In this grant flow, the server directly authorizes an application, rather than a user, by generating an access token for the application once it provides its client ID and secret.
The illustration below gives an overview of this grant flow.
To retrieve our access token, we need to send an HTTP POST request to the following URL:
https://id.twitch.tv/oauth2/token
Here are the query parameters we pass to this call:
Parameter | Type | Category | Description |
| String | Required | This is the registered client ID of an application created on the Twitch Developer Console |
| String | Required | This is the registered client secret of an application created on the Twitch Developer Console. |
| String | Required | This is the type of grant flow we're using. Since we're using the client credential grant flow, the value of this parameter will be |
If the POST request we make to this URL is successful, the server responds with a JSON object containing the following properties:
Property | Type | Description |
| String | This is the app access token generated from the request. |
| Number | This is the time in seconds for which the generated token is valid. |
| String | This is the type of token generated from the request. Using the client credential grant flow, the type of token we get is |
Let's make an actual request to retrieve our access token. The code to make the call has already been provided, and it automatically extracts the access token for us. Therefore, all we need to do is provide our client ID and secret. Let's do so by following the steps below:
- Click "Edit" in the widget below.
- Provide your client ID and secret in the
CLIENT_ID
andCLIENT_SECRET
fields, respectively. - Click "Run" to run the code.
- When the access token is generated and extracted, click "Save" to save the token for use throughout the course.
Note: As we mentioned earlier, the token will expire after a certain amount of time has passed, specified by the
expires_in
field. If your access token expires, you can always return to this section and generate a new token.
# Importing the required librariesimport requestsimport json# Defining the URL to which we will make the requesturl = 'https://id.twitch.tv/oauth2/token'# Defining the parameters to be passed to the requestdata = {'client_id' : '{{CLIENT_ID}}','client_secret' : '{{CLIENT_SECRET}}','grant_type' : 'client_credentials'}# Making a POST request to the URL to retrieve the access tokenresponse = requests.post(url, params=data).json()# Beautifying and printing the responseprint(json.dumps(response, indent=4))
Generate a user access token
We've learned to generate the app access token. Let's turn our attention to user access tokens.
User access tokens come in handy when we want our application to access a user's resources. The OAuth grant flow we'll use for this access token is the implicit grant flow. In this flow, the server directly authorizes a client by providing it with an access token.
To retrieve a token using this flow, we need to enter the following URL in our browser:
https://id.twitch.tv/oauth2/authorize
Here are the query parameters we need to pass to this URL:
Parameter | Type | Category | Description |
| String | Required | This is the registered client ID of an application created on the Twitch Developer Console. |
| String | Required | This is the URI to which the access token will be sent. This will be the URI we registered for the application we created on the Twitch console. |
| String | Required | This is the type of response we expect from the server. Since we want an access token, the value of this parameter will be |
| String | Required | This is a URL-encoded string of scopes that the application is allowed to access. |
| Boolean | Optional | This shows whether the user will be forced to reverify the application's access to their resources. This is in case the application requests access to some resources repeatedly. The default value is |
| String | Optional | This is a state string to prevent cross-site request forgery (CSRF) attacks. |
Before we make a token request, let's run an application so it’s served on Educative's VM URL that we registered as a redirect URL for our application on Twitch. Since the server returns the generated token to the registered redirect URL, an application must already be running on the specified URL.
We'll run a simple Flask application for this purpose. Simply click "Run" on the widget below. Once the application becomes visible on the URL, proceed to the next step of this flow.
<!DOCTYPE html> <html> <body> <h1>Welcome to Flask!</h1> <p style="font-size:20px" id="token"> Your access token will be displayed here. </p> <script> if(window.location.hash) { document.getElementById("token").innerHTML = "Your access token is " + window.location.hash.substring(14,44); } else { document.getElementById("token").innerHTML = "Your access token will be displayed here." } </script> </body> </html>
With an application running on the URL, we can make a token request. Let's follow the steps below:
- If you haven't already, provide your client ID in the
CLIENT_ID
field below. - Click "Run" on the widget below and open the output link in a separate browser tab.
- If you aren't already, log in to Twitch, and click "Authorize" to authorize our application to access the scopes we've defined.
- Once you're redirected to our Flask application, copy the access token displayed on the application. This token can also be found in the URL fragment, identified by the
access_token
key. - Store the access key somewhere safe.
Note: Like the app access token, the user access token will also expire after a certain amount of time has passed. If your access token expires, you can always return to this section and follow these steps again to generate a new token.
# The URL to which we will make the requestbase_url = 'https://id.twitch.tv/oauth2/authorize'# Defining the parameters to be passed to the requestclient_id = '{{CLIENT_ID}}'redirect_uri = '{{EDUCATIVE_LIVE_VM_URL}}'response_type = 'token'scopes = ['channel:read:editors','channel:read:subscriptions','channel:manage:broadcast','channel:manage:schedule','clips:edit','user:read:blocked_users','user:read:email','user:read:follows','user:manage:blocked_users','user:edit']# Generating the final URL by appending and URL-encoding the parametersfinal_url = generate_url(base_url, client_id, redirect_uri, response_type, scopes)# Printing the final URL to the consoleprint(final_url)
This token has all the scopes required to run all the endpoints discussed in this course, so we don't have to worry about generating a new token for each individual call.
Note: To learn more about scopes and what they define, visit this lesson.
Save the token
Let's save our newly generated user access token to use throughout the course. The code below saves the token and makes a test call to one of the Twitch API's endpoints to check whether the access token is valid.
Provide your user access token in the USER_ACCESS_TOKEN
field below and run the code. This fetches the details of our account on Twitch.
import requestsimport json# Defining the headers required for the requestheaders = {'Authorization' : 'Bearer {{USER_ACCESS_TOKEN}}','Client-Id' : '{{CLIENT_ID}}'}# Making an API call to an endpointresponse = requests.get('https://api.twitch.tv/helix/users', headers=headers).json()# Beautifying and printing the responseprint(json.dumps(response, indent=4))
With our access tokens saved, we can finally get started with making calls to the numerous endpoints of the Twitch API.