I was making a POST request in nutritionix API using requests module. In one of the API route which is https://trackapi.nutritionix.com/v2/natural/nutrients, which returns all the necessary details for any food item if we pass json as {"query": <any_name>} and headers as x-app-id and x-app-key.
It works fine in Postman, but in Python it shows 401 unauthorized status if I fetch the x-app-id and x-app-key from .cfg file.
The format of that cfg file is
[nutritionix]
API_ID=<api-id>
API_KEY=<api-key>
I am fetching all those keys using configparser module, I am able to print those keys in the terminal, but it shows 401 error. But if I directly paste these keys into the code directly (which is not recommended), it is showing 200 status.
I am pasting the code below for reference:
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)
I don't know why the API key and the ID is not fetching from cfg file, whereas in other files, it is fetching properly.
I was expecting to fetch the API keys from cfg and show the required result from the API.
This code will works
And credential without " or ' in
secrets.cfgfile.Result