openfoodfacts

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: May 6, 2022 License: MIT Imports: 9 Imported by: 5

README

openfoodfacts-go

Build Status

About

This library is for accessing OpenFoodFacts data for food product, ingredients and nutritional data from within your go application. You can also get the Nutri-Score and the Eco-Score

Use of the OpenFoodFacts database is subject to the OpenFoodFacts Terms of Use, please read them before using this library in your application.

This library is copyright © 2019-2021 OpenFoodFacts. All rights reserved. Use of this library is governed by the MIT license which can be found in the LICENSE.txt file.

Documentation

Package documentation

OpenFoodFacts API details

Go API wiki page

Usage details

This is a very simple example how to use the library in you go program.

package main

import (
	"github.com/openfoodfacts/openfoodfacts-go"
)

func main() {
	api := openfoodfacts.NewClient("world", "", "")
	product, err := api.Product("0737628064502")
}

There are runnable examples in the examples subdirectory.

Authors

Ken Allan

Documentation

Overview

This is a go library used to access the OpenFoodFacts.org database for food product, ingredients and nutritional data from within your go application.

The main method of using this library is to create a DataOperator and call methods on it.

Example

Create a Client to retrieve and modify database items. Client interacts with the official HTTP API from openfoodfacts.org.

NewClient("world", "", "")
Output:

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// ErrNoProduct is an error returned by Client.Product when the product could not be
	// retrieved successfully.
	// It is not a transient error, the product does not exist.
	ErrNoProduct = errors.New("Product retrieval failure")

	// ErrUnauthorized is an error returned by Client methods that require a valid user account, but none
	// was provided when the Client was instantiated.
	ErrUnauthorized = errors.New("Action requires user account")
)

Functions

This section is empty.

Types

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client is an OpenFoodFacts client. It uses the official API as data source.

func NewClient

func NewClient(locale, username, password string) Client

NewClient returns a Client that is capable of talking to the official OpenFoodFacts database via the HTTP API, or the dev server if live is false.

The locale should be one of "world" or the country level code for the locale you wish to use.

The username and password should be set to your OpenFoodFacts credentials if you need WRITE access, else provide them both as empty strings for anonymous access.

Sandbox mode

If you are testing your application, you should use the test server in order to use the sandbox environment instead of the live servers. See the Sandbox() method for more detail and an example.

Timeout

By default the HTTP client doesn't sets a timeout. See the Timeout(time.Duration) method for more detail.

UserAgent

