Home > Blockchain >  Function to extract API queries results and output them as list or dictionary
Function to extract API queries results and output them as list or dictionary

Time:06-03

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?

CodePudding user response:

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:

  1. instantiate an empty list total
  2. loop over each location item, it looks like you don't need the key param so I removed it
  3. append the results of the query to the total list
  4. repeat until done
  5. once all the items have been iterated, then return the list containing the results of the query
  • Related