gondb

package module
v0.0.0-...-16f6a7b Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 17, 2016 License: LGPL-3.0 Imports: 5 Imported by: 0

README

gondb

Build Status GoDoc

gondb is a simple, transparent Go package for accessing the National Nutrient Database for Standard Reference API.

Successful API queries return native Go structs that can be used immediately, with no need for type assertions.

gondb implements the endpoints defined in the documentation: http://ndb.nal.usda.gov/ndb/doc/. More detailed information about the behavior of each particular endpoint can be found at the official documentation of the API.

Examples

Installation

$ go get -u github.com/abadojack/gondb

##Usage

	import "github.com/abadojack/gondb"

Authentication

A data.gov API key must be incorporated into each API request. Sign up now if you do not have a key.

api := gondb.NewClient(nil, "your-api-key")

Queries

Executing queries is simple.

	result, _ := api.Search("cheese", nil)
	for _, item := range result.Items {
		fmt.Println(item.Ndbno)
	}

The endpoints allow separate optional parameter; if desired, these can be passed as the final parameter.

	v := url.Values{}
	v.Set("ndbno", "01009")
	v.Set("type", "f")

	nutrientIDs := []string{"204", "205", "269"}

	report, _ := api.GetNutrientReport(nutrientIDs, v)

Check the NDB documentation for the various parameters for each endpoint.

Usage Example

//A program to display the name and quantity of each nutrient in a raw mango.
package main

import (
	"fmt"

	"github.com/abadojack/gondb"
)

func main() {
	api := gondb.NewClient(nil, "DEMO_KEY")

	result, err := api.Search("fried chicken", nil)

	if err != nil {
		panic(err)
	}

	if len(result.Items) > 0 {
		for _, item := range result.Items {
			report, err := api.GetFoodReport(item.Ndbno, nil)
			if err != nil {
				panic(err)
			}

			for _, nutrient := range report.Food.Nutrients {
				fmt.Println(nutrient.Name, nutrient.Value, nutrient.Unit)
			}

		}
	}
}

Licence

gondb is free software licensed under the GNU LGPL license. Details provided in the LICENSE file.

Documentation

Overview

Package gondb provides structs and functions for accessing the National Nutrient Database for Standard Reference API.

Successful API queries return native Go structs that can be used immediately, with no need for type assertions.

Authentication

