Skip to content

Instantly share code, notes, and snippets.

@mattsilv
Last active November 10, 2023 06:59
Show Gist options
  • 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
@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