Skip to content

Instantly share code, notes, and snippets.

@mattsilv
Last active November 10, 2023 06:59
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mattsilv/9dfb709e7609537ffd3b1b8c097e9bfb to your computer and use it in GitHub Desktop.
Save mattsilv/9dfb709e7609537ffd3b1b8c097e9bfb to your computer and use it in GitHub Desktop.
Natural Language Request for Food Logging

Natural Language Request for Food Logging

This endpoint requires an app ID and app key from https://developer.nutritionix.com/admin/access_details

POST https://trackapi.nutritionix.com/v2/natural/nutrients

HEADERS Content-Type:application/json, x-app-id:NutritionixAppID, x-app-key:NutritionixAppKey

BODY:

{
 "query":"for breakfast i ate 2 eggs, bacon, and french toast",
 "timezone": "US/Eastern"
}

Notes:

  • The end user's timezone parameter is optional, but it should be provided to ensure accuracy in time derivations. For example, if the user says "for breakfast" it will assume 8AM in that user's time zone.
  • All consumed_at timetamps are reported back from the API in UTC
@imanpakii
Copy link

Hello,
Can you please provide any example on this method for android app?
Thank you
iman

@nikhilmaurya10
Copy link

I am facing an error
{"message":"Something went wrong","id":"417986ea-d50a-461f-9f96-3f737000b9b1"}
Its an internal server error Status →500 Internal Server Error
Can you help.

@goranch
Copy link

goranch commented Jun 27, 2017

@mattsilv
Copy link
Author

@nikhilmaurya10 can you post your exact post body and request URL?
@goranch the x-remote-user-id is explained here. It's so we can track how many unique end-users each developer has using the API.

@shravanipl
Copy link

Hi, I am not getting images and individual details which is listed after Calculate Foods button.

Here are the request and response
Request
var settings = {
“async”: true,
“crossDomain”: true,
“url”: “https://trackapi.nutritionix.com/v2/natural/nutrients”,
“method”: “POST”,
“headers”: {
“content-type”: “application/json”,
“accept”: “application/json”,
“x-app-id”: “039db79f”,
“x-app-key”: “edffc89a0cc7397efe3a456d0349b798”,
“x-remote-user-id”: “0”,
“cache-control”: “no-cache”,
“postman-token”: “fa71a67a-c306-e015-1ccb-f9e7b4dd2424”
},
“processData”: false,
“data”: “{\n \”query\“: \”1 cup spinach\“,\n \”num_servings\“: 1,\n \”aggregate\“: \”string\“,\n \”line_delimited\“: false,\n \”use_raw_foods\“: false,\n \”include_subrecipe\“: false,\n \”timezone\“: \”US/Eastern\“,\n \”consumed_at\“: null,\n \”lat\“: null,\n \”lng\“: null,\n \”meal_type\“: 0,\n \”use_branded_foods\“: false,\n \”locale\“: \”en_US\“\n }”
}

$.ajax(settings).done(function (response) {
console.log(response);
});