A data.gov API key must be incorporated into each API request. Sign up (http://ndb.nal.usda.gov/ndb/doc/#) now if you do not have a key.

api := NewClient(nil, "your-api-key")

Queries

Executing queries is simple.

result, _ := api.Search("cheese", nil)
for _, item := range result.Items {
	fmt.Println(item.Ndbno)
}

The endpoints allow separate optional parameter; if desired, these can be passed as the final parameter.

v := url.Values{}
v.Set("ndbno", "01009")
v.Set("type", "f")

nutrientIDs := []string{"204", "205", "269"}

report, _ := api.GetNutrientReport(nutrientIDs, v)

Endpoints

gondb implements the endpoints defined in the documentation: http://ndb.nal.usda.gov/ndb/doc/.

More detailed information about the behavior of each particular endpoint can be found at the official documentation.

Index

Constants

View Source
const (
	BaseURL = "http://api.nal.usda.gov/ndb/"
)

BaseURL represents the base URL for API requests.

Variables

This section is empty.

Functions

This section is empty.

Types

type APIError

type APIError struct {
	Code    string `json:"code"`
	Message string `json:"message"`
}

APIError represents an code/message error pair returned by the API.

func (APIError) Error

func (e APIError) Error() string

type Client

type Client struct {
	HTTPClient *http.Client

	//APIKey required to use the NDB API. Must be a data.gov registered API key.
	APIKey string
}

Client represents an NDB API client.

func NewClient

func NewClient(httpClient *http.Client, apiKey string) *Client

NewClient returns a new NDB API client. http.Default will be used if no httpClient is provided.

func (Client) GetFoodReport

func (c Client) GetFoodReport(Ndbno string, v url.Values) (FoodReport, error)

GetFoodReport obtains nutrient reports on individual foods.

func (Client) GetList

func (c Client) GetList(v url.Values) (List, error)

GetList returns metadata about your request and a list of names and id's of foods or nutrients depending on you request. With no other parameters the request will return 50 foods items sorted by food name beginning with the first item (0 offset) in JSON format.

func (Client) GetNutrientReport

func (c Client) GetNutrientReport(nutrientsID []string, v url.Values) (NutrientReport, error)

GetNutrientReport returns a list of foods and their nutrient values for a set of specified nutrients.

func (Client) Search

func (c Client) Search(searchTerm string, v url.Values) (SearchResultList, error)

Search request sends keyword queries and returns lists of foods which contain one or more of the keywords in the food description, scientific name, or commerical name fields.

type Food

type Food struct {
	NdbNo              string      `json:"nodno"`
	Name               string      `json:"name"`
	FoodGroup          string      `json:"fg"`
	ScientificName     string      `json:"sn"`
	CommercialName     string      `json:"cn"`
	Manufacturer       string      `json:"manu"`
	NitrogenFactor     float64     `json:"nf"`
	CarbohydrateFactor float64     `json:"cf"`
	FatFactor          float64     `json:"ff"`
	ProteinFactor      float64     `json:"pf"`
	Refuse             string      `json:"r"`
	RefuseDescription  string      `json:"rd"`
	Nutrients          []Nutrients `json:"nutrients"`
	Weight             float64     `json:"weight"`
	FoodMeasure        string      `json:"measures"`
}

Food represents metadata elements for a food.

type FoodReport

type FoodReport struct {
	StdReleaseVersion string     `json:"sr"` //Standard Release version of the data being reported
	Type              string     `json:"type"`
	Food              Food       `json:"food"`
	Sources           []Sources  `json:"sources"`
	FootNotes         []Footnote `json:"footnotes"`
	Languals          []Langual  `json:"language"`
}

FoodReport represents basic information about the report.

type Footnote

type Footnote struct {
	Idv         string `json:"idv"`
	Description string `json:"desc"`
}

Footnote represents an id/text pair of a footnote

type Item

type Item struct {
	Offset int    `json:"offset"`
	Group  string `json:"group"`
	Name   string `json:"name"`
	Ndbno  string `json:"ndbno"`
	ID     string `json:"id"`
}

Item represents individual items on the list.

type Langual

type Langual struct {
	Code        string `json:"code"`
	Description string `json:"code"`
}

Langual represents LANGUAL codes assigned to the food.

type List

type List struct {
	Type              string `json:"lt"`
	Start             int    `json:"start"`
	End               int    `json:"end"`
	Total             int    `json:"total"`
	StdReleaseVersion string `json:"sr"`
	Sort              string `json:"sort"`
	Items             []Item `json:"item"`
}

List represents a list of foods, nutrients or food groups.

type Measures

type Measures struct {
	Label      string      `json:"label"`
	Equivalent float64     `json:"eqv"`
	Value      interface{} `json:"value"` //Can either be string or float64
	Quantity   float64     `json:"qty"`
}

Measures represents list of measures reported for a nutrient.

type NutrientReport

type NutrientReport struct {
	StdReleaseVersion string      `json:"sr"` //Standard Release version of the data being reported
	Groups            interface{} `json:"groups"`
	Subset            string      `json:"subset"`
	Start             int         `json:"start"`
	End               int         `json:"end"`
	Total             int         `json:"total"`
	Foods             []Food      `json:"foods"`
}

NutrientReport represents basic information about the nutrient report.

type Nutrients

type Nutrients struct {
	ID            interface{} `json:"nutrient_id"` //Can either be string or int
	Name          string      `json:"name"`
	Group         string      `json:"group"`
	Unit          string      `json:"unit"`
	Value         interface{} `json:"value"` //Can either be string or float64
	SourceCode    interface{} `json:"sourcecode"`
	Dp            interface{} `json:"dp"`
	StandardError string      `json:"se"`
	Measures      []Measures  `json:"measures"`
	Gm            interface{} `json:"gm"` //Can either be float64 or string i.e "--"
}

Nutrients represents metadata elements for each nutrient.

type SearchResultList

type SearchResultList struct {
	Query                  string `json:"q"`     //terms requested and used in the search
	StandardReleaseVersion string `json:"sr"`    //Standard Release version of the data being reported
	Start                  int    `json:"start"` //beginning item in the list
	End                    int    `json:"end"`   //last item in the list
	Total                  int    `json:"total"` //total # of items returned by the search
	Group                  string `json:"group"`
	Sort                   string `json:"sort"`   //requested sort order (r=relevance or n=name)
	Offset                 int    `json:"offset"` //beginning offset into the results list for the items in the list requested
	FoodGroup              string `json:"fg"`     //food group filter
	Items                  []Item `json:"item"`
}

SearchResultList represents information about the items returned.

type Sources

type Sources struct {
	ID      int    `json:"id"`
	Title   string `json:"title"`
	Authors string `json:"authors"`
	Volume  string `json:"vol"`
	Iss     string `json:"iss"`
	Year    string `json:"year"`
	Start   string `json:"start"`
	End     string `json:"end"`
}

Sources represents reference source, usually a bibliographic citation, for the food.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL