我尝试使用 Python 请求模块连接到 Riot Games API,但它一直给出 401 错误。我添加了 API key ,但它仍然显示未经授权。如果有人知道代码有什么问题,我们将不胜感激。
我尝试过修补,我只有这段代码:
import os
import requests
API_KEY = os.getenv("riot-key")
URL = "https://americas.api.riotgames.com/riot"
headers = {
"Authorization": "Bearer " + API_KEY
}
response = requests.get(URL, headers=headers)
if response.status_code == 200:
print(response.json())
else:
print("Request failed with status code:", response.status_code)
我真正得出的结论是 API key 本身不是问题,而是请求调用。
最佳答案
It looks like由于某种原因,Riot Games API 使用 header X-Riot-Token
来传递身份验证 token ,而不是 Authorization
。
import os
import requests
API_KEY = os.getenv("riot-key")
URL = "https://americas.api.riotgames.com/riot"
headers = {
"X-Riot-Token": API_KEY
}
response = requests.get(URL, headers=headers)
if response.status_code == 200:
print(response.json())
else:
print("Request failed with status code:", response.status_code)
您还可以将 API key 作为查询字符串参数传递,但是在某些情况下这可能会稍微不那么安全。
import os
import requests
API_KEY = os.getenv("riot-key")
URL = "https://americas.api.riotgames.com/riot?api_key=" + API_KEY
response = requests.get(URL)
if response.status_code == 200:
print(response.json())
else:
print("Request failed with status code:", response.status_code)
关于python - 如何通过 API key 使用 Riot Games API?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75338720/