Recipe Generation API - Smart-Cart-System/backend-fastapi GitHub Wiki

Overview

The Recipe Generation API allows users to generate personalized recipes based on items purchased in their shopping sessions. The system uses an AI model to create recipes that incorporate ingredients from the user's shopping cart, providing both English and Arabic versions of the recipes.

Authentication

All endpoints require authentication using a valid JWT token in the Authorization header:

Authorization: Bearer <your_token>

Base URL

  • Development: http://127.0.0.1:8000

Endpoints

1. Generate a New Recipe

Generate a recipe using ingredients from a completed shopping session.

URL: POST /recipes/generate/{session_id}

Path Parameters:

  • session_id (integer): The ID of a completed shopping session

Response Format:

{
  "id": 1,
  "session_id": 123,
  "title": "Kharaz Tea Popcorn Snack",
  "title_ar": "وجبة خفيفة من الفشار بشاي خراز",
  "ingredients": [
    "1 kg popcorn kernels",
    "1 kg mixed oil",
    "50g Kharaz Tea leaves"
  ],
  "ingredients_ar": [
    "1 كجم من حبوب الفشار",
    "1 كجم من الزيت المختلط",
    "50 جرام من أوراق شاي خراز"
  ],
  "instructions": [
    "Heat the oil in a large pot over medium heat",
    "Add the popcorn kernels and cover with a lid",
    "Shake occasionally until popping slows down",
    "In a separate pot, steep the Kharaz Tea in hot water",
    "Serve the popcorn with the tea on the side"
  ],
  "instructions_ar": [
    "سخن الزيت في قدر كبير على نار متوسطة",
    "أضف حبوب الفشار وغطها بغطاء",
    "هز القدر من وقت لآخر حتى يتوقف الفرقعة",
    "في وعاء منفصل، انقع شاي خراز في الماء الساخن",
    "قدم الفشار مع الشاي جانباً"
  ],
  "description": "A perfect movie night snack combining freshly popped popcorn with aromatic Kharaz tea.",
  "description_ar": "وجبة خفيفة مثالية لليلة الأفلام تجمع بين الفشار الطازج وشاي خراز العطري.",
  "created_at": "2024-06-04T12:34:56.789Z"
}

Error Responses:

  • 400 Bad Request: If there are no items in the session or recipe generation fails
  • 403 Forbidden: If the user doesn't own the session
  • 404 Not Found: If the session doesn't exist

2. List Recipes for a Session

Retrieve all recipes generated for a particular shopping session.

URL: GET /recipes/session/{session_id}

Path Parameters:

  • session_id (integer): The ID of a shopping session

Response Format:

{
  "recipes": [
    {
      "id": 1,
      "session_id": 123,
      "title": "Kharaz Tea Popcorn Snack",
      "title_ar": "وجبة خفيفة من الفشار بشاي خراز",
      "ingredients": [...],
      "ingredients_ar": [...],
      "instructions": [...],
      "instructions_ar": [...],
      "description": "A perfect movie night snack...",
      "description_ar": "وجبة خفيفة مثالية لليلة الأفلام...",
      "created_at": "2024-06-04T12:34:56.789Z"
    },
    // More recipes if available
  ]
}

Error Responses:

  • 403 Forbidden: If the user doesn't own the session
  • 404 Not Found: If the session doesn't exist

3. Get Recipe Details

Retrieve details for a specific recipe.

URL: GET /recipes/{recipe_id}

Path Parameters:

  • recipe_id (integer): The ID of the recipe to retrieve

Response Format: Same as the Generate Recipe endpoint response

Error Responses:

  • 403 Forbidden: If the user doesn't own the session that contains this recipe
  • 404 Not Found: If the recipe doesn't exist

Usage Examples

When to Use Recipe Generation

The recipe generation feature is designed to be used after a shopping session is completed (after checkout). Ideal integration points include:

  1. On the order confirmation screen
  2. In the order history/details view
  3. As a "Get recipe ideas" button in the completed order details

Implementation Flow

  1. After Checkout:

    // After successful payment/checkout
    async function suggestRecipes(sessionId) {
      try {
        const response = await fetch(`${API_URL}/recipes/generate/${sessionId}`, {
          method: 'POST',
          headers: {
            'Authorization': `Bearer ${userToken}`
          }
        });
        
        if (response.ok) {
          const recipe = await response.json();
          displayRecipe(recipe);
        } else {
          // Handle error
        }
      } catch (error) {
        console.error('Failed to generate recipe:', error);
      }
    }
  2. View Recipe History:

    // In order history or session details page
    async function loadSessionRecipes(sessionId) {
      try {
        const response = await fetch(`${API_URL}/recipes/session/${sessionId}`, {
          headers: {
            'Authorization': `Bearer ${userToken}`
          }
        });
        
        if (response.ok) {
          const { recipes } = await response.json();
          displayRecipeList(recipes);
        }
      } catch (error) {
        console.error('Failed to load recipes:', error);
      }
    }

UI Integration Tips

  1. Language Toggle: Provide a way for users to toggle between English and Arabic versions of the recipe

  2. Recipe Card Display:

    • Show the recipe title, description, and an option to expand for full details
    • Use a clean, step-by-step format for instructions
    • Consider using icons for ingredients
  3. Multiple Recipes: Allow users to generate multiple recipes for the same session by calling the generate endpoint multiple times

  4. Print/Share: Add functionality to print or share recipes via social media or messaging

Error Handling

Handle these common error scenarios:

  1. No items in session:

    • Show a message that recipes require items in the shopping cart
  2. Failed recipe generation:

    • Display a friendly error message
    • Provide a "Try Again" button
  3. Unauthorized access:

    • Redirect to login if the token is expired
    • Show appropriate error if attempting to access another user's recipes

Best Practices

  1. Caching: Cache recipe data once retrieved to reduce API calls

  2. Loading States: Show appropriate loading indicators during generation

  3. Progressive Enhancement: Show simple recipes first, then enhance with images or additional details

  4. Error Recovery: If generation fails, provide clear options to retry or contact support

This API enables a personalized cooking experience for users based on their actual purchases, enhancing the value of your shopping platform.

⚠️ **GitHub.com Fallback** ⚠️