I’m guessing you’re here because Python threw a, ” TypeError: string indices must be integers”. I got this error after successfully hitting a REST endpoint using the requests Python library and attempting to access one of the responses elements. If you need an example of hitting an endpoint, try this out. It shouldn’t be much different.
Recreating the Problem
import requests
# Where url can be your favorite REST API
response = requests.request('GET', url=url)
# This is where your issue is potentially occurring
data = response.text['data']
You’ll get, “TypeError: string indices must be integers” as a
The Solution
import requests
# Where url can be your favorite REST API
response = requests.request('GET', url=url)
# This is where the magic happens
data = response.json()['data']
You should no longer get be getting the error when this change is made. The error explains that strings can only be indexed by integers because Python allows you to pull an element in a string based on its position. For example, I can pull the first element of “The” as follows.
the = "The"
firstLetter = the[0]
print firstLetter
The solution will be fairly similar if you’re making a POST request. In the weirdest of cases you may have to resort to using the ast library. I’ll cover that in the future. Cheers and happy coding!