-
Notifications
You must be signed in to change notification settings - Fork 0
/
nutritionix.py
155 lines (110 loc) · 4.36 KB
/
nutritionix.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
import logging
import json
import requests
import urlparse
API_VERSION = "v2"
BASE_URL = "https://apibeta.nutritionix.com/%s/" % (API_VERSION)
class NutritionixClient:
def __init__(self, application_id=None, api_key=None, debug=False, *arg, **kwarg):
self.APPLICATION_ID = application_id
self.API_KEY = api_key
self.DEBUG = False
if debug == True:
self.DEBUG = debug
logging.basicConfig(level=logging.DEBUG)
def get_api_version(self, *arg):
return API_VERSION
def get_application_id(self, *arg):
return self.APPLICATION_ID
def get_api_key(self, *arg):
return self.API_KEY
def execute(self, url=None, method='GET', params={}, data={}, headers={}):
""" Bootstrap, execute and return request object,
default method: GET
"""
# Verifies params
if params.get('limit') != None and params.get('offset') == None:
raise Exception('Missing offset',
'limit and offset are required for paginiation.')
elif params.get('offset') != None and params.get('limit') == None:
raise Exception('Missing limit',
'limit and offset are required for paginiation.')
# Bootstraps the request
method = method.lower()
headers['X-APP-ID'] = self.APPLICATION_ID
headers['X-APP-KEY'] = self.API_KEY
# Executes the request
if method == "get" or not 'method' in locals():
r = requests.get(url, params=params, headers=headers)
elif method == "post":
r = requests.post(url, params=params, data=data, headers=headers)
else:
return None
# Log response content
logging.debug("Response Content: %s" % (r.text))
return r.json()
#--------------
# API Methods #
#--------------
def autocomplete(self, **kwargs):
"""
Specifically designed to provide autocomplete functionality for search
boxes. The term selected by the user in autocomplete will pass to
the /search endpoint.
"""
# If first arg is String then use it as query
params = {}
if kwargs:
params = kwargs
endpoint = urlparse.urljoin(BASE_URL, 'autocomplete')
return self.execute(endpoint, params=params)
def natural(self, **kwargs):
"""
Supports natural language queries like "1 cup butter" or "100cal yogurt"
"""
# If first arg is String then use it as query
params = {}
if kwargs:
params = kwargs
# Converts 'q' argument as request data
data = ''
if params.get('q'):
data = params.get('q')
# Removes 'q' argument from params to avoid pass it as URL argument
del params['q']
endpoint = urlparse.urljoin(BASE_URL, 'natural')
return self.execute(endpoint, method="POST", params=params, data=data, headers={'Content-Type': 'text/plain'})
def search(self, **kwargs): # TODO: Add advance search filters
"""
Search for an entire food term like "mcdonalds big mac" or "celery."
"""
# Adds keyword args to the params dictionary
params = {}
if kwargs:
params = kwargs
endpoint = urlparse.urljoin(BASE_URL, 'search')
return self.execute(endpoint, params=params)
def item(self, **kwargs):
"""Look up a specific item by ID or UPC"""
# Adds keyword args to the params dictionary
params = {}
if kwargs:
params = kwargs
endpoint = urlparse.urljoin(BASE_URL, 'item/%s' % (params.get('id')))
return self.execute(endpoint)
def brand(self, **kwargs):
"""Look up a specific brand by ID. """
# Adds keyword args to the params dictionary
params = {}
if kwargs:
params = kwargs
endpoint = urlparse.urljoin(BASE_URL, 'brand/%s' % (params.get('id')))
return self.execute(endpoint)
def brand_search(self, **kwargs):
"""Look up a specific brand by ID. """
# Adds keyword args to the params dictionary
params = {}
if kwargs:
params = kwargs
endpoint = urlparse.urljoin(BASE_URL, 'search/brands/')
return self.execute(endpoint, params=params)