Response
{
“foods”: [
{
“food_name”: “string”,
“brand_name”: null,
“serving_qty”: 1,
“serving_unit”: “serving”,
“serving_weight_grams”: 180,
“nf_calories”: 41.4,
“nf_total_fat”: 0.47,
“nf_saturated_fat”: 0.08,
“nf_cholesterol”: 0,
“nf_sodium”: 126,
“nf_total_carbohydrate”: 6.75,
“nf_dietary_fiber”: 4.32,
“nf_sugars”: 0.77,
“nf_protein”: 5.35,
“nf_potassium”: 838.8,
“nf_p”: 100.8,
“full_nutrients”: [
{
“attr_id”: 203,
“value”: 5.346
},
{
“attr_id”: 204,
“value”: 0.468
},
{
“attr_id”: 205,
“value”: 6.75
},
{
“attr_id”: 207,
“value”: 3.258
},
{
“attr_id”: 208,
“value”: 41.4
},
{
“attr_id”: 221,
“value”: 0
},
{
“attr_id”: 255,
“value”: 164.178
},
{
“attr_id”: 262,
“value”: 0
},
{
“attr_id”: 263,
“value”: 0
},
{
“attr_id”: 268,
“value”: 172.8
},
{
“attr_id”: 269,
“value”: 0.774
},
{
“attr_id”: 291,
“value”: 4.32
},
{
“attr_id”: 301,
“value”: 244.8
},
{
“attr_id”: 303,
“value”: 6.426
},
{
“attr_id”: 304,
“value”: 156.6
},
{
“attr_id”: 305,
“value”: 100.8
},
{
“attr_id”: 306,
“value”: 838.8
},
{
“attr_id”: 307,
“value”: 126
},
{
“attr_id”: 309,
“value”: 1.368
},
{
“attr_id”: 312,
“value”: 0.3132
},
{
“attr_id”: 313,
“value”: 68.04
},
{
“attr_id”: 315,
“value”: 1.683
},
{
“attr_id”: 317,
“value”: 2.7
},
{
“attr_id”: 318,
“value”: 18865.8
},
{
“attr_id”: 319,
“value”: 0
},
{
“attr_id”: 320,
“value”: 943.2
},
{
“attr_id”: 321,
“value”: 11318.4
},
{
“attr_id”: 322,
“value”: 0
},
{
“attr_id”: 323,
“value”: 3.744
},
{
“attr_id”: 324,
“value”: 0
},
{
“attr_id”: 328,
“value”: 0
},
{
“attr_id”: 334,
“value”: 0
},
{
“attr_id”: 337,
“value”: 0
},
{
“attr_id”: 338,
“value”: 20354.4
},
{
“attr_id”: 401,
“value”: 17.64
},
{
“attr_id”: 404,
“value”: 0.171
},
{
“attr_id”: 405,
“value”: 0.4248
},
{
“attr_id”: 406,
“value”: 0.882
},
{
“attr_id”: 410,
“value”: 0.261
},
{
“attr_id”: 415,
“value”: 0.4356
},
{
“attr_id”: 417,
“value”: 262.8
},
{
“attr_id”: 418,
“value”: 0
},
{
“attr_id”: 421,
“value”: 35.46
},
{
“attr_id”: 430,
“value”: 888.48
},
{
“attr_id”: 431,
“value”: 0
},
{
“attr_id”: 432,
“value”: 262.8
},
{
“attr_id”: 435,
“value”: 262.8
},
{
“attr_id”: 454,
“value”: 160.2
},
{
“attr_id”: 501,
“value”: 0.072
},
{
“attr_id”: 502,
“value”: 0.2286
},
{
“attr_id”: 503,
“value”: 0.2736
},
{
“attr_id”: 504,
“value”: 0.4158
},
{
“attr_id”: 505,
“value”: 0.3276
},
{
“attr_id”: 506,
“value”: 0.099
},
{
“attr_id”: 507,
“value”: 0.063
},
{
“attr_id”: 508,
“value”: 0.2412
},
{
“attr_id”: 509,
“value”: 0.2034
},
{
“attr_id”: 510,
“value”: 0.3024
},
{
“attr_id”: 511,
“value”: 0.3024
},
{
“attr_id”: 512,
“value”: 0.1188
},
{
“attr_id”: 513,
“value”: 0.2646
},
{
“attr_id”: 514,
“value”: 0.45
},
{
“attr_id”: 515,
“value”: 0.6426
},
{
“attr_id”: 516,
“value”: 0.252
},
{
“attr_id”: 517,
“value”: 0.2088
},
{
“attr_id”: 518,
“value”: 0.1926
},
{
“attr_id”: 601,
“value”: 0
},
{
“attr_id”: 605,
“value”: 0
},
{
“attr_id”: 606,
“value”: 0.0774
},
{
“attr_id”: 607,
“value”: 0
},
{
“attr_id”: 608,
“value”: 0
},
{
“attr_id”: 609,
“value”: 0
},
{
“attr_id”: 610,
“value”: 0
},
{
“attr_id”: 611,
“value”: 0
},
{
“attr_id”: 612,
“value”: 0.0108
},
{
“attr_id”: 613,
“value”: 0.0594
},
{
“attr_id”: 614,
“value”: 0.0054
},
{
“attr_id”: 617,
“value”: 0.0054
},
{
“attr_id”: 618,
“value”: 0.0306
},
{
“attr_id”: 619,
“value”: 0.1656
},
{
“attr_id”: 620,
“value”: 0
},
{
“attr_id”: 621,
“value”: 0
},
{
“attr_id”: 626,
“value”: 0.0054
},
{
“attr_id”: 627,
“value”: 0
},
{
“attr_id”: 628,
“value”: 0
},
{
“attr_id”: 629,
“value”: 0
},
{
“attr_id”: 630,
“value”: 0
},
{
“attr_id”: 631,
“value”: 0
},
{
“attr_id”: 645,
“value”: 0.0108
},
{
“attr_id”: 646,
“value”: 0.1962
}
],
“nix_brand_name”: null,
“nix_brand_id”: null,
“nix_item_name”: null,
“nix_item_id”: null,
“upc”: null,
“consumed_at”: “2018-08-06T03:59:36+00:00”,
“metadata”: {},
“source”: null,
“ndb_no”: null,
“tags”: null,
“alt_measures”: null,
“lat”: null,
“lng”: null,
“meal_type”: 0,
“photo”: {
“thumb”: “https://d2eawub7utcl6.cloudfront.net/images/nix-apple-grey.png”,
“highres”: null,
“is_user_uploaded”: false
},
“sub_recipe”: null
}
]
}

