python - 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?
解决方案
您将在请求中发送 1 个标头。该标题名为Ocp-Apim-Subscription-Key
. 从您分享的那封电子邮件来看,他们希望标头包含一对名为API_KEY
.
如果这是问题,以下应该解决它。
headers = {'API_KEY': '{key}'.format(key=api_key)}
将字符串格式化为字符串变量的值是多余的。您的代码可以通过删除调用来清理format()
headers = {'API_KEY': api_key}
要记住的一件事
您在公共站点上发布了您的 API 密钥。鉴于 API 密钥用于身份验证,最佳做法是取消对当前密钥的身份验证并请求新密钥,以防止未经授权的使用。
推荐阅读
- angularjs - bash:http-server:找不到命令
- python - 创建自定义估计器:状态均值估计器
- android - 在 Kotlin 中按属性和最大值过滤重复项
- json - Swift JSONSerialization,如何正确格式化 REST 服务器?
- javascript - 构建 Vue 组件库时包含字体和资源
- angular - ag-grid:如何从网格列中获取或保存排序状态
- angular - *ngFor 遍历包含对象的数组
- php - 如何在codeginter中使用json从数据库中检索数据
- asp.net - SharePoint 加载视图状态失败。要加载视图状态的控件树必须与用于加载的 cntrl 树匹配
- javascript - 如何检索提交回 UI 的动态响应式表单值?