pythonhttppython-requeststwitchtwitch-api

Issues accessing Twitch API through Python


I am trying to access the Twitch API to make a simple request for channel details. I am consistently being met with a 401 Unauthorised error despite feeding in the OAUTH code I am generating successfully. I am using the formatting found in the docs:

GET 'https://api.twitch.tv/helix/search/channels?query=a_seagull' \
--header 'client-id: wbmytr93xzw8zbg0p1izqyzzc5mbiz' \
--header 'Authorization: Bearer 2gbdx6oar67tqtcmt49t3wpcgycthx'

This is what is written on the website. I have translated this into Python:

import os
import requests

URL = "https://id.twitch.tv/oauth2/token"
CLIENT_ID = os.environ['CLIENT_ID']
CLIENT_SECRET = os.environ['CLIENT_SECRET']
GRANT_TYPE = "client_credentials"
PARAMS = {
  "client_id": CLIENT_ID,
  "client_secret": CLIENT_SECRET,
  "grant_type": GRANT_TYPE
}

r1 = requests.post(url = URL, params = PARAMS)

token = r1.json()["access_token"]


URL2 = "https://api.twitch.tv/helix/search/channels?query=reisu1337"
PARAMS2 = {
  "client_id": CLIENT_ID,
  "authorization": f"Bearer {token}"
}

r2 = requests.get(url = URL2, params = PARAMS2)

data = r2.json()

The first section of code that gets the auth token works fine, but it isn't accepted when fed into the second half, giving the following error:

{'error': 'Unauthorized', 'status': 401, 'message': 'OAuth token is missing'}

My question is how can I get the API to accept the auth token and process my request. Thanks in advance for any help :)

Edit - Repl link to run/fork - https://replit.com/@reisu1337/TwitchAPICall


Solution

  • headers = {
        'Client-ID': client_id,
        'Authorization': 'Bearer ' + keys['access_token']
    }
    
    print(headers)
    
    stream = requests.get('https://api.twitch.tv/helix/streams?user_login=' + streamer_name, headers=headers)
    

    You need to pass headers, not params.