Class: Nutritionix::Api_1_1

Inherits:
Object
  • Object
show all
Defined in:
lib/nutritionix/api_1_1.rb

Overview

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(id, key, url = "https://api.nutritionix.com/v1_1", logger = APILogger.default_logger) ⇒ Api_1_1

Create the Nutritionix API client.

Parameters:

  • id

    Nutritionix application ID

  • key

    Nutritionix API key

  • url (Optional) (defaults to: "https://api.nutritionix.com/v1_1")

    Nutritionix API url



19
20
21
22
23
24
# File 'lib/nutritionix/api_1_1.rb', line 19

def initialize(id, key, url="https://api.nutritionix.com/v1_1", logger=APILogger.default_logger)
  @app_id = id
  @app_key = key
  @app_url = url
  @logger = logger
end

Instance Attribute Details

#app_idObject

Returns the value of attribute app_id.



9
10
11
# File 'lib/nutritionix/api_1_1.rb', line 9

def app_id
  @app_id
end

#app_keyObject

Returns the value of attribute app_key.



9
10
11
# File 'lib/nutritionix/api_1_1.rb', line 9

def app_key
  @app_key
end

#app_urlObject

Returns the value of attribute app_url.



9
10
11
# File 'lib/nutritionix/api_1_1.rb', line 9

def app_url
  @app_url
end

#loggerObject

Returns the value of attribute logger.



10
11
12
# File 'lib/nutritionix/api_1_1.rb', line 10

def logger
  @logger
end

Instance Method Details

#get_item(id) ⇒ Object

This operation returns an item object that contains data on all its nutritional content

Parameters:

  • id

    string The id of the food item whose details are needed

Returns:

  • the item details as json string



153
154
155
# File 'lib/nutritionix/api_1_1.rb', line 153

def get_item(id)
  get_request(id, 'item', {})
end

#get_request(query, endpoint, params = {}) ⇒ Object

Sends a GET request to the Nutritionix API Server

by developer.nutritionix.com/docs/v1_1 Nutritionix Querying Language (NXQL) convertible to a valid JSON.

Parameters:

  • query

    string Query or search term / phrase

  • endpoint

    The endpoint to send the request to.Current valid type is: search, item, brand

  • params (defaults to: {})

    a hash containing required query, filters, etc options as defined

Returns:

  • The request result or error as json string



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
# File 'lib/nutritionix/api_1_1.rb', line 70

def get_request(query, endpoint, params={})
  query = ::CGI::escape(query)
  params = sanitize_params(params)
  add_creds_to_params(params)

  serialized_params = serialize_params(params)

  url_components = [@app_url, endpoint]
  if 'item' == endpoint
    # Heroku using older version of Ruby prepend method on String is
    # not available.Thus using String's insert method
    serialized_params.insert(0, "id=#{query}&")
  else
    url_components << query
  end

  url =  "#{url_components.join('/')}?#{serialized_params}"
  logger.debug "GET request URL: #{url}"
  header = {}
  begin
    response = RestClient.get url, header
  rescue Exception => e
    logger.error "==================================================="
    logger.debug "An exception occured while processing GET request to url: #{url}"
    logger.error e.to_s
    logger.error "==================================================="
    response = { error: e.message}.to_json
  end

  response
end

#nxql_search(search_params = {}) ⇒ Object



130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
# File 'lib/nutritionix/api_1_1.rb', line 130

def nxql_search(search_params={})
  # Default sort options
  sort_options = {
    sort: {
      field: "_score",
      order: "desc"
    }
  }

  search_params.merge!(sort_options) unless search_params[:sort].nil?

  logger.debug "Nutritionix::Api_1_1 NXQL search params: #{search_params}"

  post_request('search', search_params)
end

#post_request(endpoint, params = {}) ⇒ Object

Sends a POST request to the Nutritionix API Server

by developer.nutritionix.com/docs/v1_1 Nutritionix Querying Language (NXQL) convertible to a valid JSON.

Parameters:

  • endpoint

    The endpoint to send the request to.Current valid type is: search

  • params (defaults to: {})

    a hash containing required query, filters, etc options as defined

Returns:

  • The request result or error as json string



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/nutritionix/api_1_1.rb', line 36

def post_request(endpoint, params={})
  params = sanitize_params(params)
  add_creds_to_params(params)

  params_json = params.to_json
  logger.debug "======POST Request Params Json: #{params_json}"

  url = [@app_url, endpoint].join('/')
  logger.debug "POST request URL: #{url}"
  begin
    # Reference: http://rubydoc.info/gems/rest-client/1.6.7/RestClient.post
    response = RestClient.post(url, params_json, content_type: 'application/json')
  rescue Exception => e
    logger.error "==================================================="
    logger.debug "An exception occured while processing POST request to url: #{url}"
    logger.error e.to_s
    logger.error "==================================================="
    response = { error: e.message}.to_json
  end

  response
end

#search(term, range_start = 0, range_end = 10, cal_min = 0, cal_max = 0, fields = NIL, brand_id = NIL) ⇒ Object

Pass a search term into the API like taco, or cheese fries, and the NutritionIX API will return an array of matching foods.

by default, the api will fetch the first 10 results Supports all item properties in comma delimited format. A null parameter will return the following item fields only: item_name, brand_name, item_id. NOTE– passing “*” as a value will return all item fields.

Parameters:

  • term

    string The phrase or terms you would like to search by

  • range_start (defaults to: 0)

    integer (Optional)Start of the range of results to view a section of up to 500 items in the “hits” array

  • range_end (defaults to: 10)

    integer (Optional)End of the range of results to view a section of up to 500 items in the “hits” array

  • cal_min (defaults to: 0)

    integer (Optional)The minimum number of calories you want to be in an item returned in the results

  • cal_max (defaults to: 0)

    integer (Optional)The maximum number of calories you want to be in an item returned in the results

  • fields (defaults to: NIL)

    strings (Optional)The fields from an item you would like to return in the results.

  • brand_id (defaults to: NIL)

    string (Optional)Filter your results by a specific brand by passing in a brand_id

Returns:

  • The search results as json string



120
121
122
123
124
125
126
127
128
# File 'lib/nutritionix/api_1_1.rb', line 120

def search(term, range_start = 0, range_end = 10, cal_min = 0, cal_max = 0, fields = NIL, brand_id = NIL)
  get_request(term, 'search', {
      :results => "#{range_start}:#{range_end}",
      :cal_min => "#{cal_min}",
      :cal_max => "#{cal_max}",
      :fields => fields,
      :brand_id => brand_id,
  })
end