### Complete Usage Example - PyFatSecret Source: https://context7.com/trtg/pyfatsecret/llms.txt A comprehensive example demonstrating saved meal retrieval, food search, and nutrition tracking over the past three months. Requires pandas and matplotlib for data visualization. Ensure API credentials are set. ```python from fatsecret import Fatsecret from datetime import datetime, timedelta import pandas as pd import matplotlib.pyplot as plt # Initialize the client consumer_key = 'your_consumer_key' consumer_secret = 'your_consumer_secret' fs = Fatsecret(consumer_key, consumer_secret) # Display saved meals print("=== Saved Meals ===") saved_meals = fs.saved_meals_get() if saved_meals: for meal in saved_meals: print(f"- {meal['saved_meal_name']}") # Search for foods print("\n=== Food Search ===") results = fs.foods_search("oatmeal") if results.get('foods'): for food in results['foods']['food'][:5]: print(f"- {food['food_name']} (ID: {food['food_id']})") # Get nutrition data for the past 3 months print("\n=== Nutrition Tracking ===") months_data = [] for weeks_ago in [8, 4, 0]: date = datetime.now() - timedelta(weeks=weeks_ago) data = fs.food_entries_get_month(date) if data: months_data.extend(data) if months_data: # Convert to DataFrame dates = [datetime.fromtimestamp(float(i['date_int']) * 60 * 60 * 24) for i in months_data] df = pd.DataFrame({ 'fat': pd.Series([float(i['fat']) for i in months_data], index=dates), 'carb': pd.Series([float(i['carbohydrate']) for i in months_data], index=dates), 'protein': pd.Series([float(i['protein']) for i in months_data], index=dates), 'calories': pd.Series([float(i['calories']) for i in months_data], index=dates) }) # Create visualization fig, axes = plt.subplots(2, 1, figsize=(12, 8)) df[['fat', 'carb', 'protein']].plot(ax=axes[0], style='-o', title='Macronutrients (3 Month Trend)') df[['calories']].plot(ax=axes[1], style='-o', color='red', title='Daily Calories') plt.subplots_adjust(hspace=0.4) plt.savefig('nutrition_report.png') plt.show() # Print summary statistics print(f"Average daily calories: {df['calories'].mean():.0f}") print(f"Average protein: {df['protein'].mean():.1f}g") print(f"Average carbs: {df['carb'].mean():.1f}g") print(f"Average fat: {df['fat'].mean():.1f}g") ``` -------------------------------- ### GET food_entries_get_month Source: https://context7.com/trtg/pyfatsecret/llms.txt Retrieves food diary entries for an entire month, providing daily totals for calories and macronutrients. ```APIDOC ## GET food_entries_get_month ### Description Returns food diary entries for an entire month containing the specified date. Returns a simplified list of daily entries with carbohydrate, fat, protein, and calorie totals. ### Parameters #### Query Parameters - **date** (datetime) - Optional - The date used to determine the month to retrieve. Defaults to current date. ### Response #### Success Response (200) - **date_int** (string) - Date identifier - **calories** (string) - Total calories for the day - **carbohydrate** (string) - Total carbohydrates in grams - **fat** (string) - Total fat in grams - **protein** (string) - Total protein in grams #### Response Example [ {"date_int": "16234", "calories": "1850", "carbohydrate": "180.5", "fat": "65.2", "protein": "120.3"} ] ``` -------------------------------- ### GET exercise_entries_get_month Source: https://context7.com/trtg/pyfatsecret/llms.txt Retrieves exercise diary entries for a specific month. ```APIDOC ## GET exercise_entries_get_month ### Description Returns exercise diary entries for an entire month containing the specified date, including calories burned. ### Parameters #### Query Parameters - **date** (datetime) - Optional - The date used to determine the month to retrieve. Defaults to current date. ### Response #### Success Response (200) - **date_int** (string) - Date identifier - **calories** (string) - Total calories burned #### Response Example [ {"date_int": "16234", "calories": "350"} ] ``` -------------------------------- ### Get Monthly Weight Entries and Plot Trend Source: https://context7.com/trtg/pyfatsecret/llms.txt Retrieves monthly weight entries and plots the weight trend over time using matplotlib. ```python from fatsecret import Fatsecret from datetime import datetime, timedelta import pandas as pd import matplotlib.pyplot as plt fs = Fatsecret(consumer_key, consumer_secret) # Get current month's weight data weights = fs.weights_get_month() # Get historical weight data last_month_weights = fs.weights_get_month(datetime.now() - timedelta(weeks=4)) # Returns list of weight entries: # [ # {'date_int': '16234', 'weight_kg': '75.5', 'weight_comment': 'Morning weigh-in'}, # {'date_int': '16237', 'weight_kg': '75.2'}, # ... # ] # Plot weight trend if weights: dates = [datetime.fromtimestamp(float(w['date_int']) * 60 * 60 * 24) for w in weights] weight_values = [float(w['weight_kg']) for w in weights] plt.figure(figsize=(10, 5)) plt.plot(dates, weight_values, '-o') plt.title('Weight Tracking') plt.xlabel('Date') plt.ylabel('Weight (kg)') plt.grid(True) plt.show() ``` -------------------------------- ### GET weights_get_month Source: https://context7.com/trtg/pyfatsecret/llms.txt Retrieves weight tracking entries for a specific month. ```APIDOC ## GET weights_get_month ### Description Returns weight entries for an entire month containing the specified date. ### Parameters #### Query Parameters - **date** (datetime) - Optional - The date used to determine the month to retrieve. Defaults to current date. ### Response #### Success Response (200) - **date_int** (string) - Date identifier - **weight_kg** (string) - Weight in kilograms - **weight_comment** (string) - Optional comment associated with the entry #### Response Example [ {"date_int": "16234", "weight_kg": "75.5", "weight_comment": "Morning weigh-in"} ] ``` -------------------------------- ### Get Monthly Exercise Entries and Analyze Net Calories Source: https://context7.com/trtg/pyfatsecret/llms.txt Retrieves monthly exercise entries and combines them with food diary data to calculate and display net calories (consumed - burned). ```python from fatsecret import Fatsecret from datetime import datetime, timedelta import pandas as pd import matplotlib.pyplot as plt fs = Fatsecret(consumer_key, consumer_secret) # Get current month's exercise data exercise = fs.exercise_entries_get_month() # Get previous month's exercise data last_month_exercise = fs.exercise_entries_get_month(datetime.now() - timedelta(weeks=4)) # Returns list of exercise entries: # [ # {'date_int': '16234', 'calories': '350'}, # {'date_int': '16236', 'calories': '520'}, # ... # ] # Combine with food data for net calorie analysis if exercise and fs.food_entries_get_month(): food_entries = fs.food_entries_get_month() # Create lookup of calories burned by date burned = {e['date_int']: float(e['calories']) for e in exercise} # Calculate net calories (consumed - burned) net_calories = [] for entry in food_entries: consumed = float(entry['calories']) burned_today = burned.get(entry['date_int'], 0) net_calories.append({ 'date': entry['date_int'], 'consumed': consumed, 'burned': burned_today, 'net': consumed - burned_today }) print("Net Calories Analysis:") for day in net_calories: print(f"Date {day['date']}: Consumed {day['consumed']}, Burned {day['burned']}, Net {day['net']}") ``` -------------------------------- ### Get Monthly Food Entries and Plot Trends Source: https://context7.com/trtg/pyfatsecret/llms.txt Retrieves monthly food diary entries and visualizes macronutrient and calorie trends using pandas and matplotlib. ```python from fatsecret import Fatsecret from datetime import datetime, timedelta import pandas as pd import matplotlib.pyplot as plt fs = Fatsecret(consumer_key, consumer_secret) # Get current month's food entries this_month = fs.food_entries_get_month() # Get entries from previous months last_month = fs.food_entries_get_month(datetime.now() - timedelta(weeks=4)) two_months_ago = fs.food_entries_get_month(datetime.now() - timedelta(weeks=8)) # Returns list of daily entries: # [ # {'date_int': '16234', 'calories': '1850', 'carbohydrate': '180.5', # 'fat': '65.2', 'protein': '120.3'}, # {'date_int': '16235', 'calories': '2100', 'carbohydrate': '200.1', # 'fat': '70.8', 'protein': '135.6'}, # ... # ] # Convert to pandas DataFrame for analysis if this_month: dates = [datetime.fromtimestamp(float(i['date_int']) * 60 * 60 * 24) for i in this_month] df = pd.DataFrame({ 'fat': pd.Series([float(i['fat']) for i in this_month], index=dates), 'carb': pd.Series([float(i['carbohydrate']) for i in this_month], index=dates), 'protein': pd.Series([float(i['protein']) for i in this_month], index=dates) }) calories = pd.DataFrame({ 'calories': pd.Series([float(i['calories']) for i in this_month], index=dates) }) # Plot macros and calories fig, axes = plt.subplots(2, 1) df.plot(ax=axes[0], style='-o', sharex=True, title='Macronutrients') calories.plot(ax=axes[1], style='-o', sharex=True, title='Calories') plt.subplots_adjust(hspace=0.8) plt.show() ``` -------------------------------- ### Get Saved Meals - PyFatSecret Source: https://context7.com/trtg/pyfatsecret/llms.txt Retrieves a list of the user's saved meals. Ensure the Fatsecret client is initialized with valid consumer key and secret. ```python from fatsecret import Fatsecret fs = Fatsecret(consumer_key, consumer_secret) saved_meals = fs.saved_meals_get() # Returns list of saved meals: # [ # { # 'saved_meal_id': '1111111', # 'saved_meal_name': 'Power Snack', # 'saved_meal_description': 'A high impact energy meal - terrific for the great outdoors!', # 'meals': 'Lunch,Other' # }, # { # 'saved_meal_id': '2222222', # 'saved_meal_name': 'Quick Breakfast', # 'saved_meal_description': 'Easy morning meal', # 'meals': 'Breakfast' # } # ] if saved_meals: for meal in saved_meals: print(f"Meal: {meal['saved_meal_name']}") print(f" Description: {meal.get('saved_meal_description', 'N/A')}") print(f" Categories: {meal.get('meals', 'N/A')}") print(f" ID: {meal['saved_meal_id']}") print() ``` -------------------------------- ### GET /saved_meals_get Source: https://context7.com/trtg/pyfatsecret/llms.txt Retrieves a list of the user's saved meals, including names, descriptions, categories, and unique identifiers. ```APIDOC ## GET /saved_meals_get ### Description Returns a list of the user's saved meals. Each saved meal contains a name, description, meal categories, and unique ID. ### Method GET ### Endpoint saved_meals_get() ### Response #### Success Response (200) - **saved_meal_id** (string) - Unique identifier for the saved meal - **saved_meal_name** (string) - Name of the saved meal - **saved_meal_description** (string) - Description of the saved meal - **meals** (string) - Comma-separated list of meal categories #### Response Example [ { "saved_meal_id": "1111111", "saved_meal_name": "Power Snack", "saved_meal_description": "A high impact energy meal - terrific for the great outdoors!", "meals": "Lunch,Other" } ] ``` -------------------------------- ### Get User's Favorite Foods Source: https://context7.com/trtg/pyfatsecret/llms.txt Retrieves a list of the user's favorite foods from the FatSecret API. Returns `None` if no favorites have been set. ```python from fatsecret import Fatsecret fs = Fatsecret(consumer_key, consumer_secret) favorites = fs.foods_get_favorites() if favorites: for food in favorites: print(f"Food: {food['food_name']} (ID: {food['food_id']})") # Output: # Food: Greek Yogurt (ID: 123456) # Food: Almonds (ID: 789012) ``` -------------------------------- ### Get User's Recently Eaten Foods Source: https://context7.com/trtg/pyfatsecret/llms.txt Retrieves a list of foods the user has recently consumed. The list can be filtered by meal type, such as 'breakfast', 'lunch', 'dinner', or 'other'. ```python from fatsecret import Fatsecret fs = Fatsecret(consumer_key, consumer_secret) # Get all recently eaten foods recent = fs.foods_get_recently_eaten() ``` -------------------------------- ### Get Food Details by ID Source: https://context7.com/trtg/pyfatsecret/llms.txt Retrieves detailed nutrition information and the FatSecret URL for a specific food item using its `food_id`. Returns `None` if the `food_id` is `None`. The `food_id` can be obtained from `foods_search()` results. ```python from fatsecret import Fatsecret fs = Fatsecret(consumer_key, consumer_secret) # Get detailed nutrition info for a specific food food_id = '33691' # Example food ID obtained from foods_search() food_info = fs.food_get(food_id) print(food_info) # Returns: { # 'food': { # 'food_id': '33691', # 'food_name': 'Chicken Breast', # 'food_type': 'Generic', # 'food_url': 'http://www.fatsecret.com/calories-nutrition/ப்புகளை', # 'servings': { # 'serving': [{ # 'calories': '165', # 'carbohydrate': '0', # 'fat': '3.57', # 'protein': '31.02', # 'serving_description': '100 g', # ... # }] # } # } # } ``` -------------------------------- ### Get User's Most Eaten Foods Source: https://context7.com/trtg/pyfatsecret/llms.txt Returns a list of the user's most frequently eaten foods. This list can be optionally filtered by meal type (e.g., 'breakfast', 'lunch', 'dinner', 'other'). ```python from fatsecret import Fatsecret fs = Fatsecret(consumer_key, consumer_secret) # Get all most eaten foods most_eaten = fs.foods_get_most_eaten() # Filter by meal type: 'breakfast', 'lunch', 'dinner', or 'other' breakfast_favorites = fs.foods_get_most_eaten(meal='breakfast') lunch_favorites = fs.foods_get_most_eaten(meal='lunch') if most_eaten: for food in most_eaten: print(f"{food['food_name']}: eaten {food.get('times_eaten', 'N/A')} times") ``` -------------------------------- ### Initialize Fatsecret Client Source: https://context7.com/trtg/pyfatsecret/llms.txt Initializes the FatSecret API client. On the first run, it prompts for OAuth authorization via a browser and PIN. Subsequent runs use cached tokens from a specified file or 'tokens.dat' by default. Debug output can be enabled with `verbose=1`. ```python from fatsecret import Fatsecret # Initialize with your API credentials from http://platform.fatsecret.com/api/ consumer_key = 'your_consumer_key' consumer_secret = 'your_consumer_secret' # Basic initialization (tokens cached in 'tokens.dat') fs = Fatsecret(consumer_key, consumer_secret) # With custom options fs = Fatsecret( consumer_key, consumer_secret, verbose=1, # Enable debug output cache_name='my_tokens.dat' # Custom cache file name ) # First run output: # Visit this URL in your browser then login: http://www.fatsecret.com/oauth/authorize?oauth_token=xxx # Enter PIN from browser: [user enters PIN] # fatsecret_pin is xxx ``` -------------------------------- ### Initialization Source: https://context7.com/trtg/pyfatsecret/llms.txt Initializes the FatSecret API client with OAuth authentication. Handles token caching for persistent sessions. ```APIDOC ## Initialization ### Fatsecret Class Constructor Creates a new FatSecret API client with OAuth authentication. On first run, the client will prompt the user to authorize via browser and enter a PIN. Subsequent runs use cached tokens stored in a shelve database file. ```python from fatsecret import Fatsecret # Initialize with your API credentials from http://platform.fatsecret.com/api/ consumer_key = 'your_consumer_key' consumer_secret = 'your_consumer_secret' # Basic initialization (tokens cached in 'tokens.dat') fs = Fatsecret(consumer_key, consumer_secret) # With custom options fs = Fatsecret( consumer_key, consumer_secret, verbose=1, # Enable debug output cache_name='my_tokens.dat' # Custom cache file name ) # First run output: # Visit this URL in your browser then login: http://www.fatsecret.com/oauth/authorize?oauth_token=xxx # Enter PIN from browser: [user enters PIN] # fatsecret_pin is xxx ``` ``` -------------------------------- ### Food Methods Source: https://context7.com/trtg/pyfatsecret/llms.txt Provides methods for searching and retrieving detailed information about food items from the FatSecret database. ```APIDOC ## Food Methods ### food_get(food_id) Returns detailed nutrition information and the FatSecret URL for a specific food item. The food_id can be obtained from foods_search() results. Returns None if food_id is None. ```python from fatsecret import Fatsecret fs = Fatsecret(consumer_key, consumer_secret) # Get detailed nutrition info for a specific food food_id = '33691' # Example food ID obtained from foods_search() food_info = fs.food_get(food_id) print(food_info) # Returns: { # 'food': { # 'food_id': '33691', # 'food_name': 'Chicken Breast', # 'food_type': 'Generic', # 'food_url': 'http://www.fatsecret.com/calories-nutrition/ப்புகளை', # 'servings': { # 'serving': [{ # 'calories': '165', # 'carbohydrate': '0', # 'fat': '3.57', # 'protein': '31.02', # 'serving_description': '100 g', # ... # }] # } # } # } ``` ### foods_search(search_expression, page_number=None, max_results=None) Searches the FatSecret food database for foods matching the search expression. Supports pagination for large result sets. ```python from fatsecret import Fatsecret fs = Fatsecret(consumer_key, consumer_secret) # Basic search results = fs.foods_search("chicken breast") print(results) # Returns: { # 'foods': { # 'food': [ # {'food_id': '33691', 'food_name': 'Chicken Breast', ...}, # {'food_id': '4849', 'food_name': 'Grilled Chicken Breast', ...}, # ... # ], # 'max_results': '20', # 'page_number': '0', # 'total_results': '1234' # } # } # Search with pagination results = fs.foods_search("Betty", page_number=0, max_results=10) # Extract food IDs for further queries food_ids = [item['food_id'] for item in results['foods']['food']] ``` ### foods_get_favorites() Returns a list of the user's favorite foods. Returns None if no favorites are set. ```python from fatsecret import Fatsecret fs = Fatsecret(consumer_key, consumer_secret) favorites = fs.foods_get_favorites() if favorites: for food in favorites: print(f"Food: {food['food_name']} (ID: {food['food_id']})") # Output: # Food: Greek Yogurt (ID: 123456) # Food: Almonds (ID: 789012) ``` ### foods_get_most_eaten(meal=None) Returns a list of the user's most frequently eaten foods, optionally filtered by meal type. ```python from fatsecret import Fatsecret fs = Fatsecret(consumer_key, consumer_secret) # Get all most eaten foods most_eaten = fs.foods_get_most_eaten() # Filter by meal type: 'breakfast', 'lunch', 'dinner', or 'other' breakfast_favorites = fs.foods_get_most_eaten(meal='breakfast') lunch_favorites = fs.foods_get_most_eaten(meal='lunch') if most_eaten: for food in most_eaten: print(f"{food['food_name']}: eaten {food.get('times_eaten', 'N/A')} times") ``` ### foods_get_recently_eaten(meal=None) Returns a list of the user's recently eaten foods, optionally filtered by meal type. ```python from fatsecret import Fatsecret fs = Fatsecret(consumer_key, consumer_secret) # Get all recently eaten foods recent = fs.foods_get_recently_eaten() ``` ``` -------------------------------- ### Search Foods Database Source: https://context7.com/trtg/pyfatsecret/llms.txt Searches the FatSecret food database for foods matching a given expression. Supports pagination with `page_number` and `max_results`. The results contain a list of food items, total results, and current page number. ```python from fatsecret import Fatsecret fs = Fatsecret(consumer_key, consumer_secret) # Basic search results = fs.foods_search("chicken breast") print(results) # Returns: { # 'foods': { # 'food': [ # {'food_id': '33691', 'food_name': 'Chicken Breast', ...}, # {'food_id': '4849', 'food_name': 'Grilled Chicken Breast', ...}, # ... # ], # 'max_results': '20', # 'page_number': '0', # 'total_results': '1234' # } # } # Search with pagination results = fs.foods_search("Betty", page_number=0, max_results=10) # Extract food IDs for further queries food_ids = [item['food_id'] for item in results['foods']['food']] ``` -------------------------------- ### Filter Recently Eaten Foods by Meal Source: https://context7.com/trtg/pyfatsecret/llms.txt Fetches recently eaten foods, allowing filtering by specific meals like 'dinner' or 'other'. ```python recent_dinner = fs.foods_get_recently_eaten(meal='dinner') recent_other = fs.foods_get_recently_eaten(meal='other') if recent: for food in recent: print(f"Recently ate: {food['food_name']}") ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.