I need a list of the results of an API call using gql for a dictionary of IDs. Let's say I have a dictionary of locations, ex: {"tokyo": "111", "rio": "112", "LA": "113"}
, and I need to query on an API the info for each location, ex:
transport = AIOHTTPTransport(url=API_URL, headers=HEADERS)
client = Client(transport=transport)
params = {
"id": "111"
"time": {"from": "2022-05-10", "to": "2022-05-19"},
}
q = gql(query)
r = client.execute(q, variable_values=params)
pprint.pprint(r)
I am trying to design a function that extracts the results of the queries for each ID at once and outputs it as a list. However I am new to python and I am unsure of how to go about it. I started with a function and a for loop, something like this:
total = []
def get_info(dictionary_location):
for key, value in dictionary_location.items():
global params
params = {
"lineId": value,
"time": {"from": "2022-05-10", "to": "2022-05-19"}
}
q = gql(query)
r = client.execute(q, variable_values = params)
return total.append(r)
But it's not working. Does anyone have an input on the logic/syntax?
There are some issues with your code. The main one is that because you are returning total.append(r)
within the loop, then only the first iteration of the loop is done. Make these changes into your code:
def get_info(dictionary_location):
total = []
for value in dictionary_location.values():
params = {
"lineId": value,
"time": {"from": "2022-05-10", "to": "2022-05-19"}
}
q = gql(query)
r = client.execute(q, variable_values = params)
total.append(r)
return total
In this way you will:
total
key
param so I removed itquery
to the total
listquery