class Nutritionix::API

Attributes

app_id[RW]
app_key[RW]
app_url[RW]

Public Class Methods

new(id, key, url="http://api.nutritionix.com/v1/") click to toggle source

Create the Nutritionix API client.

@param id Nutritionix application ID @param key Nutritionix API key @param url (Optional) Nutritionix API url

# File lib/nutritionix.rb, line 17
def initialize(id, key, url="http://api.nutritionix.com/v1/")
  @app_id = id
  @app_key = key
  @app_url = url
end

Public Instance Methods

get_brand(id) click to toggle source

This operation returns the a brand object that contains data on all its nutritional content

@param id string The id of the brand you want to retrieve

@return The brand as json string

# File lib/nutritionix.rb, line 95
def get_brand(id)
  nutritionix_request('brand',::CGI::escape(id), {})
end
get_item(id) click to toggle source

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

@param id string The id of the brand you want to retrieve

@return The brand as json string

# File lib/nutritionix.rb, line 83
def get_item(id)
  nutritionix_request('item',::CGI::escape(id), {})
end
get_serialized_params(params) click to toggle source

Combine the parameter hash with access credentials

@param params - Parameters associated with the query

@return string The request results string

# File lib/nutritionix.rb, line 107
def get_serialized_params(params)
  params['appId'] = @app_id
  params['appKey'] = @app_key
  request_params = []
  params.each do |key, value|
    request_params << "#{key}=#{::CGI::escape(value)}" unless value.nil?
  end
  request_params.join('&')
end
nutritionix_request(type, query, params) click to toggle source

Performs a query request with the Nutritionix API Server

@param type string type of query. Current valid types are: search, item, brand @param query string Query or search term / phrase @param params hash Parameters associated with the query

@return The request result as json string

@error application_not_found

# File lib/nutritionix.rb, line 64
def nutritionix_request(type, query, params)
  serialized = get_serialized_params(params)
  url = "#{File.join("#{@app_url}", "#{type}", "#{query}")}?#{serialized}"
  header = {}
  begin
    response = RestClient.get url, header
  rescue Exception => e
    {:error => e.message}.to_json
  end
end