### Legacy Suggestion API Examples Source: https://openfoodfacts.github.io/openfoodfacts-server/api/ref-cheatsheet Examples of using the legacy `suggest.pl` endpoint for retrieving suggestions for various taxonomies like ingredients, brands, and countries. ```http https://world.openfoodfacts.org/cgi/suggest.pl?tagtype=emb_codes&term=FR ``` ```http https://world.openfoodfacts.org/cgi/suggest.pl?tagtype=categories&term=f ``` ```http https://world.openfoodfacts.org/cgi/suggest.pl?tagtype=labels&term=f ``` ```http https://world.openfoodfacts.org/cgi/suggest.pl?tagtype=ingredients&term=f ``` ```http https://world.openfoodfacts.org/cgi/suggest.pl?tagtype=packaging_shapes&term=f ``` ```http https://world.openfoodfacts.org/cgi/suggest.pl?tagtype=packaging_materials&term=f ``` ```http https://world.openfoodfacts.org/cgi/suggest.pl?tagtype=packaging_shapes&term=f ``` ```http https://world.openfoodfacts.org/cgi/suggest.pl?tagtype=languages&term=f ``` ```http https://world.openfoodfacts.org/cgi/suggest.pl?tagtype=stores&term=f ``` ```http https://world.openfoodfacts.org/cgi/suggest.pl?tagtype=brands&term=f ``` ```http https://world.openfoodfacts.org/cgi/suggest.pl?tagtype=countries&term=f ``` ```http https://world.openfoodfacts.org/cgi/suggest.pl?tagtype=traces&term=f ``` ```http https://world.openfoodfacts.org/cgi/suggest.pl?tagtype=origins&term=f ``` ```http https://world.openfoodfacts.org/cgi/suggest.pl?tagtype=states&term=f ``` ```http https://world.openfoodfacts.org/cgi/suggest.pl?tagtype=nutrients&term=f ``` ```http https://world.openfoodfacts.org/cgi/suggest.pl?tagtype=additives&term=f ``` ```http https://world.openfoodfacts.org/cgi/suggest.pl?tagtype=allergens&term=f ``` ```http https://world.openfoodfacts.org/cgi/suggest.pl?tagtype=minerals&term=f ``` -------------------------------- ### Example API Request Source: https://openfoodfacts.github.io/openfoodfacts-server/api/tutorials/contributing-to-image-refresh-api This is an example of a GET request to the API to check the French images for a specific product barcode. ```URL https://fr.openfoodfacts.org/api/v2/produit/3483130043180?fields=images_to_update_fr ``` -------------------------------- ### Search Response Example Source: https://openfoodfacts.github.io/openfoodfacts-server/api/tutorial-off-api An example of a JSON response from the search API, showing product count and a list of matching products with selected fields. ```JSON { "count": 1629, "page": 1, "page_count": 24, "page_size": 24, "products": [ { "categories_tags_en": [ "Plant-based foods and beverages", "Beverages", "Plant-based beverages", "Fruit-based beverages", "Juices and nectars", "Fruit juices", "Concentrated fruit juices", "Orange juices", "Concentrated orange juices" ], "code": "3123340008288", "nutrition_grades": "c" }, . . . { "categories_tags_en": [ "Plant-based foods and beverages", "Beverages", "Plant-based beverages", "Fruit-based beverages", "Juices and nectars", "Fruit juices", "Non-Alcoholic beverages", "Orange juices", "Squeezed juices", "Squeezed orange juices" ], "code": "3608580844136", "nutrition_grades": "c" } ], "skip": 0 } ``` -------------------------------- ### Example User Preferences Source: https://openfoodfacts.github.io/openfoodfacts-server/api/tutorials/getting-personal-with-attributes Define user preferences in your code, specifying attributes they prefer and optionally attributes they wish to avoid. ```JSON { "preferred_attributes": ["nutriscore-a", "labels-organic", "ingredients-analysis-palm-oil-free"], "avoided_attributes": ["labels-gluten-free"] // optional if user has no dietary constraint } ``` -------------------------------- ### Sorted Search Response Example Source: https://openfoodfacts.github.io/openfoodfacts-server/api/tutorial-off-api An example of a JSON response sorted by the 'last_modified_t' field, showing the order of products based on their modification date. ```JSON { "count": 1629, "page": 1, "page_count": 24, "page_size": 24, "products": [ { "categories_tags_en": [ "Plant-based foods and beverages", "Beverages", "Plant-based beverages", "Fruit-based beverages", "Juices and nectars", "Fruit juices", "Orange juices" ], "code": "3800014268048", "nutrition_grades": "c" }, ' ' ' { "categories_tags_en": [ "Plant-based foods and beverages", "Beverages", "Plant-based beverages", "Fruit-based beverages", "Juices and nectars", "Fruit juices", "Orange juices", "Squeezed juices", "Squeezed orange juices" ], "code": "4056489641018", "nutrition_grades": "c" } ], "skip": 0 } ``` -------------------------------- ### Get Nutella Ferrero Product Data Source: https://openfoodfacts.github.io/openfoodfacts-server/api/tutorial-off-api Example of a GET request to retrieve data for a specific product using its barcode. ```http https://world.openfoodfacts.net/api/v2/product/3017624010701 ``` -------------------------------- ### Construct Full Resolution Raw Image URL Source: https://openfoodfacts.github.io/openfoodfacts-server/api/how-to-download-images Example of constructing the URL for a full-resolution raw image using the product's barcode and image ID. ```url https://images.openfoodfacts.org/images/products/316/893/001/0883/1.jpg ``` -------------------------------- ### Basic Search Endpoint Source: https://openfoodfacts.github.io/openfoodfacts-server/api/tutorial-off-api The base URL for the product search API. Use this as the starting point for all search requests. ```HTTP https://world.openfoodfacts.org/api/v2/search ``` -------------------------------- ### Nutri-Score Computation Response Example Source: https://openfoodfacts.github.io/openfoodfacts-server/api/tutorial-off-api An example JSON response containing detailed 'nutriscore_data' and 'nutriments' for calculating the Nutri-score. ```json { "code": "3017624010701", "product": { "nutriments": { "carbohydrates": 57.5, "carbohydrates_100g": 57.5, "carbohydrates_unit": "g", "carbohydrates_value": 57.5, "energy": 2255, "energy-kcal": 539, "energy-kcal_100g": 539, "energy-kcal_unit": "kcal", "energy-kcal_value": 539, "energy_unit": "kJ", "energy_value": 2255, "fat": 30.9, "fat_100g": 30.9, "fat_unit": "g", "fat_value": 30.9, "proteins": 6.7, "proteins_100g": 6.7, "proteins_unit": "g", "proteins_value": 6.7, "sugars": 56.3, "sugars_100g": 56.3, "sugars_unit": "g", "sugars_value": 56.3 }, "nutriscore_data": { "energy": 2255, "energy_points": 6, "energy_value": 2255, "grade": "e", "grades": { "a": null, "b": null, "c": null, "d": null, "e": 10 }, "is_beverage": false, "negative_points": 0, "positive_points": 10, "score": "10", "saturated-fat": 10.6, "saturated-fat_points": 10, "saturated-fat_value": 10.6, "sodium": 0.01, "sodium_points": 0, "sodium_value": 0.01, "sugars": 56.3, "sugars_points": 10, "sugars_value": 56.3 }, "nutrition_grades": "e", "product_name": "Nutella" }, "status": 1, "status_verbose": "product found" } ``` -------------------------------- ### Get Suggestions - Legacy suggest.pl Source: https://openfoodfacts.github.io/openfoodfacts-server/api/ref-cheatsheet Retrieve suggestions for various fields like brands, categories, and ingredients using the legacy `suggest.pl` endpoint. ```APIDOC ## Get Suggestions - Legacy suggest.pl ### Description This legacy solution provides suggestions for various data fields, including brands, categories, and ingredients. It returns all taxonomized values and only taxonomized values. ### Endpoint Examples - `https://world.openfoodfacts.org/cgi/suggest.pl?tagtype={tagtype}&term={term}` ### Parameters #### Query Parameters - **tagtype** (string) - Required - The type of tag to get suggestions for (e.g., `brands`, `categories`, `ingredients`) - **term** (string) - Required - The search term for suggestions ``` -------------------------------- ### Adding Categories to a Product Source: https://openfoodfacts.github.io/openfoodfacts-server/api/tutorials/adding-missing-products This example demonstrates how to add categories to a product using the `add_categories` parameter. Using the `add_` prefix ensures that new categories are appended without deleting existing ones. ```HTTP POST https://us.openfoodfacts.org/cgi/product_jqm2.pl?code=0074570036004&user_id=test&password=test&add_categories=Desserts ``` -------------------------------- ### Search with Filters Source: https://openfoodfacts.github.io/openfoodfacts-server/api/tutorial-off-api Filter products by category and nutrition grade. This example searches for 'Orange Juice' with a nutrition grade of 'c'. ```HTTP https://world.openfoodfacts.net/api/v2/search?categories_tags_en=Orange Juice&nutrition_grades_tags=c ``` -------------------------------- ### Example Wikidata Link in API Output Source: https://openfoodfacts.github.io/openfoodfacts-server/api/leveraging-links-to-wikidata This JSON snippet shows an example of a Wikidata link within the Open Food Facts API output for categories. ```json { "linkeddata": { "wikidata:en": "Q40050" }, "url": "https://world.openfoodfacts.org/category/beverages", "name": "Beverages", "id": "en:beverages", "products": 14196 } ``` -------------------------------- ### User-Agent Header Example Source: https://openfoodfacts.github.io/openfoodfacts-server/api/tutorials/finding-healthy-cereals A User-Agent header is required for API calls. It identifies your application to prevent accidental blocking. ```text User-Agent: HealthyFoodChoices - Android - Version 1.0 ``` -------------------------------- ### Construct Lower Resolution Raw Image URL Source: https://openfoodfacts.github.io/openfoodfacts-server/api/how-to-download-images Example of constructing the URL for a lower-resolution raw image (e.g., 400px) using the product's barcode and image ID. ```url https://images.openfoodfacts.org/images/products/316/893/001/0883/1.400.jpg ``` -------------------------------- ### Read Product Data - Get Product with Blame Information Source: https://openfoodfacts.github.io/openfoodfacts-server/api/ref-cheatsheet Retrieve product data along with information about who last modified each field and when. ```APIDOC ## Read Product Data - Get Product with Blame Information ### Description To obtain details about the last modification of each field in a product's data, include the `blame` parameter in your request. ### Endpoint `https://world.openfoodfacts.org/api/v2/product/{product_id}.json?blame=1` ### Parameters #### Query Parameters - **blame** (integer) - Optional - Set to `1` to include blame information ### Response Fields (within `blame` object) - **userid** (string) - The ID of the user who last modified the field - **t** (integer) - Timestamp of the modification - **rev** (string) - Revision number of the modification - **value** (string) - The current value of the field ``` -------------------------------- ### Get Product Data with Specific Fields Source: https://openfoodfacts.github.io/openfoodfacts-server/api/tutorial-off-api This request uses query parameters to limit the response to only 'product_name' and 'nutriscore_data'. This is useful for fetching only the necessary information. ```http https://world.openfoodfacts.net/api/v2/product/3017624010701?fields=product_name,nutriscore_data ``` -------------------------------- ### Nutri-Score Response Example Source: https://openfoodfacts.github.io/openfoodfacts-server/api/tutorial-off-api A sample JSON response from the API, showing product name and Nutri-score. The 'status' field indicates if the product was found. ```json { "code": "3017624010701", "product": { "nutrition_grades": "e", "product_name": "Nutella" }, "status": 1, "status_verbose": "product found" } ``` -------------------------------- ### Conditional Prompts for Product Data Completion Source: https://openfoodfacts.github.io/openfoodfacts-server/api/tutorials/get-ingredient-related-analysis Use these conditions to prompt users for necessary ingredient and category information to determine processing levels and additives. These prompts guide users on what data is missing. ```pseudocode if ( status= category-to-be-completed && status = ingredients-to-be-completed ) then "Add ingredients and a category to see the level of food processing and potential additives" if ( status= category-to-be-completed ) then "Add a category to see the level of food processing and potential additives" if ( status = ingredients-to-be-completed ) then "Add ingredients to see the level of food processing and potential additives" ``` -------------------------------- ### Get Product Barcode Endpoint Source: https://openfoodfacts.github.io/openfoodfacts-server/api/tutorial-off-api This is the base endpoint for retrieving product information by barcode. Replace {barcode} with the actual product's barcode. ```http https://world.openfoodfacts.net/api/v2/product/{barcode} ``` -------------------------------- ### Successful Product Image Upload Response Source: https://openfoodfacts.github.io/openfoodfacts-server/api/tutorial-uploading-photo-to-a-product This is an example of a successful JSON response after uploading a product image. It includes details about the saved fields and the new image ID. ```json { "files": [ { "url": "/product/0180411000803/100%-real-orange-juice", "filename": "", "name": "100% Real Orange Juice", "thumbnailUrl": "/images/products/018/041/100/0803.jpg", "code": "0180411000803" } ], "image": { "thumb_url": "123.100.jpg", "imgid": 123, "crop_url": "123.400.jpg" }, "imgid": 123, "status": "status ok", "imagefield": "ingredients_en", "code": "0180411000803" } ``` -------------------------------- ### Query Taxonomy with Labels and Fields Source: https://openfoodfacts.github.io/openfoodfacts-server/api/ref-cheatsheet Example of querying the taxonomy endpoint for labels, specifying fields to return and including children. Useful for retrieving detailed information about specific labels. ```http https://world.openfoodfacts.org/api/v2/taxonomy?tagtype=labels&tags=en:organic,en:fair-trade&fields=name,description,children&include_children=1&lc=en,fr ``` -------------------------------- ### Get Taxonomy-Based Suggestions (v3 API) Source: https://openfoodfacts.github.io/openfoodfacts-server/api/ref-cheatsheet The v3 API offers suggestions based on taxonomy fields like synonyms, categories, and packaging shapes, with options to filter by language and get synonyms. ```APIDOC ## Get Taxonomy-Based Suggestions (v3 API) ### Description This v3 API endpoint provides suggestions derived from taxonomy fields such as synonyms, categories, and packaging shapes. You can refine suggestions by language and request synonyms. ### Endpoint `https://world.openfoodfacts.org/api/v3/taxonomy_suggestions` ### Parameters #### Query Parameters - **tagtype** (string) - Required - The type of taxonomy field (e.g., `labels`, `categories`, `packaging_materials`) - **lc** (string) - Optional - Language code for filtering suggestions (e.g., `fr`) - **string** (string) - Required - The search string for suggestions - **get_synonyms** (integer) - Optional - Set to `1` to include synonyms - **shape** (string) - Optional - Filter by packaging shape (e.g., `box`) ``` -------------------------------- ### Get Data for a List of Products Source: https://openfoodfacts.github.io/openfoodfacts-server/api/ref-cheatsheet Perform bulk requests by separating product codes with commas and limit the response fields using the `fields` parameter. ```http https://world.openfoodfacts.org/api/v2/search?code=3263859883713,8437011606013,6111069000451&fields=code,product_name ``` -------------------------------- ### Get Taxonomy Suggestions (v3 API) - Packaging Shape Source: https://openfoodfacts.github.io/openfoodfacts-server/api/ref-cheatsheet Fetch suggestions for packaging materials based on shape by using `tagtype=packaging_materials` and the `shape` parameter. ```http https://world.openfoodfacts.org/api/v3/taxonomy_suggestions?tagtype=packaging_materials&shape=box ``` -------------------------------- ### Get Product Data with Nutri-Score Computation Details Source: https://openfoodfacts.github.io/openfoodfacts-server/api/tutorial-off-api This request includes additional fields like 'nutriscore_data' and 'nutriments' to provide details on how the Nutri-score is computed. ```http https://world.openfoodfacts.net/api/v2/product/3017624010701?fields=product_name,nutriscore_data,nutriments,nutrition_grades ``` -------------------------------- ### Get Data for a List of Products Source: https://openfoodfacts.github.io/openfoodfacts-server/api/ref-cheatsheet Retrieve data for multiple products in a single request by separating product codes with commas. The response can be limited using the `fields` parameter. ```APIDOC ## Get Data for a List of Products ### Description This endpoint allows for bulk requests by fetching data for multiple products simultaneously. Use comma separation for multiple query parameters and the `fields` parameter to limit the returned data. ### Endpoint `https://world.openfoodfacts.org/api/v2/search?code={code1},{code2}&fields={field1},{field2}` ### Parameters #### Query Parameters - **code** (string) - Required - Comma-separated list of product codes - **fields** (string) - Optional - Comma-separated list of fields to include in the response ``` -------------------------------- ### Get Product with Blame Information Source: https://openfoodfacts.github.io/openfoodfacts-server/api/ref-cheatsheet Append `?blame=1` to a product API request to retrieve modification history, including user ID, timestamp, revision, and value. ```http https://world.openfoodfacts.org/api/v2/product/3017620422003.json?blame=1 ``` -------------------------------- ### Product Attributes API Response Source: https://openfoodfacts.github.io/openfoodfacts-server/api/explain-product-attributes Example response from the Open Food Facts API showing product details including attribute groups and individual attributes with their match scores. ```json { "status": 1, "code": "3700214614266", "status_verbose": "product found", "product": { "product_name": "Chocolat noir Pérou 90% fruité et boisé", "code": "3700214614266", "attribute_groups_en": [ { "attributes": [ { "status": "known", "name": "Nutri-Score", "match": 30, "id": "nutriscore", "title": "Nutri-Score D", "description": "", "description_short": "Poor nutritional quality" } ], "name": "Nutritional quality", "id": "nutritional_quality" }, { "id": "processing", "name": "Food processing", "attributes": [ { "id": "nova", "match": 50, "name": "NOVA group", "status": "known", "description_short": "Processed foods", "description": "", "title": "NOVA 3" } ] }, { "id": "labels", "name": "Labels", "attributes": [ { "title": "Organic product", "description_short": "Promotes ecological sustainability and biodiversity.", "description": "Organic farming aims to protect the environment and to conserve biodiversity by prohibiting or limiting the use of synthetic fertilizers, pesticides and food additives.", "name": "Organic farming", "match": 100, "status": "known", "id": "labels_organic" }, { "id": "labels_fair_trade", "match": 100, "name": "Fair trade", "status": "known", "description_short": "Fair trade products help producers in developing countries.", "description": "When you buy fair trade products, producers in developing countries are paid a higher and fairer price, which helps them improve and sustain higher social and often environmental standards.", "title": "Fair trade product" } ] } ] } } ``` -------------------------------- ### Get Taxonomy Suggestions (v3 API) - Labels Source: https://openfoodfacts.github.io/openfoodfacts-server/api/ref-cheatsheet Retrieve suggestions for labels using the v3 API, specifying the language (`lc`) and search string (`string`). ```http https://world.openfoodfacts.org/api/v3/taxonomy_suggestions?tagtype=labels&lc=fr&string=f&get_synonyms=1 ``` -------------------------------- ### Query Taxonomy with Categories and Parents Source: https://openfoodfacts.github.io/openfoodfacts-server/api/ref-cheatsheet Example of querying the taxonomy endpoint for categories, requesting parent and children information, and specifying country context. Useful for exploring hierarchical category data. ```http https://world.openfoodfacts.org/api/v2/taxonomy?tagtype=categories&tags=en:carrot-juices&fields=name,parents,children,wikidata,auth_url&lc=en,fr&cc=fr ``` -------------------------------- ### Get Product Details Source: https://openfoodfacts.github.io/openfoodfacts-server/api/tutorial-off-api Retrieve detailed information about a specific product, including its name, nutriscore data, and nutriment information. This is useful for verifying updates or checking computed scores. ```APIDOC ## GET /api/v2/product/{code} ### Description Retrieves detailed information for a specific product, including its name, nutriscore data, and nutriment information. ### Method GET ### Endpoint https://world.openfoodfacts.net/api/v2/product/{code} ### Parameters #### Query Parameters - **fields** (string) - Optional - Comma-separated list of fields to include in the response. Example: `product_name,nutriscore_data,nutriments,nutrition_grades` ### Request Example ``` https://world.openfoodfacts.net/api/v2/product/0180411000803?fields=product_name,nutriscore_data,nutriments,nutrition_grades ``` ### Response #### Success Response (200) - **code** (string) - The product's barcode. - **product** (object) - Contains product details including: - **product_name** (string) - The name of the product. - **nutriments** (object) - Nutritional information. - **nutriscore_data** (object) - Data related to the Nutri-Score computation. - **nutrition_grades** (string) - The computed nutrition grade (e.g., 'c'). - **status** (integer) - Indicates the success status of the operation. - **status_verbose** (string) - A verbose description of the status. #### Response Example ```json { "code": "0180411000803", "product": { "nutriments": { "carbohydrates": 11.864406779661, "sugars_unit": "g", "sugars_value": 11.864406779661 }, "nutriscore_data": { "energy": 195, "energy_points": 7, "energy_value": 195, "sugars_value": 11.86 }, "nutrition_grades": "c", "product_name": "100% Real Orange Juice" }, "status": 1, "status_verbose": "product found" } ``` ``` -------------------------------- ### Get Taxonomy Suggestions (v3 API) - Categories Source: https://openfoodfacts.github.io/openfoodfacts-server/api/ref-cheatsheet Get category suggestions by providing the `tagtype=categories` and a search string. ```http https://world.openfoodfacts.org/api/v3/taxonomy_suggestions?tagtype=categories&string=organic ``` -------------------------------- ### Upload Product Image using curl Source: https://openfoodfacts.github.io/openfoodfacts-server/api/tutorial-uploading-photo-to-a-product Use this curl command to upload a product image. Ensure you replace placeholders with your actual user ID, password, and provide the correct file path. ```bash curl -XPOST https://world.openfoodfacts.net/cgi/product_image_upload.pl \ -F user_id=your_user_id -F password=your_password \ -F code=0180411000803 -F imagefield=ingredients_en -F imgupload_ingredients_en=@images/real-orange-juice-ingredients.jpg ``` -------------------------------- ### Adding a Product with Brand and Kosher Label Source: https://openfoodfacts.github.io/openfoodfacts-server/api/tutorials/adding-missing-products Use this endpoint to add a new product or update an existing one, specifying parameters like brand and labels. Ensure you use `add_brands` and `add_labels` for new products to avoid overwriting existing data. ```HTTP POST https://us.openfoodfacts.org/cgi/product_jqm2.pl?code=0074570036004&user_id=test&password=test&brands=Häagen-Dazs&labels=kosher ``` -------------------------------- ### Sample API Response Source: https://openfoodfacts.github.io/openfoodfacts-server/api/tutorials/contributing-to-image-refresh-api The API response contains a 'product' object with an 'images_to_update_[lang]' field. The values indicate the status of each image type. ```JSON { "product": { "images_to_update_fr": { "packaging_fr": 0, "front_fr": 83734290, "ingredients_fr": 83734290 } } } ``` -------------------------------- ### Add Prepared Nutrition Facts Source: https://openfoodfacts.github.io/openfoodfacts-server/api/ref-cheatsheet Send prepared nutritional values by appending `_prepared` to the nutrient key, e.g., `nutriment_energy-kj_prepared`. ```text * nutriment_energy-kj (regular) * nutriment_energy-kj_prepared (prepared) ``` -------------------------------- ### Test Staging API Endpoint with Basic Auth Source: https://openfoodfacts.github.io/openfoodfacts-server/api This JavaScript snippet demonstrates how to fetch product data from the staging API using basic authentication. It's useful for testing applications before deploying to production. ```javascript fetch("https://world.openfoodfacts.net/api/v2/product/3274080005003.json", { method: "GET", headers: { Authorization: "Basic " + btoa("off:off") }, }) .then((response) => response.json()) .then((json) => console.log(json)); ``` -------------------------------- ### Setting a Proper User-Agent Source: https://openfoodfacts.github.io/openfoodfacts-server/api/tutorials/scanning-barcodes It is essential to set a proper User-Agent header for API etiquette. Use the specified format including your app name, platform, version, and a contact URL. ```text User-Agent: MyAppName - Android - Version 2.1 - https://example.com - scan ``` -------------------------------- ### Filter and Download Sample Images Source: https://openfoodfacts.github.io/openfoodfacts-server/api/aws-images-dataset Extract a random sample of images from the dataset by filtering the data keys file and downloading selected images. ```bash # Extract images from AWS n=1000 images_dir="images" bucket_url="https://openfoodfacts-images.s3.eu-west-3.amazonaws.com/" zcat data_keys.gz | grep '.jpg' | # Filter shuf -n "$n" | # Random sample sed "s|^|$bucket_url|" | #Add bucket_url: "https://openfoodfacts-images.s3.eu-west-3.amazonaws.com/data/376/005/047/0099/1.jpg" while read -r url; do filename=$(echo "$url" | sed "s|$bucket_url||" | tr '/' '_' | sed 's|data_||') # Filename as 376_005_047_0099_1.jpg wget -O "$images_dir/$filename" "$url" done ``` -------------------------------- ### Get Partial Taxonomy Entries (v2 API) Source: https://openfoodfacts.github.io/openfoodfacts-server/api/ref-cheatsheet Use the `/api/v2/taxonomy` endpoint to retrieve specific taxonomy entries instead of downloading the entire taxonomy. ```APIDOC ## Get Partial Taxonomy Entries (v2 API) ### Description This endpoint allows you to fetch selected taxonomy entries without needing to download the complete taxonomy dataset. It's efficient for accessing specific classification data. ### Endpoint `/api/v2/taxonomy` ``` -------------------------------- ### Generate Open Food Facts Image URL (Python) Source: https://openfoodfacts.github.io/openfoodfacts-server/api/how-to-download-images Use this Python function to generate the correct URL for a product image. It handles both raw and selected images, different resolutions, and constructs the product folder path based on the product code. ```python def get_image_url(product_data, image_name, resolution="full"): if image_name not in product_data["images"]: return None base_url = "https://images.openfoodfacts.org/images/products" # get product folder name folder_name = product_data["code"] if len(folder_name) > 8: folder_name = re.sub(r'(...)(...)(...)(.*)', r'\1/\2/\3/\4', folder_name) # get filename if re.match("^\d+$", image_name): # only digits # raw image resolution_suffix = "" if resolution == "full" else f".{resolution}" filename = f"{image_name}{resolution_suffix}.jpg" else: # selected image rev = product_data["images"][image_name]["rev"] filename = f"{image_name}.{rev}.{resolution}.jpg" # join things together return f"{base_url}/{folder_name}/{filename}" ``` -------------------------------- ### Fetch Product with Attributes Source: https://openfoodfacts.github.io/openfoodfacts-server/api/tutorials/getting-personal-with-attributes Retrieve a specific product's details, including its associated attribute groups. Use the 'fields' parameter to specify 'attribute_groups' for inclusion. ```HTTP GET https://world.openfoodfacts.org/api/v2/product/3700214614266?fields=product_name,code,attribute_groups ``` -------------------------------- ### Add or Edit A Product Source: https://openfoodfacts.github.io/openfoodfacts-server/api/tutorial-off-api This endpoint allows you to add or edit product information. It requires authentication with user_id and password. You can provide various product details, including nutriment data and categories, to update existing products or add new ones. ```APIDOC ## POST /cgi/product_jqm2.pl ### Description Allows adding or editing product information, including nutriment data and categories. Requires authentication. ### Method POST ### Endpoint https://world.openfoodfacts.net/cgi/product_jqm2.pl ### Parameters #### Request Body - **user_id** (string) - Required - A valid user_id for authentication. - **password** (string) - Required - A valid password for authentication. - **code** (string) - Required - The barcode of the product to be added/edited. - **nutriment_sodium** (string) - Optional - Amount of sodium. - **nutriment_sodium_unit** (string) - Optional - Unit of sodium relative to the amount. - **categories** (string) - Optional - Category of the Product. ### Request Example ```json { "user_id": "your_user_id", "password": "your_password", "code": "0180411000803", "nutriment_sodium": "0.015", "nutriment_sodium_unit": "g", "categories": "Orange Juice" } ``` ### Response #### Success Response (200) - **status_verbose** (string) - Indicates that the fields have been saved. - **status** (integer) - Indicates the success status of the operation. #### Response Example ```json { "status_verbose": "fields saved", "status": 1 } ``` ``` -------------------------------- ### Get Missing Tags for Nutri-Score Computation Source: https://openfoodfacts.github.io/openfoodfacts-server/api/tutorial-off-api Retrieve the `misc_tags` field for a product to identify missing data required for Nutri-Score computation. This helps in understanding what data needs to be provided. ```APIDOC ## GET /api/v2/product/{code} ### Description Retrieves the `misc_tags` field for a product, which indicates missing data required for Nutri-Score computation. ### Method GET ### Endpoint https://world.openfoodfacts.net/api/v2/product/{code} ### Parameters #### Query Parameters - **fields** (string) - Required - Specify `misc_tags` to retrieve this specific field. Example: `misc_tags` ### Request Example ``` https://world.openfoodfacts.net/api/v2/product/0180411000803?fields=misc_tags ``` ### Response #### Success Response (200) - **code** (string) - The product's barcode. - **product** (object) - Contains product details: - **misc_tags** (array) - A list of tags indicating missing data or computation status (e.g., `en:nutriscore-missing-category`, `en:nutriscore-missing-nutrition-data-sodium`). - **status** (integer) - Indicates the success status of the operation. - **status_verbose** (string) - A verbose description of the status. #### Response Example ```json { "code": "0180411000803", "product": { "misc_tags": [ "en:nutriscore-not-computed", "en:nutriscore-missing-category", "en:nutrition-not-enough-data-to-compute-nutrition-score", "en:nutriscore-missing-nutrition-data", "en:nutriscore-missing-nutrition-data-sodium", "en:ecoscore-extended-data-not-computed", "en:ecoscore-not-computed", "en:main-countries-new-product" ] }, "status": 1, "status_verbose": "product found" } ``` ``` -------------------------------- ### Get Ecoscore Grade using Raw API Source: https://openfoodfacts.github.io/openfoodfacts-server/api/tutorials/get-the-green-score Retrieve the ecoscore_grade field for a specific product using the Open Food Facts Raw API. This field indicates the environmental score from A to F. ```json https://world.openfoodfacts.org/api/v0/product/3414280980209.json?fields=environmental_score_grade ``` ```json https://world.openfoodfacts.org/api/v0/product/3414280980209.json?fields=ecoscore_grade ``` ```json {"status_verbose":"product found","product":{"ecoscore_grade":"b"},"status":1,"code":"3414280980209"} ``` -------------------------------- ### Download Image using wget Source: https://openfoodfacts.github.io/openfoodfacts-server/api/aws-images-dataset Directly download a specific image from the S3 bucket using wget. ```bash wget https://openfoodfacts-images.s3.eu-west-3.amazonaws.com/data/401/235/911/4303/1.jpg ``` -------------------------------- ### Fetch Multiple Products with Attributes Source: https://openfoodfacts.github.io/openfoodfacts-server/api/tutorials/getting-personal-with-attributes Efficiently fetch multiple products by their codes and include their attribute groups. This is useful for batch processing and applying matching algorithms to a list of products. ```HTTP GET https://world.openfoodfacts.org/api/v2/search?code=3700214614266,3274080005003,3017620429484&fields=product_name,code,attribute_groups ``` -------------------------------- ### Get Product States for Green Score Calculation Source: https://openfoodfacts.github.io/openfoodfacts-server/api/tutorials/get-the-green-score Retrieve product states, including environmental score grade and tags, to determine if Green Score computation is possible or if data is missing. This is useful for displaying relevant disclaimers to the user. ```json https://world.openfoodfacts.org/api/v0/product/3414280980209.json?fields=environmental_score_grade,states_tags ``` ```json https://world.openfoodfacts.org/api/v0/product/3414280980209.json?fields=environmental_score_grade,ecoscore_alpha,states_tags ``` -------------------------------- ### Check for Missing Nutrition Photo or Uploads Source: https://openfoodfacts.github.io/openfoodfacts-server/api/tutorials/get-the-nutriscore Implement this logic to prompt users when a nutrition photo is missing or needs to be uploaded. ```Python if "en:nutrition-photo-to-be-selected" in states_tags OR "en:photos-to-be-uploaded" in states_tags ``` -------------------------------- ### Download Data Keys File Source: https://openfoodfacts.github.io/openfoodfacts-server/api/aws-images-dataset Download the gzipped text file containing all object keys in the S3 bucket. ```bash wget https://openfoodfacts-images.s3.eu-west-3.amazonaws.com/data/data_keys.gz ``` -------------------------------- ### Add/Edit Product - Prepared Product Nutrition Facts Source: https://openfoodfacts.github.io/openfoodfacts-server/api/ref-cheatsheet Add prepared nutritional values for a product, differentiating them from regular values using a `_prepared` suffix. ```APIDOC ## Add/Edit Product - Prepared Product Nutrition Facts ### Description You can provide nutritional values for the prepared version of a product. These are indicated by appending `_prepared` to the standard nutrient field name. ### Parameters #### Query Parameters - **nutriment_energy-kj_prepared** (integer) - Optional - Prepared energy value in kJ ``` -------------------------------- ### Add/Edit Product - Adding Values to Existing Fields Source: https://openfoodfacts.github.io/openfoodfacts-server/api/ref-cheatsheet Prefix field names with `add_` to append new values to existing fields like categories, labels, or brands. ```APIDOC ## Add/Edit Product - Adding Values to Existing Fields ### Description To add new values to fields that already contain data, such as categories, labels, or brands, prefix the field name with `add_`. ### Parameters #### Query Parameters - **add_categories** (string) - Optional - Add new categories - **add_labels** (string) - Optional - Add new labels - **add_brands** (string) - Optional - Add new brands ``` -------------------------------- ### Filter Data Keys for 400px Images Source: https://openfoodfacts.github.io/openfoodfacts-server/api/aws-images-dataset Use zcat and grep to filter the data keys file and list only the 400px versions of all images. ```bash zcat data_keys.gz | grep '.400.jpg' ``` -------------------------------- ### List and descriptions of available product attributes Source: https://openfoodfacts.github.io/openfoodfacts-server/api/explain-product-attributes Retrieve a list of all available product attribute groups and their associated attributes. This endpoint provides machine-readable data and internationalized human-friendly data for various product characteristics. ```APIDOC ## GET /api/v3.4/attribute_groups ### Description Fetches a list of all available product attribute groups and their attributes for API v3.4 and later. ### Method GET ### Endpoint /api/v3.4/attribute_groups ### Parameters None ### Response #### Success Response (200) Returns a JSON array of attribute groups. Each group contains an `id`, `name`, optional `warning`, and an `attributes` array. Each attribute in the `attributes` array contains an `id`, `name`, `setting_name`, optional `setting_note`, and optional `parameters`. #### Response Example ```json [ { "id": "nutritional_quality", "name": "Nutritional quality", "attributes": [ { "id": "nutriscore", "name": "Nutri-Score", "setting_name": "Good nutritional quality (Nutri-Score)" } ] } ] ``` ## GET /api/v2/attribute_groups ### Description Fetches a list of all available product attribute groups and their attributes for API v2. ### Method GET ### Endpoint /api/v2/attribute_groups ### Parameters None ### Response #### Success Response (200) Returns a JSON array of attribute groups. The structure is similar to API v3.4 but may not support attributes with parameters. ## GET /api/v2/attribute_groups_[language code] ### Description Fetches a list of all available product attribute groups and their attributes for API v2, localized to a specific language. ### Method GET ### Endpoint /api/v2/attribute_groups_[language code] ### Parameters - **language code** (string) - Required - The ISO 639-1 code for the desired language (e.g., 'en', 'fr'). ### Response #### Success Response (200) Returns a JSON array of attribute groups localized to the specified language. The structure is similar to API v2. ### Note API versions prior to 3.4 do not support product attributes with parameters. ``` -------------------------------- ### Client-Side Logic for Button Text Source: https://openfoodfacts.github.io/openfoodfacts-server/api/tutorials/contributing-to-image-refresh-api This pseudo-code demonstrates how to parse the API response to determine whether to prompt the user to 'Take' a new picture (if missing) or 'Refresh' an old one. ```Pseudocode // Assume 'images_to_update' is the object from the API response // e.g., { packaging_fr: 0, front_fr: 83734290 } for (key, value) in images_to_update: // 1. Determine the action (verb) let verb = "" if value == 0: verb = "Take" // Image is missing else: verb = "Refresh" // Image is old // 2. Get the field name and language // e.g., "front_fr" -> ["front", "fr"] let parts = key.split("_") let field_name = parts[0] let field_language = parts[1] // Useful for localization // 3. Create the button text // You would use localized strings in a real app let button_text = `${verb} ${field_name} picture` // Now, create a button with this text. // e.g., "Refresh front picture", "Take packaging picture" ```