API Reference

Introduction

The Food Nutrients API allows you to analyze food images and get detailed nutritional information. This reference provides all the details you need to integrate with our API.

Base URL: https://tastyapi.com

Authentication

All API requests require authentication using an API key. Include your API key in the Authorization header as a Bearer token.

Authorization: Bearer YOUR_API_KEY

You can get an API key by subscribing to one of our plans.

Endpoints

The TastyAPI provides the following endpoints:

POST /analyze-image

Analyze a food image and get detailed nutritional information.

Request Parameters

Headers

Authorization String Required

Bearer token for API authentication. Format: Bearer YOUR_API_KEY

Body

image File Required

The food image to analyze. Must be a JPEG or PNG file.

Responses

200 OK

Returns the analysis of the food image with nutritional information.

{
  "analysis": {
    "foodName": "Grilled Chicken Salad with Balsamic Vinaigrette",
    "servingSize": {
      "amount": 250,
      "unit": "g"
    },
    "nutrients": {
      "calories": {
        "amount": 350,
        "unit": "kcal"
      },
      "protein": {
        "amount": 30,
        "unit": "g"
      },
      "carbohydrates": {
        "amount": 15,
        "unit": "g"
      },
      "fat": {
        "amount": 20,
        "unit": "g"
      },
      // Additional nutrients...
    },
    "dietaryInfo": {
      "isVegetarian": false,
      "isVegan": false,
      "isGlutenFree": true,
      // Additional dietary information...
    }
  }
}
400 Bad Request

Invalid input. Returned when the request is malformed or missing required parameters.

{
  "error": "No image file provided"
}
401 Unauthorized

Authentication failed. Returned when the API key is invalid or expired.

{
  "error": "Invalid or expired token",
  "paymentUrl": "https://example.com/checkout"
}
GET /api/usage

Get subscription usage information and statistics.

Request Parameters

Headers

Authorization String Required

Bearer token for API authentication. Format: Bearer YOUR_API_KEY

Responses

200 OK

Returns current subscription usage information.

{
  "status": "active",
  "plan": "Professional",
  "usage": {
    "total": 15000,
    "used": 1247,
    "remaining": 13753,
    "percentUsed": 8.31
  },
  "subscription": {
    "created": "2024-01-15T10:30:00Z",
    "expires": "2024-02-15T10:30:00Z",
    "daysRemaining": 18
  }
}
401 Unauthorized

Authentication failed. Returned when the API key is invalid or expired.

{
  "error": "Invalid or expired token"
}
POST /api/subscription/cancel

Cancel your active subscription. Cancellation will be effective at the end of the current billing period.

Request Parameters

Headers

Authorization String Required

Bearer token for API authentication. Format: Bearer YOUR_API_KEY

Responses

200 OK

Subscription cancellation was successful.

{
  "success": true,
  "message": "Subscription cancelled successfully. Access will continue until the end of your current billing period.",
  "cancellationEffective": "2024-02-15T10:30:00Z"
}
400 Bad Request

Cancellation failed or subscription already cancelled.

{
  "error": "Subscription is already cancelled or does not exist"
}
401 Unauthorized

Authentication failed. Returned when the API key is invalid or expired.

{
  "error": "Invalid or expired token"
}

Response Format

POST /analyze-image

The API returns nutritional information in JSON format. Here's a description of the main fields:

Field Type Description
foodName string The name of the food detected in the image
servingSize object Information about the serving size, including amount and unit
nutrients object Detailed nutritional information, including calories, macronutrients, vitamins, and minerals
dietaryInfo object Information about dietary compatibility (vegetarian, vegan, gluten-free, etc.)
allergens object Information about allergens contained in the food
glycemicInfo object Glycemic index and load information
ingredients array List of detected ingredients in the food
dailyValuePercentages object Percentage of daily recommended values for various nutrients
imageAnalysis object Information about the image quality and confidence of the analysis

GET /api/usage

This endpoint returns subscription usage information. Here's a description of the fields:

Field Type Description
status string Current status of the subscription (active)
plan string The subscription plan type (Basic, Professional, or Annual)
usage.total number Total API calls allowed in the subscription period
usage.used number Number of API calls used so far
usage.remaining number Number of API calls remaining in the subscription period
usage.percentUsed number Percentage of the total usage limit consumed
subscription.created string ISO timestamp of when the subscription was created
subscription.expires string ISO timestamp of when the subscription will expire
subscription.daysRemaining number Number of days remaining in the current subscription period

