Sign in | Sign up

Python // Basic Example Code

Tagged:

Currently contains 2 posts

Avatar

June 15, 2019 06:59

MDC

To save some CS students the trouble, I’ve included a couple helpful code examples and explanations to save you the headache.

Warning: This is simply information that I have deduced from using the API and MAY NOT BE CORRECT or efficient. I will NOT be editing this post from here on so take that as you will.

>>> General
For my project, I was required to take in data and store it into JSON files, so you will need the following imports:
import requests
import json

>>> Headers
Create a dictionary with your API id key and API application key. You will need to pass this header with every API call/request. If you are planning to parse the data as a json, you may wish to include ‘Content-Type’ in your header.

Example:
HEADERS = {’x-app-id’: <INSERT APP ID HERE>,
‘x-app-key’: <INSERT APP KEY HERE>,
“Content-Type”: “application/json”}

>>> General Item Search
Using the code below, you will see that ‘data’ contains two dictionaries, ‘common’ and ‘branded’ with each associated with common foods and branded foods based on your query. You use whatever method you want to parse that data.

Example:
url: “https://trackapi.nutritionix.com/v2/search/instant?query=<INSERT QUERY HERE>”
response = requests.get(url, headers=HEADERS)
data = json.loads(response.content.decode(‘utf-8’))

>>> ID Search
Grab ‘nix_item_id’ from any item that you’ve searched up (see above) and use it as a query here to pull specific nutritional information. Make sure this is NOT ‘nix_brand_id’. NOTE: This only works for branded items.

Example:
url = “https://trackapi.nutritionix.com/v2/search/item?nix_item_id=<INSERT ID HERE>”
response = requests.get(url, headers=HEADERS)
data = json.loads(response.content.decode(‘utf-8’))

>>> Brand Search
Similarly to the two searches above, you can pull ‘brand’ from an item and use it as a query here.

Example:
url = “https://trackapi.nutritionix.com/v2/search/instant?query=\”\“?brand_ids=<INSERT BRAND HERE>”
response = requests.get(url, headers=HEADERS)
data = json.loads(response.content.decode(‘utf-8’))

Avatar

June 17, 2019 19:14

MDC

>>> Nutrient Search
Unlike the searches above, you will need to use POST instead of GET here in order to get back nutrient data (useful for common foods as specified in the documentation). If using the keyword argument “json” doesn’t work, try using “body” or “data” to see if you get a response.

Example:
url = “https://trackapi.nutritionix.com/v2/natural/nutrients”
query = {"query": <INSERT QUERY HERE>}
response = requests.post(url, headers=HEADERS, json=query)
data = json.loads(response.content.decode(‘utf-8’))

Reply to thread