2

I'm attempting to request nutrients from the Edamam Food Nutrition api using Node.JS. They provide this example using curl curl -d @food.json -H "Content-Type: application/json" "https://api.edamam.com/api/food-database/v2/nutrients?app_id=${YOUR_APP_ID}&app_key=${YOUR_APP_KEY}"

I've successively fetched data from their Food Database API where the only parameter is a URL. This one is requires a JSON with the URL. I've hard coded a JSON to correctly call the API. The response I get is

{ "error": "bad_request", "message": "Entity could not be parsed" }

What needs to be changed to get a good response?

const url = 'https://api.edamam.com/api/food-database/v2/nutrients?app_id=' + nutrition_app_id + '&app_key=' + nutrition_app_key;
var myFood = '{"ingredients": [ { "quantity": 2, "measureURI": "http://www.edamam.com/ontologies/edamam.owl#Measure_ounce", "foodId": "food_akjf74ibll2id8aqb8xbha4t4axl"} ]}';

    postData(url, myFood, res)
        .then((data) => {
            res.send(data);
        })
        .catch((error) => console.log(error));

Here is the postData() function

async function postData(url = '', data, res) {
    console.log(data);
    const response = await fetch(url, {
        method: 'POST',
        cache: 'no-cache',
        credentials: 'same-origin',

        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
    });
    return response.json();
}
1
  • Pass an object instead of a string into data. You're stringifying a JSON string. Commented Mar 16, 2021 at 0:49

2 Answers 2

2

Your data myFood already is a JSON string, then no need to cast it to string with JSON.stringify(data) in postData function.

A simple way to fix this issue - make sure the data object always be a JSON object.

var myFood = {
  "ingredients": [
    {
      "quantity": 2,
      "measureURI": "http://www.edamam.com/ontologies/edamam.owl#Measure_ounce",
      "foodId": "food_akjf74ibll2id8aqb8xbha4t4axl",
    },
  ]
}; // object instead of string
Sign up to request clarification or add additional context in comments.

Comments

1

Since you're using JSON.stringify to serialize your data remove the quotes when you define your myFood variable. The way you have it defined now it's a string while you actually want to define an object.

var myFood = { "ingredients": [ { "quantity": 2, "measureURI": "http://www.edamam.com/ontologies/edamam.owl#Measure_ounce", "foodId": "food_akjf74ibll2id8aqb8xbha4t4axl"} 
] }; 

Compare theses two:

JSON.stringify('{"ingredients":[]}');
// yields '"{\"ingredients\":[]}"'
JSON.stringify({"ingredients":[]});
// yields '{"ingredients":[]}'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.