API Reference

The AI Ingredient Scanner provides a FastAPI REST backend for mobile app integration. This reference documents all available endpoints, request/response schemas, and usage examples.

Base URL
http://your-server-ip:8000

Health Endpoints

GET /

Basic health check endpoint.

Response 200
{
  "status": "ok",
  "message": "AI Ingredient Safety Analyzer API"
}

GET /health

Service health status for monitoring.

Response 200
{
  "status": "healthy"
}

POST /ocr

Extract ingredients from an image using Gemini Vision API. Supports multi-language labels with automatic translation to English.

Request Body

{
  "image": "<base64_encoded_image>"
}

Response

Success Response
{
  "success": true,
  "text": "Water, Glycerin, Sodium Lauryl Sulfate, Fragrance, Citric Acid",
  "error": null
}
Error Response
{
  "success": false,
  "text": "",
  "error": "Failed to process image"
}

Supported Languages

LanguageDetection Headers
EnglishIngredients:, INGREDIENTS:
FrenchIngrédients:, COMPOSITION:
SpanishIngredientes:
GermanInhaltsstoffe:, Zutaten:
ItalianIngredienti:
Korean성분:, 전성분:
Japanese成分:, 全成分:
Chinese成分:, 配料:
PortugueseIngredientes:

POST /analyze

Analyze ingredients for safety with personalized recommendations based on user profile.

Request Body

{
  "product_name": "CeraVe Moisturizer",
  "ingredients": "Water, Glycerin, Cetearyl Alcohol, Phenoxyethanol, Fragrance",
  "allergies": ["Fragrance", "Parabens"],
  "skin_type": "sensitive",
  "expertise": "beginner"
}

Parameters

FieldTypeRequiredDescription
product_namestringNoProduct name (default: "Unknown Product")
ingredientsstringYesComma-separated ingredient list
allergiesstring[]NoUser's known allergies
skin_typestringNoUser's skin type
expertisestringNoExplanation style
Skin Types
normaldryoilycombinationsensitive
Expertise Levels
beginnerexpert

Response

Success Response
{
  "success": true,
  "product_name": "CeraVe Moisturizer",
  "overall_risk": "low",
  "average_safety_score": 8,
  "summary": "This product is generally safe for sensitive skin...",
  "allergen_warnings": [
    "ALLERGEN WARNING: Fragrance - matches your declared sensitivity"
  ],
  "ingredients": [
    {
      "name": "Water",
      "purpose": "Solvent, hydration",
      "safety_score": 10,
      "risk_level": "low",
      "concerns": "No specific concerns",
      "recommendation": "SAFE",
      "origin": "Natural",
      "category": "Both",
      "allergy_risk": "low",
      "is_allergen_match": false,
      "alternatives": []
    },
    {
      "name": "Fragrance",
      "purpose": "Scent, masking agent",
      "safety_score": 4,
      "risk_level": "medium",
      "concerns": "Common allergen, may cause sensitivity",
      "recommendation": "CAUTION",
      "origin": "Synthetic",
      "category": "Cosmetics",
      "allergy_risk": "high",
      "is_allergen_match": true,
      "alternatives": ["fragrance-free alternatives", "natural essential oils"]
    }
  ],
  "execution_time": 12.5,
  "error": null
}

Data Types

IngredientDetail

interface IngredientDetail {
  name: string;
  purpose: string;
  safety_score: number;      // 1-10
  risk_level: RiskLevel;     // "low" | "medium" | "high"
  concerns: string;
  recommendation: string;    // "SAFE" | "CAUTION" | "AVOID"
  origin: string;            // "Natural" | "Synthetic" | "Semi-synthetic"
  category: string;          // "Food" | "Cosmetics" | "Both"
  allergy_risk: string;      // "high" | "low"
  is_allergen_match: boolean;
  alternatives: string[];
}

AnalysisResponse

interface AnalysisResponse {
  success: boolean;
  product_name: string;
  overall_risk: string;
  average_safety_score: number;
  summary: string;
  allergen_warnings: string[];
  ingredients: IngredientDetail[];
  execution_time: number;
  error?: string;
}

Error Handling

HTTP Status Codes

CodeDescription
200Success
400Bad Request (invalid input)
500Internal Server Error

Error Response Format

{
  "success": false,
  "error": "Error description",
  "product_name": "Unknown Product",
  "overall_risk": "unknown",
  "average_safety_score": 0,
  "summary": "",
  "allergen_warnings": [],
  "ingredients": [],
  "execution_time": 0
}

CORS Configuration

The API allows all origins for development:

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)
Production Warning

For production deployments, restrict allow_origins to your specific domains.


Usage Examples

cURL

# Health Check
curl http://localhost:8000/health

# OCR
curl -X POST http://localhost:8000/ocr \
  -H "Content-Type: application/json" \
  -d '{"image": "base64_encoded_image_data"}'

# Analysis
curl -X POST http://localhost:8000/analyze \
  -H "Content-Type: application/json" \
  -d '{
    "product_name": "Test Product",
    "ingredients": "Water, Glycerin, Fragrance",
    "allergies": ["Fragrance"],
    "skin_type": "sensitive",
    "expertise": "beginner"
  }'

TypeScript

import axios from 'axios';

const API_URL = 'http://192.168.1.100:8000';

// Analyze ingredients
const response = await axios.post(`${API_URL}/analyze`, {
  product_name: 'My Product',
  ingredients: 'Water, Glycerin, Citric Acid',
  allergies: ['Fragrance'],
  skin_type: 'sensitive',
  expertise: 'beginner'
});

console.log(response.data.ingredients);

Python

import requests

API_URL = 'http://localhost:8000'

# Analyze ingredients
response = requests.post(f'{API_URL}/analyze', json={
    'product_name': 'My Product',
    'ingredients': 'Water, Glycerin, Citric Acid',
    'allergies': ['Fragrance'],
    'skin_type': 'sensitive',
    'expertise': 'beginner'
})

data = response.json()
print(f"Overall risk: {data['overall_risk']}")

Running the API

Development
uvicorn api:app --host 0.0.0.0 \
  --port 8000 --reload
Production
uvicorn api:app --host 0.0.0.0 \
  --port 8000 --workers 4

Related Documentation