@Andras1000
Copy link

Andras1000 commented Jan 5, 2019

I am trying to look up the calorie count of some basic foods.

curl -H "Content-Type:application/json" -H "x-app-id: xxxxxxxx" -H "x-app-key: xxxxxxxxxxxxxxxxxxxxxxx" -X POST -d {"query":"butter"} https://trackapi.nutritionix.com/v2/natural/nutrients

returns

{"message":"Unexpected token q in JSON at position 1"}

Not sure what's wrong. Would be the nice to have some simple examples with curl.

SOLVED:

Problem: missing quotation marks after -d. This works:

curl -H "Content-Type:application/json" -H "x-app-id: xxxxxxxx" -H "x-app-key: xxxxxxxxxxxxxxxxxxxxxxx" -X POST -d '{"query":"butter"}' https://trackapi.nutritionix.com/v2/natural/nutrients

@HewieTran
Copy link

HewieTran commented Jan 31, 2019

Hi,

I'm using Postman. I entered all required data (headers and body) but I can't get a correct response from my POST request. Here's the message that returns to me:

"message": "child "query" fails because ["query" is required]",

See image for more info:
https://content.screencast.com/users/tranhieu/folders/Jing/media/ca06abd4-0bad-4f75-af14-c7923d8936f4/2019-01-30_2149.png

Appreciate any help!

SOLVED:

I used x-www-urlencoded instead of form-data for body.

@mf24
Copy link

mf24 commented Feb 1, 2019

Hi,

I'm developing an app on Android Studio. I've got the same problem as @HevieTran -
ResponseCode 400 - ERROR: {"message":"child "query" fails because ["query" is required]","id":"78324641-c1bf-4904-ac06-41d1ac51be59"}.

My body:

final String jsonBody = "{"query":"bacon"}";
@OverRide
public byte[] getBody() {
Log.i("getBODY", "inside getBody");

            byte[] body = new byte[0];
            try {
                body = jsonBody.getBytes("UTF-8");
                Log.i("getBODY", jsonBody.toString());

            } catch (UnsupportedEncodingException e) {
            }
            return body;
        }

My headers:
@OverRide
public Map<String, String> getHeaders() {
Log.i("LOG: ", "HEADERS");
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
headers.put("x-app-id", "3b6a9637");
headers.put("x-app-key", "db6065a4684b490a368fdfbe72c9063c");
return headers;
}

What can be wrong? I've tested every possible thing...
Thanks in advance

@shreyag12
Copy link

Hi, How can I fetch the total nutrition of a recipe like we get on the picture Nutrition Facts when we click on "Calculate Foods" button here https://www.nutritionix.com/natural-demo? I am getting nutrition of individual food items in response but not the total nutrition.

@codingmeow
Copy link

Hi, How can I fetch the total nutrition of a recipe like we get on the picture Nutrition Facts when we click on "Calculate Foods" button here https://www.nutritionix.com/natural-demo? I am getting nutrition of individual food items in response but not the total nutrition.

I'm looking for the same thing as mentioned above. Can someone direct us the right direction?

@AmalKhatib
Copy link

I get
{
"message": "Unexpected token - in JSON at position 0"
}
can anybody explain?

@seanren96
Copy link

Can you give me an exact example? Like I am using ajax.
Here is my code:
var settings = {
async: true,
url: "https://trackapi.nutritionix.com/v2/natural/nutrients",
method: "POST",
header: {
"content-type": "application/json",
accept: "application/json",
"x-app-id": "84de5f10",

  "x-app-key": "57360fb5c60c020f0244f5d2008995fe",
  "x-remote-user-id": "0",
  "cache-control": "no-cache",
  "postman-token": "fa71a67a-c306-e015-1ccb-f9e7b4dd2424"
},
processData: false,
data:
  "{\n ”query“: ”1 cup spinach“,\n ”num_servings“: 1,\n ”aggregate“: ”string“,\n ”line_delimited“: false,\n ”use_raw_foods“: false,\n ”include_subrecipe“: false,\n ”timezone“: ”US/Eastern“,\n ”consumed_at“: null,\n ”lat“: null,\n ”lng“: null,\n ”meal_type“: 0,\n ”use_branded_foods“: false,\n ”locale“: ”en_US“\n }"

};
$.ajax(settings).done(function(response) {
console.log(response);
});

}
This is what i GET.
{"message":"request requires x-app-id and x-app-key headers","id":"f859f421-7996-4ba9-b8eb-4d1fef66e20e"}

