1
$\begingroup$

I'm working on a project to build a graph based on nutritional elements of common foods. A popular source of this information is Nutritionix, which provides data via a set of APIs. I'm using MMA (v12.1) to access the API, but without success. Here is my code so far:

applicationID = "91d3b93f"; 
applicationKEY = "df2551cd5bdb242279928ad14417db41";
userID = 0; (* required by API*)
urlRoot = "https://trackapi.nutritionix.com/v2/natural/nutrients";
headers = 
  "Headers" -> {"x-app-id" -> applicationID, 
    "x-app-key" -> applicationKEY, "x-remote-user-id" -> userID};
qry = "Query" -> {"1 cup of flour"};

I'm providing my applicationID and applicationKEY to assist anyone who wishes to answer this question (I will change them later)

Based on the API documentation, the POST call seems simple enough. But it results in the following error:

In[18]:= results = 
 URLExecute[HTTPRequest[urlRoot, <|Method -> "POST", headers, qry, "ContentType" -> "application/json"|>]]

Out[18]= {"message" -> "child \"query\" fails because [\"query\" is required]",  "id" -> "ddedaf39-0568-47e9-91ac-6f0764f38e58"}

I've tried a few different permutations of this, but without success.I'm hoping someone better versed in the nuances of API calls can assist me.

Thanks!

$\endgroup$

1 Answer 1

3
$\begingroup$

This request works:

qry = ExportString[{"query" -> "1 cup of flour"}, "JSON"];
results = URLExecute[
  HTTPRequest[
   urlRoot, <|
    Method -> "POST",
    headers,
    "Body" -> qry,
    "ContentType" -> "application/json"
    |>]
  ]

{"foods" -> {{"food_name" -> "flour", "brand_name" -> Null, "serving_qty" -> 1, "serving_unit" -> "cup", "serving_weight_grams" -> 125, "nf_calories" -> 455, "nf_total_fat" -> 1.23, "nf_saturated_fat" -> 0.19, "nf_cholesterol" -> 0, "nf_sodium" -> 2.5, "nf_total_carbohydrate" -> 95.39, "nf_dietary_fiber" -> 3.38, "nf_sugars" -> 0.34, "nf_protein" -> 12.91, "nf_potassium" -> 133.75, "nf_p" -> 135, ....

Note that I changed "Query" to "Body", and that the body should be a JSON string.

For more information about what you can put in the JSON string, have a look here. (Click on the endpoint /v2/natural/nutrients.)

$\endgroup$
1
  • $\begingroup$ Fantastic! Thanks very much for your response. $\endgroup$ Commented Jul 8, 2020 at 23:59

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.