我正在使用请求模块在Nutritionix API中发出POST请求.在其中一个为https://trackapi.nutritionix.com/v2/natural/nutrients
的API路径中,如果我们将json作为{"query": <any_name>}
传递,将Header作为x-app-id
和x-app-key
传递,它将返回任何食品的所有必要详细信息.
它在Postman中运行良好,但在Python中,如果我从.cfg文件中获取x-app-id和x-app-key,它将显示401未授权状态.
CFG文件格式为
[nutritionix]
API_ID=<api-id>
API_KEY=<api-key>
我正在使用配置解析器模块获取所有这些密钥,我可以在终端中打印这些密钥,但它显示401错误.但如果我直接将这些键直接粘贴到代码中(不推荐),它将显示200状态.
我粘贴以下代码以供参考:
import requests
from configparser import ConfigParser
config = ConfigParser()
config.read('./secrets.cfg')
x_app_id = config['nutritionix']['API_ID']
x_app_key = config['nutritionix']['API_KEY']
headers = {
'Accept':'application/json',
'Content-Type': 'application/json',
"x-app-id": x_app_id,
"x-app-key": x_app_key,
}
url = 'https://trackapi.nutritionix.com/v2/natural/nutrients/'
def get_details(prompt: str):
food_details = requests.post(url, headers=headers, json={"query": prompt})
print(food_details)
我不知道为什么API密钥和ID不能从CFG文件中获取,而在其他文件中,它可以正确地获取.
我希望从CFG获取API密钥,并显示API所需的结果.