@allenind
Copy link

allenind commented Nov 1, 2019

I get
{
"message": "Unexpected token - in JSON at position 0"
}
can anybody explain?

I am also getting this error. I tried doing it in curl, here is my curl:

curl -H "Content-Type:application/json" -H "x-app-id: XXXXXX" -H "x-app-key: XXXXXXXXXXXXXXXXX" -H "x-remote-user-id: 0" -X POST -d '{"query":"butter"}' https://trackapi.nutritionix.com/v2/natural/nutrients

This is my error: {message: Unexpected token ' in JSON at position 0} any help? @mattsilv

@malloha
Copy link

malloha commented Dec 16, 2019

Can you give me an exact example? Like I am using ajax.
Here is my code:
var settings = {
async: true,
url: "https://trackapi.nutritionix.com/v2/natural/nutrients",
method: "POST",
header: {
"content-type": "application/json",
accept: "application/json",
"x-app-id": "84de5f10",

  "x-app-key": "57360fb5c60c020f0244f5d2008995fe",
  "x-remote-user-id": "0",
  "cache-control": "no-cache",
  "postman-token": "fa71a67a-c306-e015-1ccb-f9e7b4dd2424"
},
processData: false,
data:
  "{\n ”query“: ”1 cup spinach“,\n ”num_servings“: 1,\n ”aggregate“: ”string“,\n ”line_delimited“: false,\n ”use_raw_foods“: false,\n ”include_subrecipe“: false,\n ”timezone“: ”US/Eastern“,\n ”consumed_at“: null,\n ”lat“: null,\n ”lng“: null,\n ”meal_type“: 0,\n ”use_branded_foods“: false,\n ”locale“: ”en_US“\n }"

};
$.ajax(settings).done(function(response) {
console.log(response);
});

}
This is what i GET.
{"message":"request requires x-app-id and x-app-key headers","id":"f859f421-7996-4ba9-b8eb-4d1fef66e20e"}

Were you able to fix it?

@ultraYumm
Copy link

Hello, what does "meal_type" refer to and what do the different values correspond to?
{
"query": "string",
"num_servings": 0,
"aggregate": "string",
"line_delimited": false,
"use_raw_foods": false,
"include_subrecipe": false,
"timezone": "string",
"consumed_at": "string",
"lat": 0,
"lng": 0,
"meal_type": 0,
"use_branded_foods": false,
"locale": "string"
}

@gnikoloudis
Copy link

Simple code:

import http.client

conn = http.client.HTTPSConnection("trackapi.nutritionix.com")

headers = {
'x-app-id': "",
'x-app-key': "",
'x-remote-user-id': "0"
}
#the app-id and app-key are hidden

conn.request(
"POST", "/v2/natural/nutrients?query=lamb++kebabs", headers=headers)

res = conn.getresponse()
data = res.read()

print(data.decode("utf-8"))

Why am I getting this error?
{"message":"child "query" fails because ["query" is required]","id":"858dd283-6025-4e8d-a2c5-312057bb4f6e"}

@SorinTautu1991
Copy link

Has anyone manage to make a POST request in Java and get the desired results to this url: https://trackapi.nutritionix.com/v2/natural/nutrients? The documentation is very thick. If you did, please let me know how you did it. Thank you!

@dcazrael
Copy link

dcazrael commented Jan 20, 2021

Hey @SorinTautu1991,

I used postman to do the request, but this should help you out.

import java.io.*;
import okhttp3.*;
public class main {
    public static void main(String []args) throws IOException{
        OkHttpClient client = new OkHttpClient().newBuilder()
            .build();
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "query=for breakfast I ate 2 eggs, bacon, and french toast&timezone=US/Eastern");
        Request request = new Request.Builder()
            .url("https://trackapi.nutritionix.com/v2/natural/nutrients")
            .method("POST", body)
            .addHeader("x-app-id", "fb282fff")
            .addHeader("x-app-key", "cdc5f249f7666091473ffc65b3f47d9a")
            .addHeader("content", "application/json")
            .addHeader("Content-Type", "application/x-www-form-urlencoded")
            .build();
        Response response = client.newCall(request).execute();
        System.out.println(response.body().string());
    }
}

or in curl

curl --location --request POST 'https://trackapi.nutritionix.com/v2/natural/nutrients' \
--header 'x-app-id: fb282fff' \
--header 'x-app-key: cdc5f249f7666091473ffc65b3f47d9a' \
--header 'content: application/json' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'query=for breakfast I ate 2 eggs, bacon, and french toast' \
--data-urlencode 'timezone=US/Eastern'

