Prerequisites
Code Example
This example demonstrates how to use the Food Analysis API to analyze a food image. We’ll show how to do this in both Python and Node.js.
import requests
import base64
# Function to encode the image
def encode_image(image_path):
with open(image_path, "rb") as image_file:
return base64.b64encode(image_file.read()).decode('utf-8')
# API endpoint
url = "http://api.calai.app/v1/scanImage"
# Path to your image file
image_path = "path/to/your/image.jpg"
# Encoding the image
base64_image = encode_image(image_path)
# Preparing the payload
payload = {
"imageData": base64_image
}
# Bearer token
bearer_token = "YOUR_API_KEY"
# Headers
headers = {
"Authorization": f"Bearer {bearer_token}"
}
# Making the API request
response = requests.post(url, json=payload, headers=headers)
# Check if the request was successful
if response.status_code == 200:
result = response.json()
if result["success"]:
# Process the successful response
analysis = result["data"]
print(f"Meal Name: {analysis['name']}")
print(f"Calories: {analysis['calories']}")
print(f"Protein: {analysis['protein']}g")
print(f"Carbs: {analysis['carbs']}g")
print(f"Fats: {analysis['fats']}g")
else:
# Handle API-level error
print(f"API Error: {result['error']}")
else:
# Handle HTTP error
print(f"HTTP Error: {response.status_code}")
Both examples do the following:
- Encode an image file to base64.
- Prepare the payload with the encoded image data.
- Send a POST request to the
/scanImage
endpoint.
- Process the response, handling both successful analyses and potential errors.
Remember to replace "path/to/your/image.jpg"
with the actual path to your image file, and ensure you have the necessary libraries installed (requests
for Python, axios
for Node.js).