StackUnderFlow
StackUnderFlow

Reputation: 367

How to loop a list of queries via restful api?

I'm trying to display each of the fruits total mention count below from a rest api request.

Pretty new to python so wondering the best method to run this.

Below in the parameters, if I hardcode "apple" for example, I am able to successfully get the total amount of times "apple" was mentioned.

Now I'm trying to loop through the "query" list of fruits and want to display the total counts for each of the fruits.

Not sure the best route in doing this. Tried running a for loop below and adding it to the query parameter. Do I need to run a loop on the entire URL request?

import requests

query = ["apple", "orange", "banana", "cherry", "blueberry"]


def mentions():
    for d in query:
        return d


url = 'https://api.fruits.com/Search?'
parameters = {
    "key": "1234567890abc",
    "rt": "json",
    "mode": "full",
    "query": mentions()
}

response = requests.get(url, params=parameters)
data = response.json()

print(data['response']['TotalFound'])

Upvotes: 0

Views: 885

Answers (1)

Errol
Errol

Reputation: 610

Try this:

import requests

query = ["apple", "orange", "banana", "cherry", "blueberry"]


url = 'https://api.fruits.com/Search?'

data_list = []

for item in query:
    parameters = {
        "key": "1234567890abc",
        "rt": "json",
        "mode": "full",
        "query": item
    }
    response = requests.get(url, params=parameters)
    data = response.json()
    data_list.append(data['response']['TotalFound'])

print(data_list)

Upvotes: 1

Related Questions