@gnikoloudis
You are using the query in the request instead of a payload

import http.client

conn = http.client.HTTPSConnection("trackapi.nutritionix.com")
payload = 'query=for%20breakfast%20I%20ate%202%20eggs%2C%20bacon%2C%20and%20french%20toast&timezone=US%2FEastern'
headers = {
  'x-app-id': 'fb282fff',
  'x-app-key': 'cdc5f249f7666091473ffc65b3f47d9a',
  'content': 'application/json',
  'Content-Type': 'application/x-www-form-urlencoded'
}
conn.request("POST", "/v2/natural/nutrients", payload, headers)
res = conn.getresponse()
data = res.read()
print(data.decode("utf-8"))

@SneakingSlayer
Copy link

SneakingSlayer commented Apr 6, 2021

How do you multifield search here? in v1_1 all you need to do is queries: {"item_name":"burger"}. How do I do this in V2?

@inspiraller
Copy link

From this REST api page:
https://trackapi.nutritionix.com/docs/#/default/post_v2_natural_nutrients

When testing this api get request:
/v2/natural/nutrients

I have entered my id, key and 0 as the remote id.

I still get Error:

Undocumented | Error: UnauthorizedResponse body{ "message": "unauthorized", "id": "847c88c5-81fe-4e10-9083-540ad8d0a68c" }

@rdhungerf0rd
Copy link

I get status 400 back when I run the following Swift code to do a query of an apple. I'd appreciate any help in debugging. I've put dummy characters in the app-id and app-key fields. I'm sure those fields aren't causing the problem because I can do a upc search just fine. Thanks.

    let headers: [String: String] = ["Content-Type": "application/json", "accept": "application/json", "x-app-id": "xxxxxxxxxx", "x-app-key": "xxxxxxxxxxxxxxxxxxxxxxxxxxxx", "x-remote-user-id": "0"]
    
    let request = NSMutableURLRequest(url: NSURL(string: "https://trackapi.nutritionix.com/v2/natural/nutrients?query=apple")! as URL, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10.0)
    
    request.httpMethod = "POST"
    request.allHTTPHeaderFields = headers
    
    let task = URLSession.shared.dataTask(with: request as URLRequest, completionHandler: { [self] data, response, error in
        guard let data = data, error == nil else {
        }

@xjohnfit
Copy link

xjohnfit commented Jun 5, 2023

const options = {
            method: 'POST',
            url: 'https://trackapi.nutritionix.com/v2/natural/nutrients',
            headers: {
                'content-type': 'application/json',
                'accept': 'application/json',
                'x-app-id': 'MYID',
                'x-app-key': 'MYKEY'
            },
            body: {
                "query": "banana",
                "timezone": "US/Eastern"
            }
        };

Im trying this code above in react, but i get a 400 Bad Request Error down below

{message: "child "query" fails because ["query" is required]",…}
id
: 
"9e69e3bb-a6c0-4b3c-964f-faeff72929e8"
message
: 
"child \"query\" fails because [\"query\" is required]"

@siddharth201983
Copy link

const options = {
            method: 'POST',
            url: 'https://trackapi.nutritionix.com/v2/natural/nutrients',
            headers: {
                'content-type': 'application/json',
                'accept': 'application/json',
                'x-app-id': 'MYID',
                'x-app-key': 'MYKEY'
            },
            body: {
                "query": "banana",
                "timezone": "US/Eastern"
            }
        };

Im trying this code above in react, but i get a 400 Bad Request Error down below

{message: "child "query" fails because ["query" is required]",…}
id
: 
"9e69e3bb-a6c0-4b3c-964f-faeff72929e8"
message
: 
"child \"query\" fails because [\"query\" is required]"

Use data instead of body

@MakersMarked
Copy link

MakersMarked commented Nov 10, 2023

I'm convinced Nutrients API is broken. all other endpoints work for me but this one just keeps giving err after err.

async function food () {
 const res =  fetch('https://trackapi.nutritionix.com/v2/natural/nutrients',{
  method: 'post',
  headers:{
    'x-app-id': process.env.NUTRITIONIX_ID,
    'x-app-key': process.env.NUTRITIONIX_KEY,
    'Content-Type':'application/json',
    'accept': 'application/json',
    'x-remote-user-id': '0'
  },
  body:  {
    "query": "turkey and mashed potatoes this morning"
  }
});
try {
const data = await res
 console.log(data)  
}
 catch(error){
  console.log(error)
 }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment