首页 > 解决方案 > bad key error occurred when tried to fetch data from api endpoint in python?

问题描述

I tried to fetch data from api endpoint using request, but I got a bad key error. In my case, I provided api-key and endpoint url, so I used request to get json content of the data then used pandas to create data frame. I looked into SO but didn't find a clue how to get over this. Does anyone have possible thoughts or attempts to fix this? How can I correctly fetch data from api endpoint? Any idea?

my attempt

I tried to fetch data from this site: market data

import requests
import pandas as pd

api_key = 'ec95a478-e46e-47f9-b57d-3d19012d527d'
url = 'https://apps.fas.usda.gov/OpenData/api/esr/countries'
headers = {'Ocp-Apim-Subscription-Key': '{key}'.format(key=api_key)}
jsonData = requests.get(url, headers=headers).json()
df = pd.read_json(json.dumps(jsonData)

but I got this error after running the above codes:

'Bad API Key'

I accessed to this api and got this instruction as follow:

Hello Adam, your custom API key is ********---****-3d19012d527d Show Please copy and paste your API key into api_key text box in Swagger window below and start exploring the API. Please ues your custom key as name value pair API_KEY:Value in HTTP Header, when making API request from your applications.

where am I wrong in my above attempt? How can I correctly fetch data from any API endpoint on this site? Can anyone suggest a possible way of fetching data from api endpoints with json, request, and pandas? Any thoughts?

标签: pythonjsonpandasapi

解决方案


您将在请求中发送 1 个标头。该标题名为Ocp-Apim-Subscription-Key. 从您分享的那封电子邮件来看,他们希望标头包含一对名为API_KEY.

如果这是问题,以下应该解决它。

headers = {'API_KEY': '{key}'.format(key=api_key)}

将字符串格式化为字符串变量的值是多余的。您的代码可以通过删除调用来清理format()

headers = {'API_KEY': api_key}

要记住的一件事

您在公共站点上发布了您的 API 密钥。鉴于 API 密钥用于身份验证,最佳做法是取消对当前密钥的身份验证并请求新密钥,以防止未经授权的使用。


推荐阅读