如何使用 Python 进行 API 调用并使用给定的 API 密钥对其进行身份验证?

问题描述

这是我的代码,用于从包含数据科学项目的篮球数据的端点中提取球员数据。注意:我更改了自订阅以来获得的实际 API 密钥的名称。出于隐私目的,我更改了用户名/密码。使用正确的凭据,我不会收到语法错误,但状态代码总是返回 401。由于它不接受 API 密钥,我还添加了我的帐户用户名、密码和 HTTP 身份验证标头,但状态代码仍然返回 401。

如果这是相关的,这是网站在开发者门户中的建议: **API 密钥可以作为查询参数或使用以下 HTTP 请求标头传递。

请告诉我可以对代码进行哪些更改。任何帮助表示赞赏。

Ocp-Apim-Subscription-Key:{key}**

PS:我的代码在发布时变得碎片化,但它都在一个函数中。

定义 getData():

user_name = "name@gmail.com"

api_endpoint = "https://api.sportsdata.io/v3/nba/stats/json/PlayerGameStatsByDate/2020-FEB7" api_key = "a45;lkf"

password = "ksaljd"

header = "Ocp-Apim-Subscription-Key"
ParaMS = {'user': user_name,'pass': password,'header': header,'key': api_key} 
response = requests.get(url = api_endpoint,data = ParaMS)
print(response.status_code)
file = open("Data.csv","w")
file.write(response.text)
file.close()

解决方法

def _get_auth_headers() -> dict:
    return {
        'Content-Type': 'application/json','Ocp-Apim-Subscription-Key': "`Insert key here`"
    }
api_endpoint = "https://api.sportsdata.io/v3/nba/stats/json/PlayerGameStatsByDate/2020-FEB7"
PARAMS = {
    # Your params here
}
response = requests.get(
    api_endpoint,headers=_get_auth_headers(),params=PARAMS
)
,

您需要在 dict 参数中传递 headers 而不是一个字符串,并且 auth param 存在,以便您可以按如下方式使用它:

def getData():
    [...]

    header = {
        "Ocp-Apim-Subscription-Key": api_key
    }
    
    [...]
    response = requests.get(url = api_endpoint,data = PARAMS,headers=header,auth = (user_name,password))
,

根据API documentation,您不需要提供电子邮件和密码。您只需将您的 API Key 添加到标题:

import requests

r = requests.get(url='https://api.sportsdata.io/v3/nba/stats/json/PlayerGameStatsByDate/2020-FEB7',headers={'Ocp-Apim-Subscription-Key': 'API_KEY'})
print(r.json())

输出:

[{
        'StatID': 768904,'TeamID': 25,'PlayerID': 20000788,'SeasonType': 1,'Season': 2020,'Name': 'Tim Hardaway Jr.','Team': 'DAL','Position': 'SF','Started': 1,'FanDuelSalary': 7183,'DraftKingsSalary': 7623,'FantasyDataSalary': 7623,...