Please set a UserAgent HTTP Header with the name of the app/service querying, the version, system and a URL if you have one, so that you are not blocked by mistake (e.g. CoolFoodApp - Go - Version 1.0 - https://coolfoodapp.com)

func (*Client) Product

func (h *Client) Product(code string) (*Product, error)

Product returns a new Product for the given code, retrieved from the server.

It will return an error on a failed retrieval, if the retrieval is successful but the API result status is not 1, then will return a "ProductRetrievalError" error. This indicates the product is not available.

Example

You can use the Client.Product method to retrieve a Product by barcode.

api := NewClient("world", "", "")
product, err := api.Product("5201051001076")
if err != nil {
	fmt.Printf("%+v\n", product)
}
Output:

func (*Client) Sandbox

func (h *Client) Sandbox()

Sandbox configures this operator to use the sandbox server at http://world.openfoodfacts.net instead of the live server. This is used for testing purposes instead of operating on the live server.

Example

This will enable test mode and connect you to the sandbox server.

api := NewClient("world", "", "")
api.Sandbox() // Enable test mode
Output:

func (*Client) Timeout

func (h *Client) Timeout(timeout time.Duration)

Timeout configures the HTTP client timeout. As the net/http specifies a 0 timeout means no timeout.

Example

This will set a timeout for the http client

api := NewClient("world", "", "")
api.Timeout(10 * time.Second) // Set http client timeout
Output:

func (*Client) UserAgent

func (h *Client) UserAgent(ua string)

UserAgent configures the HTTP User-Agent Header.

type EpochTime

type EpochTime struct {
	time.Time
}

EpochTime allows the proper un/marshaling of a seconds-since-epoch value from JSON.

func (*EpochTime) MarshalJSON

func (t *EpochTime) MarshalJSON() ([]byte, error)

func (*EpochTime) UnmarshalJSON

func (t *EpochTime) UnmarshalJSON(b []byte) (err error)

type Ingredient

type Ingredient struct {
	ID         string      `json:"id"`
	Rank       int         `json:"rank,omitempty"`
	Text       string      `json:"text"`
	Vegan      string      `json:"vegan,omitempty"`
	Vegetarian string      `json:"vegetarian,omitempty"`
	Percent    json.Number `json:"percent,omitempty"`
}

type NutrientLevel

type NutrientLevel struct {
	Sugars       string `json:"sugars"`
	SaturatedFat string `json:"saturated-fat"`
	Fat          string `json:"fat"`
	Salt         string `json:"salt"`
}

type Nutriment

type Nutriment struct {
	Salt                    float64 `json:"salt"`
	Salt100G                float64 `json:"salt_100g"`
	SaltValue               float64 `json:"salt_value"`
	SaltServing             float64 `json:"salt_serving"`
	SaltUnit                string  `json:"salt_unit"`
	Sugars100G              float64 `json:"sugars_100g"`
	Sugars                  float64 `json:"sugars"`
	SugarsUnit              string  `json:"sugars_unit"`
	SugarsServing           float64 `json:"sugars_serving"`
	SugarsValue             float64 `json:"sugars_value"`
	Iron                    float64 `json:"iron"`
	IronValue               float64 `json:"iron_value"`
	IronLabel               string  `json:"iron_label"`
	IronUnit                string  `json:"iron_unit"`
	Iron100G                float64 `json:"iron_100g"`
	IronServing             float64 `json:"iron_serving"`
	CalciumUnit             string  `json:"calcium_unit"`
	CalciumServing          float64 `json:"calcium_serving"`
	Calcium                 float64 `json:"calcium"`
	CalciumValue            float64 `json:"calcium_value"`
	CalciumLabel            string  `json:"calcium_label"`
	Calcium100G             float64 `json:"calcium_100g"`
	Cholesterol100G         float64 `json:"cholesterol_100g"`
	SaturatedFat100G        float64 `json:"saturated-fat_100g"`
	SaturatedFatServing     float64 `json:"saturated-fat_serving"`
	SaturatedFat            float64 `json:"saturated-fat"`
	SaturatedFatValue       float64 `json:"saturated-fat_value"`
	SaturatedFatUnit        string  `json:"saturated-fat_unit"`
	Fat100G                 float64 `json:"fat_100g"`
	FatServing              float64 `json:"fat_serving"`
	FatValue                float64 `json:"fat_value"`
	FatUnit                 string  `json:"fat_unit"`
	Fat                     float64 `json:"fat"`
	TransFatLabel           string  `json:"trans-fat_label"`
	TransFatUnit            string  `json:"trans-fat_unit"`
	TransFat                float64 `json:"trans-fat"`
	TransFat100G            float64 `json:"trans-fat_100g"`
	TransFatServing         float64 `json:"trans-fat_serving"`
	TransFatValue           float64 `json:"trans-fat_value"`
	VitaminA                float64 `json:"vitamin-a"`
	VitaminA100G            float64 `json:"vitamin-a_100g"`
	VitaminAValue           float64 `json:"vitamin-a_value"`
	VitaminAServing         float64 `json:"vitamin-a_serving"`
	VitaminAUnit            string  `json:"vitamin-a_unit"`
	VitaminALabel           string  `json:"vitamin-a_label"`
	VitaminCValue           float64 `json:"vitamin-c_value"`
	VitaminCUnit            string  `json:"vitamin-c_unit"`
	VitaminC100G            float64 `json:"vitamin-c_100g"`
	VitaminC                float64 `json:"vitamin-c"`
	VitaminCServing         float64 `json:"vitamin-c_serving"`
	VitaminCLabel           string  `json:"vitamin-c_label"`
	Proteins100G            float64 `json:"proteins_100g"`
	ProteinsServing         float64 `json:"proteins_serving"`
	ProteinsValue           float64 `json:"proteins_value"`
	ProteinsUnit            string  `json:"proteins_unit"`
	Proteins                float64 `json:"proteins"`
	PolyunsaturatedFat100G  float64 `json:"polyunsaturated-fat_100g"`
	Potassium100G           float64 `json:"potassium_100g"`
	Sodium                  float64 `json:"sodium"`
	SodiumServing           float64 `json:"sodium_serving"`
	SodiumValue             float64 `json:"sodium_value"`
	Sodium100G              float64 `json:"sodium_100g"`
	SodiumUnit              string  `json:"sodium_unit"`
	CarbohydratesUnit       string  `json:"carbohydrates_unit"`
	CarbohydratesValue      float64 `json:"carbohydrates_value"`
	Carbohydrates100G       float64 `json:"carbohydrates_100g"`
	Carbohydrates           float64 `json:"carbohydrates"`
	CarbohydratesServing    float64 `json:"carbohydrates_serving"`
	AlcoholValue            float64 `json:"alcohol_value"`
	AlcoholServing          float64 `json:"alcohol_serving"`
	AlcoholUnit             string  `json:"alcohol_unit"`
	Alcohol100G             float64 `json:"alcohol_100g"`
	Alcohol                 float64 `json:"alcohol"`
	MonounsaturatedFat100G  float64 `json:"monounsaturated-fat_100g"`
	NovaGroup               float64 `json:"nova-group"`
	NovaGroupServing        float64 `json:"nova-group_serving"`
	NovaGroup100G           float64 `json:"nova-group_100g"`
	Energy                  float64 `json:"energy"`
	EnergyServing           float64 `json:"energy_serving"`
	EnergyKcalServing       float64 `json:"energy-kcal_serving"`
	EnergyKcal              float64 `json:"energy-kcal"`
	Energy100G              float64 `json:"energy_100g"`
	EnergyUnit              string  `json:"energy_unit"`
	EnergyKcalValue         float64 `json:"energy-kcal_value"`
	EnergyKcalUnit          string  `json:"energy-kcal_unit"`
	EnergyKcal100G          float64 `json:"energy-kcal_100g"`
	EnergyValue             float64 `json:"energy_value"`
	NutritionScoreUk100G    float64 `json:"nutrition-score-uk_100g"`
	NutritionScoreFrServing float64 `json:"nutrition-score-fr_serving"`
	NutritionScoreFr        float64 `json:"nutrition-score-fr"`
	NutritionScoreFr100G    float64 `json:"nutrition-score-fr_100g"`
	NutritionScoreUkServing float64 `json:"nutrition-score-uk_serving"`
	NutritionScoreUk        float64 `json:"nutrition-score-uk"`
	Fiber                   float64 `json:"fiber"`
	Fiber100G               float64 `json:"fiber_100g"`
	FiberValue              float64 `json:"fiber_value"`
	FiberServing            float64 `json:"fiber_serving"`
	FiberUnit               string  `json:"fiber_unit"`
}

Nutriment is the collection of all retruned nutriment associated with the product

type Product

type Product struct {
	Id                                          string         `json:"id"`
	Code                                        string         `json:"code"`
	Brands                                      string         `json:"brands"`
	BrandsTags                                  []string       `json:"brands_tags"`
	GenericName                                 string         `json:"generic_name"`
	GenericNameEn                               string         `json:"generic_name_en"`
	CreatedTime                                 EpochTime      `json:"created_t"`
	LastImageTime                               EpochTime      `json:"last_image_t"`
	LastModifiedTime                            EpochTime      `json:"last_modified_t"`
	CompletedTime                               EpochTime      `json:"completed_t"`
	ImageFrontSmallURL                          URL            `json:"image_front_smallURL"`
	ImageFrontThumbURL                          URL            `json:"image_front_thumb_url"`
	ImageFrontURL                               URL            `json:"image_front_url"`
	ImageIngredientsSmallURL                    URL            `json:"image_ingredients_small_url"`
	ImageIngredientsThumbURL                    URL            `json:"image_ingredients_thumb_url"`
	ImageIngredientsURL                         URL            `json:"image_ingredients_url"`
	ImageNutritionSmallURL                      URL            `json:"image_nutrition_small_url"`
	ImageNutritionThumbURL                      URL            `json:"image_nutrition_thumb_url"`
	ImageNutritionURL                           URL            `json:"image_nutrition_url"`
	ImageSmallURL                               URL            `json:"image_small_url"`
	ImageThumbURL                               URL            `json:"image_thumb_url"`
	ImageURL                                    URL            `json:"image_url"`
	Creator                                     string         `json:"creator"`
	Checkers                                    []interface{}  `json:"checkers"`
	CheckersTags                                []interface{}  `json:"checkers_tags"`
	Editors                                     []string       `json:"editors"`
	EditorsTags                                 []string       `json:"editors_tags"`
	Correctors                                  []string       `json:"correctors"`
	CorrectorsTags                              []string       `json:"correctors_tags"`
	Informers                                   []string       `json:"informers"`
	InformersTags                               []string       `json:"informers_tags"`
	Photographers                               []string       `json:"photographers"`
	PhotographersTags                           []string       `json:"photographers_tags"`
	LastEditDatesTags                           []string       `json:"last_edit_dates_tags"`
	LastEditor                                  string         `json:"last_editor"`
	LastImageDatesTags                          []string       `json:"last_image_dates_tags"`
	LastModifiedBy                              string         `json:"last_modified_by"`
	Additives                                   string         `json:"additives"`
	AdditivesDebugTags                          []interface{}  `json:"additives_debug_tags"`
	AdditivesNumber                             int            `json:"additives_n"`
	AdditivesOldNumber                          int            `json:"additives_old_n"`
	AdditivesOldTags                            []string       `json:"additives_old_tags"`
	AdditivesPrev                               string         `json:"additives_prev"`
	AdditivesPrevNumber                         int            `json:"additives_prev_n"`
	AdditivesPrevTags                           []string       `json:"additives_prev_tags"`
	AdditivesTags                               []string       `json:"additives_tags"`
	AdditivesTagsNumber                         interface{}    `json:"additives_tags_n"`
	Allergens                                   string         `json:"allergens"`
	AllergensHierarchy                          []interface{}  `json:"allergens_hierarchy"`
	AllergensTags                               []interface{}  `json:"allergens_tags"`
	Categories                                  string         `json:"categories"`
	CategoriesDebugTags                         []interface{}  `json:"categories_debug_tags"`
	CategoriesHierarchy                         []string       `json:"categories_hierarchy"`
	CategoriesPrevHierarchy                     []string       `json:"categories_prev_hierarchy"`
	CategoriesPrevTags                          []string       `json:"categories_prev_tags"`
	CategoriesTags                              []string       `json:"categories_tags"`
	CitiesTags                                  []interface{}  `json:"cities_tags"`
	CodesTags                                   []string       `json:"codes_tags"`
	Complete                                    int            `json:"complete"`
	Countries                                   string         `json:"countries"`
	CountriesHierarchy                          []string       `json:"countries_hierarchy"`
	CountriesTags                               []string       `json:"countries_tags"`
	EmbCodes                                    string         `json:"emb_codes"`
	EmbCodes20141016                            string         `json:"emb_codes_20141016"`
	EmbCodesOrig                                string         `json:"emb_codes_orig"`
	EmbCodesTags                                []interface{}  `json:"emb_codes_tags"`
	EntryDatesTags                              []string       `json:"entry_dates_tags"`
	EcoscoreGrade                               string         `json:"ecoscore_grade"`
	EcoscoreTags                                []string       `json:"ecoscore_tags"`
	ExpirationDate                              string         `json:"expiration_date"`
	FruitsVegetablesNuts100GEstimate            json.Number    `json:"fruits-vegetables-nuts_100g_estimate"`
	Ingredients                                 []Ingredient   `json:"ingredients"`
	IngredientsDebug                            []interface{}  `json:"ingredients_debug"`
	IngredientsFromOrThatMayBeFromPalmOilNumber int            `json:"ingredients_from_or_that_may_be_from_palm_oil_n"`
	IngredientsFromPalmOilNumber                int            `json:"ingredients_from_palm_oil_n"`
	IngredientsFromPalmOilTags                  []interface{}  `json:"ingredients_from_palm_oil_tags"`
	IngredientsIdsDebug                         []string       `json:"ingredients_ids_debug"`
	IngredientsN                                json.Number    `json:"ingredients_n"`
	IngredientsNTags                            []string       `json:"ingredients_n_tags"`
	IngredientsTags                             []string       `json:"ingredients_tags"`
	IngredientsText                             string         `json:"ingredients_text"`
	IngredientsTextDebug                        string         `json:"ingredients_text_debug"`
	IngredientsTextEn                           string         `json:"ingredients_text_en"`
	IngredientsTextWithAllergens                string         `json:"ingredients_text_with_allergens"`
	IngredientsTextWithAllergensEn              string         `json:"ingredients_text_with_allergens_en"`
	IngredientsThatMayBeFromPalmOilNumber       int            `json:"ingredients_that_may_be_from_palm_oil_n"`
	IngredientsThatMayBeFromPalmOilTags         []interface{}  `json:"ingredients_that_may_be_from_palm_oil_tags"`
	InterfaceVersionCreated                     string         `json:"interface_version_created"`
	InterfaceVersionModified                    string         `json:"interface_version_modified"`
	Keywords                                    []string       `json:"_keywords"`
	Labels                                      string         `json:"labels"`
	LabelsDebugTags                             []interface{}  `json:"labels_debug_tags"`
	LabelsHierarchy                             []string       `json:"labels_hierarchy"`
	LabelsPrevHierarchy                         []string       `json:"labels_prev_hierarchy"`
	LabelsPrevTags                              []string       `json:"labels_prev_tags"`
	LabelsTags                                  []string       `json:"labels_tags"`
	Lang                                        string         `json:"lang"`
	Languages                                   map[string]int `json:"languages"`
	LanguagesCodes                              map[string]int `json:"languages_codes"`
	LanguagesHierarchy                          []string       `json:"languages_hierarchy"`
	LanguagesTags                               []string       `json:"languages_tags"`
	Locale                                      string         `json:"lc"`
	ManufacturingPlaces                         string         `json:"manufacturing_places"`
	ManufacturingPlacesTags                     []string       `json:"manufacturing_places_tags"`
	MaxImgId                                    string         `json:"max_imgid"`
	NewAdditivesNumber                          int            `json:"new_additives_n"`
	NoNutritionData                             interface{}    `json:"no_nutrition_data"`
	NutrientLevels                              NutrientLevel  `json:"nutrient_levels"`
	NutrientLevelsTags                          []string       `json:"nutrient_levels_tags"`
	Nutriments                                  Nutriment      `json:"nutriments"`
	NutritionDataPer                            string         `json:"nutrition_data_per"`
	NutritionGradeFr                            string         `json:"nutrition_grade_fr"`
	NutritionGrades                             string         `json:"nutrition_grades"`
	NutritionGradesTags                         []string       `json:"nutrition_grades_tags"`
	NutritionScoreDebug                         string         `json:"nutrition_score_debug"`
	OriginTags                                  []string       `json:"origins_tags"`
	Origins                                     string         `json:"origins"`
	Packaging                                   string         `json:"packaging"`
	PackagingTags                               []string       `json:"packaging_tags"`
	PnnsGroups1                                 string         `json:"pnns_groups_1"`
	PnnsGroups1Tags                             []string       `json:"pnns_groups_1_tags"`
	PnnsGroups2                                 string         `json:"pnns_groups_2"`
	PnnsGroups2Tags                             []string       `json:"pnns_groups_2_tags"`
	ProductName                                 string         `json:"product_name"`
	ProductNameEn                               string         `json:"product_name_en"`
	PurchasePlaces                              string         `json:"purchase_places"`
	PurchasePlacesTags                          []interface{}  `json:"purchase_places_tags"`
	Quantity                                    string         `json:"quantity"`
	Rev                                         json.Number    `json:"rev"`
	ScansNumber                                 int            `json:"scans_n"`
	ServingQuantity                             json.Number    `json:"serving_quantity"`
	ServingSize                                 string         `json:"serving_size"`
	SortKey                                     int            `json:"sortkey"`
	States                                      string         `json:"states"`
	StatesHierarchy                             []string       `json:"states_hierarchy"`
	StatesTags                                  []string       `json:"states_tags"`
	Stores                                      string         `json:"stores"`
	StoresTags                                  []interface{}  `json:"stores_tags"`
	Traces                                      string         `json:"traces"`
	TracesHierarchy                             []string       `json:"traces_hierarchy"`
	TracesTags                                  []string       `json:"traces_tags"`
	UniqueScansNumber                           int            `json:"unique_scans_n"`
	UnknownNutrientsTags                        []interface{}  `json:"unknown_nutrients_tags"`
	UpdateKey                                   string         `json:"update_key"`
}

type ProductResult

type ProductResult struct {
	StatusVerbose string   `json:"status_verbose"`
	Status        int      `json:"status"`
	Code          string   `json:"code"`
	Product       *Product `json:"product"`
}

type URL

type URL struct {
	url.URL
}

URL allows URL to be properly un/marshaled from a JSON string.

func (*URL) MarshalJSON

func (u *URL) MarshalJSON() ([]byte, error)

func (*URL) UnmarshalJSON

func (u *URL) UnmarshalJSON(b []byte) error

Directories

Path Synopsis
examples
simple-get-product
A simple application to demonstrate looking up a product from the OpenFoodFacts database using the EAN number from a barcode.
A simple application to demonstrate looking up a product from the OpenFoodFacts database using the EAN number from a barcode.

Jump to

Keyboard shortcuts

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