【问题标题】:How to loop through list during API call?API调用期间如何循环列表?
【发布时间】:2021-01-23 16:07:18
【问题描述】:

我希望使用 API 循环浏览大约 5 个股票代码。目前,我将“MSFT”作为唯一被调用的股票;但是,我想制作一个股票列表以返回多个响应。

例如:

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

如何向查询字符串请求所有 5 只股票以打印每个响应?这是我目前仅将“MSFT”打印为 json 格式的内容...

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)

【问题讨论】:

  • 这是当前输出:{'Global Quote': {'01.符号':'MSFT','02。打开':'227.0800','03。高':'230.0700','04。低':'225.8000','05。价格':'225.9500','06.卷':'30172663','07。最近交易日': '2021-01-22', '08.上一个收盘价': '224.9700', '09.变化':'0.9800','10。变化百分比':'0.4356%'}}状态码:200
  • 你试过迭代stock_list吗?

标签: python api call


【解决方案1】:

尝试使用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())

您也可以尝试使用 json 模块漂亮地打印 json 输出。

import json

# ... your code ...

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

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

此外,您应该在 API 密钥被任何人滥用之前删除它!这些必须妥善保存在某个地方。

【讨论】:

  • 太棒了!谢谢尼克。会的!
猜你喜欢
  • 2019-05-09
  • 2011-05-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多