Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
82 views
in Technique[技术] by (71.8m points)

python - How to loop through list during API call?

I am looking to loop through about 5 stock tickers using an API. Currently I have "MSFT" as the only stock being called; however, I would like to make a stock list to return multiple responses.

For example:

stock_list = ["MSFT", "AAPL", "LMD", "TSLA", "FLGT"]

How can I request all 5 of these stocks to the querystring to print each response? Here is what I have currently which prints only "MSFT" into a json format...

import requests

#Use RapidAPI request to call info on Stocks
url = "https://alpha-vantage.p.rapidapi.com/query"

querystring = {"function":"GLOBAL_QUOTE","symbol": "MSFT"}


headers = {
    'x-rapidapi-key': "KEY INSERTED HERE,
    'x-rapidapi-host': "alpha-vantage.p.rapidapi.com"
    }

response = requests.request("GET", url, headers=headers, params=querystring)
question from:https://stackoverflow.com/questions/65861376/how-to-loop-through-list-during-api-call

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try using a for loop.

import requests

url = 'https://alpha-vantage.p.rapidapi.com/query'
headers = {
    'x-rapidapi-key': '<API KEY>',
    'x-rapidapi-host': 'alpha-vantage.p.rapidapi.com',
}

tickers = ['MSFT', 'AAPL', 'LMD', 'TSLA', 'FLGT']

for ticker in tickers:
    querystring = {'function': 'GLOBAL_QUOTE', 'symbol': ticker}
    r = requests.get(url, headers=headers, params=querystring)
    print(r.json())

You can also try pretty printing the json output using the json module.

import json

# ... your code ...

for ticker in tickers:
    # ... your code ...

    print(json.dumps(r.json(), indent=2))

Also, you should delete your API key before its abused by anyone! These have to be kept safe somewhere.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...