POST /api/subscription/cancel

This endpoint cancels your subscription. Here's a description of the response fields:

Field Type Description
success boolean Whether the cancellation was successful
message string Human-readable message about the cancellation
cancellationEffective string ISO timestamp of when the cancellation becomes effective

Code Examples

Analyze Image

curl -X POST https://tastyapi.com/analyze-image \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -F "image=@./path/to/food-image.jpg"

Check Usage

curl -X GET https://tastyapi.com/api/usage \
  -H "Authorization: Bearer YOUR_API_KEY"

Cancel Subscription

curl -X POST https://tastyapi.com/api/subscription/cancel \
  -H "Authorization: Bearer YOUR_API_KEY"

JavaScript/Node.js Example

// Browser/Frontend Example
async function analyzeImage(file) {
  const formData = new FormData();
  formData.append('image', file);

  try {
    const response = await fetch('https://tastyapi.com/analyze-image', {
      method: 'POST',
      headers: {
        'Authorization': 'Bearer YOUR_API_KEY'
      },
      body: formData
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const data = await response.json();
    console.log('Analysis result:', data);
    return data;
  } catch (error) {
    console.error('Error analyzing image:', error);
    return { error: error.message };
  }
}

// Node.js Example with FormData
const FormData = require('form-data');
const fs = require('fs');

async function analyzeImageNode(imagePath) {
  const formData = new FormData();
  formData.append('image', fs.createReadStream(imagePath));

  try {
    const response = await fetch('https://tastyapi.com/analyze-image', {
      method: 'POST',
      headers: {
        'Authorization': 'Bearer YOUR_API_KEY',
        ...formData.getHeaders()
      },
      body: formData
    });

    const data = await response.json();
    console.log('Analysis result:', data);
    return data;
  } catch (error) {
    console.error('Error:', error);
    return { error: error.message };
  }
}

// Check Usage
async function checkUsage() {
  try {
    const response = await fetch('https://tastyapi.com/api/usage', {
      headers: { 'Authorization': 'Bearer YOUR_API_KEY' }
    });
    const data = await response.json();
    console.log('Usage data:', data);
    return data;
  } catch (error) {
    console.error('Error checking usage:', error);
  }
}

// Cancel Subscription
async function cancelSubscription() {
  try {
    const response = await fetch('https://tastyapi.com/api/subscription/cancel', {
      method: 'POST',
      headers: { 'Authorization': 'Bearer YOUR_API_KEY' }
    });
    const data = await response.json();
    console.log('Cancellation result:', data);
    return data;
  } catch (error) {
    console.error('Error cancelling subscription:', error);
  }
}

Python Example

import requests

def analyze_image():
    url = "https://tastyapi.com/analyze-image"
    headers = {
        "Authorization": "Bearer YOUR_API_KEY"
    }
    
    try:
        with open("path/to/food-image.jpg", "rb") as image_file:
            files = {
                "image": image_file
            }
            response = requests.post(url, headers=headers, files=files)
        
        try:
            data = response.json()
            print("Analysis result:", data)
            return data
        except Exception as e:
            return {
                "status_code": response.status_code,
                "raw_response": response.text,
                "json_error": str(e)
            }
        
    except FileNotFoundError:
        return {"error": "Image file not found", "status_code": 404}
    except Exception as e:
        return {"error": str(e), "status_code": 500}

# Usage example
result = analyze_image()

# Check Usage
usage_response = requests.get("https://tastyapi.com/api/usage", 
                            headers={"Authorization": "Bearer YOUR_API_KEY"})
usage_data = usage_response.json()
print("Usage data:", usage_data)

# Cancel Subscription
cancel_response = requests.post("https://tastyapi.com/api/subscription/cancel", 
                               headers={"Authorization": "Bearer YOUR_API_KEY"})
cancel_data = cancel_response.json()
print("Cancel result:", cancel_data)

Rate Limits

API calls are limited based on your subscription plan:

Plan Monthly Limit Price
Basic 5,000 requests $29 per month
Professional 15,000 requests $69 per month
Annual 5,000 requests $278 per year