ATTACH INGREDIENT:
XID
NAME
QUANTITY
COOKING METHOD
//NOTE: The Javascript example is not secure and is shown only for informational purposes. Nutritics doesn't recommend its usage. // Get results using JSONP: function myCallback(result) { //Define a function to be called after we receive the data if( result.status == 200 ){ //ON SUCCESS: console.log(result) //output the result to the console }else{ // ON ERROR: console.log('ERROR '+result.status+': '+result.msg) } } //Run the request: var script = document.createElement('script') script.src = 'https://[USERNAME]:[PASSWORD]@[URL]&callback=myCallback' document.getElementsByTagName('head')[0].appendChild(script)
require 'rubygems' require 'json' require 'rest-client' # Get json results using RestClient. response = RestClient.get 'https://[USERNAME]:[PASSWORD]@[URL]', {:accept => :json} if response.code == 200 # Convert the string to a JSON Object data = JSON.parse(response) # Print the returned json data out puts JSON.pretty_generate(data) #Loop through each object and print out their id for item in data; puts item["id"] end else #We have an error end
//NOTE: The JQuery example is not secure and is shown only for informational purposes. Nutritics doesn't recommend its usage. // Get results using JSONP: var requsetURL = 'https://[USERNAME]:[PASSWORD]@[URL]&callback=?' $.getJSON( requestURL, function( result ){ //Define a function to be called after we receive the data if( result.status == 200 ){ //ON SUCCESS: console.log(result) //output the result to the console }else{ // ON ERROR: console.log('ERROR '+result.status+': '+result.msg) } } )
/*Note: Json library needs to be import for the results.*/ /*imports*/ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.Authenticator; import java.net.PasswordAuthentication; import java.net.URL; import java.net.URLConnection; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; public class NutriticsApi { public static void main(String [] arg) throws IOException, JSONException { //CREATE AN AUTHENTICATOR: Authenticator.setDefault(new Authenticator() { String username="[USERNAME]"; String password="[PASSWORD]"; @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password.toCharArray()); } }); URL url = new URL("[URL]"); URLConnection conn = url.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String inputLine, output = ""; while ((inputLine = in.readLine()) != null) { output += inputLine; } // HOW TO GET THE FIRST RESULT: JSONArray newArr= new JSONArray(output); System.out.println(newArr.getJSONObject(0)); // HOW TO LOOP THROUGH RESULTS TO GET INDIVIDUAL FIELDS: for(int i=0; i<newArr.length(); i++) { JSONObject dataObj= newArr.getJSONObject(i); System.out.println(dataObj.getString("id")); //output the id number for each result } } }
#Example to use an API call with Python v2 and authentication #You have to use these basic libraries import urllib2 import sys import re import base64 import json from urlparse import urlparse theurl = 'https://[URL]' username = '[USERNAME]' password = '[PASSWORD]' req = urllib2.Request(theurl) try: handle = urllib2.urlopen(req) except IOError, e: # Here we want to fail pass else: sys.exit(1) if not hasattr(e, 'code') or e.code != 401: # Uknown error (no response code) sys.exit(1) #We extract scheme and realm authline = e.headers['www-authenticate'] authobj = re.compile(r'''(?:\s*www-authenticate\s*:)?\s*(\w*)\s+realm=['"]([^'"]+)['"]''',re.IGNORECASE) matchobj = authobj.match(authline) if not matchobj: # here something is wrong (you have to catch an error) print authline sys.exit(1) scheme = matchobj.group(1) realm = matchobj.group(2) # here we've extracted the scheme and the realm from the header if scheme.lower() != 'basic': # here something is wrong (you have to catch an error) sys.exit(1) base64string = base64.encodestring('%s:%s' % (username, password))[:-1] authheader = "Basic %s" % base64string req.add_header("Authorization", authheader) try: handle = urllib2.urlopen(req) except IOError, e: # authentication failed print "The username or password is wrong." sys.exit(1) #We read the result thepage = handle.read() #Print the returned json data out print thepage; jsondata = json.loads(thepage) #Loop through each object and print out their id for item in jsondata: print item["id"]
//BASIC EXAMPLE: $requestURL = "https://[USERNAME]:[PASSWORD]@[URL]"; if($result = file_get_contents( $requestURL ) ) { $result = json_decode( $result, true ); //unpack the response into an array if( $result['status'] == 200 ){ //ON SUCCESS: print_r($result); // print the full object }else{ //ON ERROR: die('ERROR '.$result['status'].': '.$result['msg']); } }else die("There was an error sending the request");
'How to import REST API data into a Microsoft Excel Workbook: 'Open the excel VBA editor and paste the code below into a new module. 'Next, create a button on sheet1 and choose getNutritics as the onclick function. Sub getNutritics() URL = "https://[URL]" user = "[USERNAME]" pass = "[PASSWORD]" Set httpReq = CreateObject("MSXML2.ServerXMLHTTP.6.0") httpReq.Open "GET", URL, False httpReq.setRequestHeader "Content-Type", "application/xml" httpReq.setRequestHeader "Accept", "application/xml" httpReq.setRequestHeader "Authorization", "Basic " + Base64Encode(user + ":" + pass) httpReq.send 'MsgBox httpReq.responseText n2XlJSONParser (httpReq.responseText) 'displays the result in sheet 1 End Sub 'JSON parsing function 'http://www.mrexcel.com/forum/excel-questions/640780-parse-json-excel-visual-basic-applications-3.html 'parses a JSON string into a range of cells Sub n2XlJSONParser(Src) Dim ws As Worksheet ' Target worksheet for extracted data Dim TLen As Integer ' Total length of of input cell data Dim columnsCR As Integer ' limit number of data pairs before forced Carriage Return Dim cCR As Integer ' Runtime modified carriage return value for relative reference from start. Dim lenLim As Integer ' Data lenth limit to cause a new row. 0 = none Dim rStart As Integer ' Starting output row Dim cStart As Integer ' Starting output column Dim rOut As Integer ' Dest Row for output Dim cOut As Integer ' Dest Col for output Dim nDex As Integer ' Current position in Source string Dim nDex2 As Integer ' further index to find end quote Dim nDexChr As String ' The character at nDex Dim n2This As String ' value within from nDex -> nDex2 range Dim records As Integer ' Total number of records to report parsed. ' Propagation rules: ' A brace "{" indents the table 1 column. ' An end brace "}" un-indents the table (is that a word?). ' Quotes are partial delimiters to find a string value to extract by looking ahead to the next quote. ' colons and commas are minor delimiters; a comma looks back to the previous colon. ' "}," is a major delimiter, and causes the extraction to start a new row. ' First assign the source Set ws = ActiveWorkbook.Worksheets(1) 'Src = ws.Range("A4").Value ' Cell that contains JSON data to parse. TLen = Len(Src) records = 0 ' Initialize cell output behavior. Adjust these to suit. rStart = 1 ' Start output in row 1 cStart = 1 ' Start output in "A" column columnsCR = 0 ' Number of columns, after which, force the start of a new row. _ ' _ A ZERO value turns this off. (even numbers work best) lenLim = 0 ' If string longer than this, start new row. A ZERO value turns this off. '...if you use lenLim, variable record lengths can break table structure. ' Set up assorted variables rOut = rStart cOut = cStart Sheet1.Cells(rStart, cStart).Activate ' This is the starting output cell. cStart = cStart - 1 ' Pay no attention to the man behind the curtain! ' Initialize nDex ' The nDex crawls through the Source, leaving nDex2 behind. When it finds a delimiter, it grabs _ ' what is in between the two NDex counters. Then it brings up nDex2 and continues. This is like _ ' an inch-worm process through the source data. It's smart enough to know to look for the next _ ' quote after finding a quote. This way it won't have to check EVERY character of data. ' A future version will increase speed dramatically by looking ahead for next delimiter. nDex = 1 nDex2 = nDex ' MAIN LOOP Do While nDex <= TLen nDexChr = Mid(Src, nDex, 1) ' Get the character sitting at the nDex location ' Find what's at the nDex location If nDexChr = """" Then ' Is it a quote? nDex2 = nDex ' Bring up the tail nDex = InStr(nDex2 + 1, Src, """") ' Find the next quote n2This = Mid(Src, nDex2 + 1, (nDex - nDex2) - 1) 'Get what is in the quotes ws.Cells(rOut, cOut) = n2This ' Dump the first found data here and now. records = records + 1 nDex = nDex + 1 ' increment the inchworm nDex2 = nDex ' ...and bring up the tail cOut = cOut + 1 ElseIf nDexChr = "," Then ' Is it a comma? If nDex2 <> nDex Then ' Should we look back? n2This = Mid(Src, nDex2 + 1, (nDex - nDex2) - 1) ' Get what's between the head and tail. ws.Cells(rOut, cOut) = n2This ' Dump data into cell records = records + 1 cOut = cOut + 1 ' next output cell in a new column End If nDex = nDex + 1 nDex2 = nDex ' encountered comma now see if we should start new line. If (cOut >= cCR And columnsCR > 0) Or (Len(n2This) > lenLim And lenLim <> 0) Then rOut = rOut + 1 cOut = cStart cCR = cStart + columnsCR End If ElseIf nDexChr = "}" Then cStart = cStart - 1 cCR = cStart + columnsCR If nDex <> nDex2 Then ' didn't start here so look back. n2This = Mid(Src, nDex2 + 1, (nDex - nDex2) - 1) ws.Cells(rOut, cOut) = n2This records = records + 1 End If nDex = nDex + 1 nDex2 = nDex If InStr(nDex, Src, ",") = nDex Then ' is this character a comma? rOut = rOut + 1 cOut = cStart Else: cOut = cOut + 1 End If nDex = nDex + 1 ElseIf nDexChr = "{" Then cStart = cStart + 1 If cOut < cStart Then cOut = cStart End If cCR = cStart + columnsCR nDex = nDex + 1 Else: nDex = nDex + 1 End If Loop MsgBox records & " total records were parsed." End Sub Function Base64Encode(sText) Dim oXML, oNode Set oXML = CreateObject("Msxml2.DOMDocument.3.0") Set oNode = oXML.createElement("base64") oNode.DataType = "bin.base64" oNode.nodeTypedValue = Stream_StringToBinary(sText) Base64Encode = oNode.Text Set oNode = Nothing Set oXML = Nothing End Function 'Stream_StringToBinary Function 2003 Antonin Foller, http://www.motobit.com 'Text - string parameter To convert To binary data Function Stream_StringToBinary(Text) Const adTypeText = 2 Const adTypeBinary = 1 'Create Stream object Dim BinaryStream 'As New Stream Set BinaryStream = CreateObject("ADODB.Stream") 'Specify stream type - we want To save text/string data. BinaryStream.Type = adTypeText 'Specify charset For the source text (unicode) data. BinaryStream.Charset = "us-ascii" 'Open the stream And write text/string data To the object BinaryStream.Open BinaryStream.WriteText Text 'Change stream type To binary BinaryStream.Position = 0 BinaryStream.Type = adTypeBinary 'Ignore first two bytes - sign of BinaryStream.Position = 0 'Open the stream And get binary data from the object Stream_StringToBinary = BinaryStream.Read Set BinaryStream = Nothing End Function 'Stream_BinaryToString Function '2003 Antonin Foller, http://www.motobit.com 'Binary - VT_UI1 | VT_ARRAY data To convert To a string Function Stream_BinaryToString(Binary) Const adTypeText = 2 Const adTypeBinary = 1 'Create Stream object Dim BinaryStream 'As New Stream Set BinaryStream = CreateObject("ADODB.Stream") 'Specify stream type - we want To save text/string data. BinaryStream.Type = adTypeBinary 'Open the stream And write text/string data To the object BinaryStream.Open BinaryStream.Write Binary 'Change stream type To binary BinaryStream.Position = 0 BinaryStream.Type = adTypeText 'Specify charset For the source text (unicode) data. BinaryStream.Charset = "us-ascii" 'Open the stream And get binary data from the object Stream_BinaryToString = BinaryStream.ReadText Set BinaryStream = Nothing End Function
v1.2Welcome
Nutritics API allows you to leverage the power of the world's favourite nutrition engine in your own app, program or website. Integration requires you to either be or to hire a developer. The API can be accessed from any programming language which can connect to the internet.
Most common uses for our API
- Search our vast international databases
- Analyse recipes from your own app or platform
- Analyse a diet from your own app or platform
- Generate a meal plan from your own app or platform
- Control Nutritics user data
Introduction
Working with the API is very straight forward. All requests are made via HTTPS URLs. Each URL contains a set of parameters which specify the data you wish to retrieve. The data is always returned in JSON format.
For example, here's a simple request which searches our database for the keyword "banana"
https://[USERNAME]:[PASSWORD]@www.nutritics.com/api/v1.2/LIST/food=banana
API explorer
You can use our powerful API explorer to build and test your requests before deploying them. The explorer will automatically generate a basic connection script in the most common coding languages to get you up and running quickly.
Syntax for requests
https://{USERNAME}:{PASSWORD}@www.nutritics.com/api/{API_VERSION}/{FUNCTION}/user={USER_ID}&{OBJECT}={ID OR GROUP}&[other parameters...]
Parameters after the last forward slash can be listed in any order.
Please note, the following characters are in use by the API engine and may break certain requests unless URL encoded:
{ ' } / \ | ¦ ~ > < + - , : " [ ]Request Methods
Nutritics API supports both HTTP GET and HTTP POST methods. For simplicity, the GET method is used throughout our documentation. Please note however that HTML GET maximum URL length is 2048 characters so you will need to use the POST method if you need to make very long requests.
Required Parameters
The following parameters are required on all requests.
{USERNAME}:{PASSWORD}
Your developer username & Password{API_VERSION}
Currently v1.2{FUNCTION}
The action you wish to perform. Read more about functions.
function description LIST Search and retrieve a list of Nutritics Objects or any set of data within them CREATE Create a new Nutritics Object and return it's calculated values MODIFY Edit a Nutritics Object DELETE Remove a Nutritics Object {OBJECT}
The type of data you wish to work with. A description of each of our core objects is listed below. Read more about objects.
object parent description user dev A Nutritics account client user A customer of a Nutritics user food user A base food or ingredient recipe user Multiple foods are combined to form a recipe activity system An exercise or physical action dietlog client A list of foods a client has eaten over a given period mealplan client A special diet prescribed by a user for their client Return Data
All requests return a stripped Nutritics object in JSON format. The following attributes are appended to all returned objects
Attribute Type description status int(3)int: A numeric value without a decimal Response code of your request msg stringstring: Letters, numbers, or other types of characters A message containing errors or warnings regarding your request. queryTime intint: A numeric value without a decimal Number of miliseconds the server took to process your request id intint: A numeric value without a decimal Returned only with 404 errors to specify the nutritics ID of the missing component. warning stringstring: Letters, numbers, or other types of characters Returned only when something has gone wrong but your request was still processed successfully. Debugging
You may append &debug=1 to any request to see a breakdown of all the data the API is using to calculate its response to your request. This can give useful insight when debugging your application.
Nutritics Objects
Data is sent and received from the API in Nutritics objects. The tables below detail all available parameters for objects. Note that all functions return a stripped object, which will not contain all available fields. If you need fields which are not returned by default, you may use the DETAIL function to specify these.
- Foods
- Recipes
- Clients
- Diet Logs
- Meal Plans
- Outlet
- Orders
- Nutrients
- Portions
- Menus
- Components
- Special
Data Types
Data Type List
Special Fields Definition (to be moved to Nutritics Objects Tables dropdowns)
cat: category definition.cat1,cat2,cat3
allergens: allergens definition.freefrom,maycontain,contains,suitablefor.{allergenlist}
Traffic LightsFunctions
- LIST
DETAIL- CREATE
- MODIFY
- DELETE
- ADMIN
- HELP
Response Codes
Code Name Description 200 Success Everything worked as expected. 400 Bad Request The request was unacceptable, often due to missing a required parameter. 401 Unauthorized Your username or password are incorrect 402 Limit Reached (check your account status) 404 Not Found No object found under the specified filters. 429 Too Many Requests Too many requests hit the API too quickly. We recommend an exponential backoff of your requests. 500, 502,
503, 504Server Errors Something went wrong on our end (check the API status)
Allergen mapping recommendations
To minimise risk of allergen misinterpretation, Nutritics recommend mapping allergens from the allergens attribute (e.g &attr=allergens). To parse and map the results, use a LIKE search for the cereal species (wheat, oats, barley, rye) and an exact match for 'Gluten'. In no scenario should the presence of a cereal species invoke a gluten tag automatically in the destination system. Mappings should be 1:1.
Nutritics sends…
Activates
Trigger word:
Oats, gluten-oats
Oats
%LIKE match for ‘Oats’ '%Oats%'
Wheat, gluten-wheat
Wheat
%LIKE match ‘%Wheat%’
Barley, gluten-barely
Barely
%LIKE match ‘%Barley%’
Rye, gluten-rye
Rye
%LIKE match ‘%Rye%’
Gluten
Cereals Containing Gluten
Exact match for ‘Gluten’
Notes:
- We have used the term %LIKE match which is a SQL term and should be understood as such. The matching logic and the underlying technology can be different but the principle demonstrated above should be considered to avoid misinterpretation of our allergen data.
Changelog v1.2
Features:
- New columns available in every object. Read the documentation for more information
- Search can now be made by IFC (removed src & code option)
- Portion cost field added to the portion object
- Cooking methods added to recipes
- Response codes were updated to web standards
- CREATE function now accepts the ID of an object to replace
- MODIFY, ADMIN and HELP functions added
- Added photos to LIST results
- queryTime parameter added to all requests
- Additional units accepted on component quantity (lb, kg, oz, ml, etc)
- Additional options added to component quantity ("one serving" & "recipe total")
- Dedicated barcodes added to portions
- New API Documentation
- New colour coding on explorer sample code & JSON response
- Activity object is now supported
Fixes:
- Removed id2 we recommend to use IFC instead
- "ingredients" field renamed to "components"
- "attr" field added to to LIST
- "filter" field in DETAIL renamed to "attr"
- "source" field renamed to "src"
- "txt" field renamed to to "msg"
- "measure" field removed. Use "quantity" instead.
- Empty values will be shown as "" instead of "null"
- Boolean values will be shown as true or false instead of "0","1"
- Integer and float values will be shown without quotes
- Fixed source field default value on recipe creation
- Fixed output encoding problems
- Fixed bug when deleting client
- Fixed problem when filtering fields on foods and recipes
- Fixed problem when showing allergens on foods and recipes
- Fixed problems with traffic lights and labeling
- Fixed bug when using pagination on foods and recipes
- Fixed bug related when detail a food or recipe and adding specific nutrients in the filter
- Javascript Callback for JSONP repaired