0

I am trying to fetch Twitch's user ID through their API, but I am not being able to do so. This is my first time using APIs.

Right now this is my code:

import requests
import json

parameters = {
    "login": "shroud,impakt"
}

response = requests.get("https://api.twitch.tv/kraken/users/", params=parameters, headers={'Accept': 'application/vnd.twitchtv.v5+json', 'Client-ID': 'xytnh8lrt9k8l4lpv22gogmdnfp1bg'})

userid = response.json()["users"][0]["_id"]

ids = []

for d in userid:
    uid = d["_id"]
    ids.append(uid)

print(ids)

I believe I may need to use a for loop, but am not understanding how to approach this.

Here is an example of the data response:

{
    "_total": 1,
    "users": [
        {
            "display_name": "shroud",
            "_id": "37402112",
            "name": "shroud",
            "type": "user",
            "bio": "I'm back baby",
            "created_at": "2012-11-03T15:50:32.87847Z",
            "updated_at": "2021-06-18T15:48:05.411438Z",
            "logo": "https://static-cdn.jtvnw.net/jtv_user_pictures/7ed5e0c6-0191-4eef-8328-4af6e4ea5318-profile_image-300x300.png"
        }
    ]
}

When running I get the error TypeError: string indices must be integers.

overclock
  • 585
  • 3
  • 20
  • 2
    give an example of what the data response looks like. Also, you can remove a lot of code by just doing `print(response.json()["users"]["_id"])` – Cireo Jun 19 '21 at 02:01
  • @Cireo I added the example. – overclock Jun 19 '21 at 02:03
  • `parsed_json["users"]` is a list, as indicated by its value in `[...]`. You need to access its contents like any regular Python list, by indexing each element (`["users"][0]`) or looping through the list. Then you get 1 dictionary, which you can then get each key-value like any regular Python dictionary. – Gino Mempin Jun 19 '21 at 02:12
  • Does this answer your question? [Getting a list of values from a list of dicts](https://stackoverflow.com/questions/7271482/getting-a-list-of-values-from-a-list-of-dicts) – Gino Mempin Jun 19 '21 at 02:19
  • @GinoMempin it shined a light, but I am still not able to fetch several ``_id``s. I have updated my code in the question. – overclock Jun 19 '21 at 02:40
  • You need to loop over the list, `response.json()["users"]`. I recommend learning how to use a debugger or even basic print-debugging, to see what value each variable has on each line. – Gino Mempin Jun 19 '21 at 02:42

1 Answers1

1

"users" is a list. So try using:

print(response.json()["users"][0]["_id"])

To get all users try:

for i in response.json()["users"]:
    print(i["_id"])
Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
Hot Shot
  • 115
  • 1
  • 5
  • This will only give the first ``_id``. I am trying to understand how to loop it to get other ids if I had multiple usernames in the parameters. – overclock Jun 19 '21 at 02:28