Generate Access Tokens

Learn to generate app access and user access tokens for the Twitch API.

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

client_id

String

Required

This is the registered client ID of an application created on the Twitch Developer Console

client_secret

String

Required

This is the registered client secret of an application created on the Twitch Developer Console.

grant_type

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 client_credentials.

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

access_token

String

This is the app access token generated from the request.

expires_in

Number

This is the time in seconds for which the generated token is valid.

token_type

String

This is the type of token generated from the request. Using the client credential grant flow, the type of token we get is bearer.

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:

  1. Click "Edit" in the widget below.
  2. Provide your client ID and secret in the CLIENT_ID and CLIENT_SECRET fields, respectively.
  3. Click "Run" to run the code.
  4. 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.

Press + to interact
# Importing the required libraries
import requests
import json
# Defining the URL to which we will make the request
url = 'https://id.twitch.tv/oauth2/token'
# Defining the parameters to be passed to the request
data = {
'client_id' : '{{CLIENT_ID}}',
'client_secret' : '{{CLIENT_SECRET}}',
'grant_type' : 'client_credentials'
}
# Making a POST request to the URL to retrieve the access token
response = requests.post(url, params=data).json()
# Beautifying and printing the response
print(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

client_id

String

Required

This is the registered client ID of an application created on the Twitch Developer Console.

redirect_uri

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.

response_type

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 token.

scope

String

Required

This is a URL-encoded string of scopes that the application is allowed to access.

force_verify

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 false.

state

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>
A simple Flask application where the access token is returned

With an application running on the URL, we can make a token request. Let's follow the steps below:

  1. If you haven't already, provide your client ID in the CLIENT_ID field below.
  2. Click "Run" on the widget below and open the output link in a separate browser tab.
  3. If you aren't already, log in to Twitch, and click "Authorize" to authorize our application to access the scopes we've defined.
  4. 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.
  5. 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.

Press + to interact
# The URL to which we will make the request
base_url = 'https://id.twitch.tv/oauth2/authorize'
# Defining the parameters to be passed to the request
client_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 parameters
final_url = generate_url(base_url, client_id, redirect_uri, response_type, scopes)
# Printing the final URL to the console
print(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.

Press + to interact
import requests
import json
# Defining the headers required for the request
headers = {
'Authorization' : 'Bearer {{USER_ACCESS_TOKEN}}',
'Client-Id' : '{{CLIENT_ID}}'
}
# Making an API call to an endpoint
response = requests.get('https://api.twitch.tv/helix/users', headers=headers).json()
# Beautifying and printing the response
print(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.