psf / requests

A simple, yet elegant, HTTP library.
https://requests.readthedocs.io/en/latest/
Apache License 2.0
52.04k stars 9.31k forks source link

Getting 401 unauthorized status in an API #6470

Closed subhendudash02 closed 1 year ago

subhendudash02 commented 1 year ago

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)
Mariatta commented 1 year ago

This issue doesn't look like a problem with the requests library. You probably should ask for further help in stackoverflow, but one hint:

x_app_id = config['nutritionix']['API_ID']

Here you're using 'API_ID' string instead of the API_ID variable.

nateprewitt commented 1 year ago

Yep, I believe @Mariatta is right. Thank you!

I'm going to close this out because it doesn't appear to be an issue with Requests.

subhendudash02 commented 1 year ago

This issue doesn't look like a problem with the requests library. You probably should ask for further help in stackoverflow, but one hint:

x_app_id = config['nutritionix']['API_ID']

Here you're using 'API_ID' string instead of the API_ID variable.

This solution didn't work out for me and I didn't realise that this issue isn't related to requests library, my bad. I will post this in stack overflow.

Well, thanks @Mariatta for helping me out!