【问题标题】:How do I make an API call and authenticate it with a given API key using Python?如何使用 Python 进行 API 调用并使用给定的 API 密钥对其进行身份验证?
【发布时间】:2021-02-07 19:03:17
【问题描述】:

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

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

请让我知道我可以对我的代码进行哪些更改。任何帮助表示赞赏。

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

PS:我的代码在发布时出现了碎片,但它都在一个功能中。

def 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()

【问题讨论】:

  • 尝试将'key'改为'Ocp-Apim-Subscription-Key'!如果这不起作用,请尝试将 headers={'Ocp-Apim-Subscription-Key': '**key**'} 作为附加参数。

标签: python api parameters data-science http-authentication


【解决方案1】:
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
)

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

      根据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,
      ...
      

      【讨论】:

        猜你喜欢
        • 2017-06-07
        • 1970-01-01
        • 1970-01-01
        • 2019-02-17
        • 1970-01-01
        • 2020-04-11
        • 1970-01-01
        • 2011-12-10
        • 1970-01-01
        相关资源
        最近更新 更多