Food Journaling has become quite popular in the past few years, as it goes without saying that having a well-balanced diet is key to living a healthy life. Whether your health goals are cutting calories, increasing energy, or simply aiming to monitor your consumption – keeping track of your daily intake will always be the first step in that journey. As per this study, 48% of Americans said that one of their New Year’s resolutions is to eat healthier.
There were times when people had to resort to the old-fashioned way of tracking food with a notebook and pen. However, this has changed with the evolution of technology and the rise of smartphones and mobile applications. As a result, diet and nutrition tracking apps are getting immensely popular. According to the research, the mobile health industry market size is forecasted to reach 100 billion USD by the end of 2021. One of the top-grossing health and fitness apps generated roughly 3.3 million USD in revenues from global users. And the biggest reason behind this rising demand for these apps is that people around the globe are becoming more aware of the health issues that obesity and poor lifestyle can cause, especially in the backdrop of the coronavirus pandemic.
Therefore, choosing a diet and nutrition app is simply a no-brainer for developers and organizations who want to venture into mobile application development. However, starting development from scratch can be a daunting task for any application.
That’s where the CalorieNinjas API comes to the rescue – you can provide it with any text, and it will extract the accurate nutrition information out of it. Moreover, the API is smart, so it doesn’t require any unique format. For example, one can ask, “Last night we ordered 14oz prime rib and mashed potatoes,” and it will return the complete nutrition breakdown of both items, such as calories, total fat, saturated fat, cholesterol, sodium, carbohydrates, fiber, sugar, and protein.
Note: If you are new to the APIs, please go through this article before diving into the details.
What is CalorieNinjas API
CalorieNinjas API is a natural language API that allows extracting nutrition information from any text. The API contains nutrition data for over 100,000 foods and beverages from all regions of the world.
The API’s backend is powered by robust algorithms that can provide customized results for any given portion size. In addition, it has a vast database containing food ingredients and complete dishes and items from popular food brands, which are constantly updated to provide accurate nutrition facts.
The API is completely free and provides an effortless way of querying the nutrition information using a single endpoint.
How does the CalorieNinjas API work?
The CalorieNinja API follows REST Guidelines and provides a single endpoint that can be invoked over the web using numerous languages and frameworks.
It works in the following way.
The Client application executes the endpoint by issuing a GET request to its Text Nutrition API. The API processes the requests and extracts nutrition information (with the help of its AI-powered algorithms and). The nutrition data is then formatted in order and then returned to the client as a JSON response.
The below diagram illustrates the high-level overview of the CalorieNinjas API.
Who can use the CalorieNinjas API?
Mobile Application Developers
Application developers aiming to build mobile or web applications in the health and fitness domain are potential users of CalorieNinjas API. It gives developers a kick start to build a highly accurate diet and nutrition app without starting from scratch. Users can create valuable features, such as daily calories intake, comprehensive macro information and nutrients breakdown, healthy and nutritious food, etc.
Nutritionists
The world is still recovering from the coronavirus pandemic, and the need to strengthen your immune system has never been more critical. CalorieNinjas API can help nutritionists around the globe to help to create an optimal nutrition plan tailor-made for their clients.
Restaurants
Food and restaurant apps can also use CalorieNinjas API. to provide nutrition facts along with their recipes or restaurant menus. The API not only includes ingredients but also complete dishes and food brands from all over the world.
Data Scientists
This API is ideal for data scientists who are keen on establishing a correlation between popular food, diet plans, and their impact on health. The API has access to over 100K food and beverages, including many famous food brands and restaurant chains.
Artificial Intelligence Enthusiasts
The API provides nutrition data such as cholesterol, saturated fat, and total fat, which can be used in developing and training the AI model to identify unhealthy foods or recipes.
How to Connect to CalorieNinjas API Tutorial – Step by Step
Connecting to CalorieNinjas API. is a three-step process which can be summarized as below:
Step1: Signup for an Account on RapidAPI
First, you need to create an account on RapidAPI (where you can find and connect to thousands of APIs using one SDK and one API Key).
Step2: Search the API Marketplace
After successful registration, you will be redirected to the dashboard. Navigate to “API Marketplace” and search for “CalorieNinjas API“.
Step3: Test the CalorieNinjas API
Navigate to the ‘Endpoints’ tab and select the ‘TextNutrition’ endpoint.
Note: RapidAPI console will automatically generate the required parameters, such as API Key and Host information
To execute the request, you need to provide a ‘query’ parameter and the API will return the breakdown of the nutrients for the given text.
For instance, the below request demonstrates the breakdown of the nutrients for ‘one glass of milk’.
Note: In case of any failure, the CalorieNinjas API may return one of the following responses:
- 400 Bad Request – Client sent an invalid request (missing required parameters).
- 401 Unauthorized – Failed to authenticate with the API server.
- 403 Forbidden – The client authenticated but didn’t have permission to access the required resource.
- 404 Not Found – The requested resource (endpoint) doesn’t exist.
- 500 Internal Server Error – A generic error occurred on the API server.
- 503 Service Unavailable – The API service is not available.
If the API couldn’t find the information about the given query, it will return the empty JSON response.
Explanation of the CalorieNinjas API Endpoints
The API provides a single endpoint called ‘Text Nutrition,’ which extracts the list of food and drink from the given text and provides detailed nutrition information.
This endpoint has one required parameter, allowing users to provide food and drink information in any order.
Some of the examples input can be as follows:
- 14oz prime rib and mashed potatoes
- One large BBQ Chicken Pizza
- I had 2.5 pounds of brisket and fries
CalorieNinjas API algorithms use natural language processing and are smart enough to calculate the custom portions size as well.
The below image illustrates the successful response from the API.
How to use CalorieNinjas API with Python
To run the Python application, make sure that you have installed the Python application. You can use any client library to use CalorieNinjas API.
The following code snippet uses http.client to fetch nutrition information for ‘14oz prime rib and mashed potatoes’
import http.client conn = http.client.HTTPSConnection("calorieninjas.p.rapidapi.com") headers = { 'x-rapidapi-key': "ce19d0164fmsh3d383efc0e85ce5p16dcb1jsnb1a4a3c79541", 'x-rapidapi-host': "calorieninjas.p.rapidapi.com" } conn.request("GET", "/v1/nutrition?query=14oz%20prime%20rib%20and%20mashed%20potatoes", headers=headers) res = conn.getresponse() data = res.read() print(data.decode("utf-8"))
The API successfully returned the nutrition data for the above query.
How to use CalorieNinjas API with PHP
Before running the sample code shared below, please make sure that you have installed PHP. You may follow this guide on how to install this correctly.
The below code example also executes the Text Nutrition endpoint to fetch nutrition data in 1 glass of skimmed milk.
<?php $curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://calorieninjas.p.rapidapi.com/v1/nutrition?query=1%20glass%20of%20skimmed%20milk.%20", CURLOPT_RETURNTRANSFER => true, CURLOPT_FOLLOWLOCATION => true, CURLOPT_ENCODING => "", CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "GET", CURLOPT_HTTPHEADER => [ "x-rapidapi-host: calorieninjas.p.rapidapi.com", "x-rapidapi-key: ce19d0164fmsh3d383efc0e85ce5p16dcb1jsnb1a4a3c79541" ], ]); $response = curl_exec($curl); $err = curl_error($curl); curl_close($curl); if ($err) { echo "cURL Error #:" . $err; } else { echo $response;
The above code is executed successfully as shown in the below image.
How to use CalorieNinjas API with Ruby
The below example uses Ruby’s net-http gem to execute the endpoint. It queries the nutrition breakdown for the popular brand ‘KitKat.
Before using this code snippet, please make sure that you have installed Ruby on your system.
require 'uri' require 'net/http' require 'openssl' url = URI("https://calorieninjas.p.rapidapi.com/v1/nutrition?query=2%20Kitkat") http = Net::HTTP.new(url.host, url.port) http.use_ssl = true http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Get.new(url) request["x-rapidapi-key"] = 'ce19d0164fmsh3d383efc0e85ce5p16dcb1jsnb1a4a3c79541' request["x-rapidapi-host"] = 'calorieninjas.p.rapidapi.com' response = http.request(request) puts response.read_body
The endpoint is successfully executed as we can see the nutrition breakdown in the JSON formatted response.
How to use CalorieNinjas API with Javascript
To use the API in JavaScript, you need to first set up the JavaScript environment. You can download text editors such as Atoms, Visual Studio Code, NotePad++, etc.
The following code snippet demonstrates how nutrition information can be fetched using Javascript for any recipe such as “steak and baked potato”.
fetch("https://calorieninjas.p.rapidapi.com/v1/nutrition?query=Steak%20and%20Baked%20Potato", { "method": "GET", "headers": { "x-rapidapi-key": "ce19d0164fmsh3d383efc0e85ce5p16dcb1jsnb1a4a3c79541", "x-rapidapi-host": "calorieninjas.p.rapidapi.com" } }) .then(response => { console.log(response); }) .catch(err => { console.error(err); });
In the below image, we can see that the nutrition breakdown for the given recipe is successfully extracted.
Benefits
Seamless Integration
The CalorieNinjas API offers seamless integration and supports integration with 100+ apps. In addition, it provides access to nutrition information of 100,000+ foods and beverages from all regions of the world, and that too, using a simplified natural language that requires no specialized formatting or syntax.
Built for Enterprises
The API is highly robust as it processes 500K queries per month. It is lightning fast and can process large queries in less than 1.3 seconds, and has a 100% service level (the percentage of successful calls made to the API within the last 30 days), making it trustworthy nutrition technology for enterprises.
Highly Customizable
One of its promising features is its ability to adjust nutrition results to any given portion size. Thus, It allows the users to track certain macronutrients or meet calorie goals efficiently.
Alternatives to CalorieNinjas API
Below are some alternatives to CalorieNinjas API.
- Nutrifai API: This is a freemium API that allows users to track food habits and health. It provides powerful endpoints through which users can upload the picture or voice notes about what they had for lunch.
- Edamame Nutrition Analysis API: This is also a freemium API and uses natural language processing to provide nutrition data about a given query.
- Food Calorie Data Search API: This API allows searching calories by food name. It returns the calorie count and contains a complete breakdown of nutrition information, including vitamins and minerals. This API is completely free and has only 776ms latency.
- Fitness Calculator API: This API provides various endpoints to find daily calory requirements and macronutrients, along with the fitness metrics such as BMI, ideal weight and body fat percentage, etc.
- Recipe Search and Diet API: This is a freemium API that allows searching over 2 million recipes, which can be filtered using calorie and diet preferences. It also provides a detailed nutrition breakdown of each recipe with 25+ nutrients.
Summary
In this article, we have learned how mobile application developers can benefit from CalorieNinjas API to create various applications in the health and fitness domain. We have also discussed in detail the endpoint it offers and how it can be integrated using various code snippets in popular programming languages such as Python, PHP, Ruby, and Javascript.
Leave a Reply