How do i access and manipulate the api values

I would like some direction on how i can access the data and do some modifications etc. for example accessing and listing only emails, etc please

import requests,json

api = "https://reqres.in/api/users?page=2"

test = requests.get(api)
x = test.json()

data_structure = []
data_structure.append(x)


print(data_structure)

Output [{‘page’: 2, ‘per_page’: 6, ‘total’: 12, ‘total_pages’: 2, ‘data’: [{‘id’: 7, ’email’: ‘[email protected]’, ‘first_name’: ‘Michael’, ‘last_name’: ‘Lawson’, ‘avatar’: ‘https://reqres.in/img/faces/7-image.jpg’}, {‘id’: 8, ’email’: ‘lindsay.fergu[email protected]’, ‘first_name’: ‘Lindsay’, ‘last_name’: ‘Ferguson’, ‘avatar’: ‘https://reqres.in/img/faces/8-image.jpg’}, {‘id’: 9, ’email’: ‘[email protected]’, ‘first_name’: ‘Tobias’, ‘last_name’: ‘Funke’, ‘avatar’: ‘https://reqres.in/img/faces/9-image.jpg’}, {‘id’: 10, ’email’: ‘[email protected]’, ‘first_name’: ‘Byron’, ‘last_name’: ‘Fields’, ‘avatar’: ‘https://reqres.in/img/faces/10-image.jpg’}, {‘id’: 11, ’email’: ‘[email protected]’, ‘first_name’: ‘George’, ‘last_name’: ‘Edwards’, ‘avatar’: ‘https://reqres.in/img/faces/11-image.jpg’}, {‘id’: 12, ’email’: ‘[email protected]’, ‘first_name’: ‘Rachel’, ‘last_name’: ‘Howell’, ‘avatar’: ‘https://reqres.in/img/faces/12-image.jpg’}], ‘support’: {‘url’: ‘https://reqres.in/#support-heading’, ‘text’: ‘To keep ReqRes free, contributions towards server costs are appreciated!’}}]

Answer

First, I highly recommend you to install the JSON Viewer extension, which will help you a lot to see what’s going on your API.

https://chrome.google.com/webstore/detail/json-viewer/gbmdgpbipfallnflgajpaliibnhdgobh?hl=es

Then, you don’t need to create a new list, since the x = test.json() already outputs the same dictionary you brought from the API.

So your first chunk of code should look like this

import requests,json

api = "https://reqres.in/api/users?page=2"

test = requests.get(api)
x = test.json()

Then you can access all the data inside that dictionary, for example let’s get all the emails.

To make it easier you should go to the api link using JSON Viewer to see the structure of your dictionary.

To access the emails we first need to access the “data” key on your dictionary

import requests,json

api = "https://reqres.in/api/users?page=2"

test = requests.get(api)
x = test.json()

data_list = x["data"]

After that you can see that data_list is a new list of dictionaries with all the data from each element on your API (in your case each id).

So finally, to access the emails, we need to iterate trough that list and get the “email” key from each dictionary on the list.

import requests,json

api = "https://reqres.in/api/users?page=2"

test = requests.get(api)
x = test.json()

data_list = x["data"]

for i in data_list:
    print(i["email"])

And that my friend, is how you get info from an API, the same way you manipulate lists and dictionaries.