DEV Community

Cover image for "How to Get a 'GET' Response as an Array in Python
NUR ARIF
NUR ARIF

Posted on

"How to Get a 'GET' Response as an Array in Python

If you are working with APIs in Python, you may want to retrieve the data from a GET request and store it as an array. In this tutorial, we will go over how to do this using the requests library and the json() method.
First, let's make a GET request to retrieve the data. We will use the requests library to send the request and store the response in a variable.

import requests

url = 'https://api.example.com/endpoint'
response = requests.get(url)

Enter fullscreen mode Exit fullscreen mode

Next, we can use the json() method to convert the response to a dictionary.

data = response.json()

Enter fullscreen mode Exit fullscreen mode

Now, let's say that the data we want is stored in the 'results' key of the dictionary. We can access it like this:

results = data['results']

Enter fullscreen mode Exit fullscreen mode

The 'results' key contains a list of dictionaries, so we can iterate over the list and store each dictionary in an array.

array = []
for result in results:
  array.append(result)
Enter fullscreen mode Exit fullscreen mode

That's it! Now you have the 'GET' response stored as an array in Python. You can access the data in the array by using the index, just like with any other list.

print(array[0])  # prints the first item in the array
print(array[1])  # prints the second item in the array

Enter fullscreen mode Exit fullscreen mode

I hope this tutorial has helped you learn how to get a 'GET' response as an array in Python. If you have any questions, please leave a comment below."

Top comments (0)