### Fetch MyFitnessPal Report Data (Specific Start Date) - Python Source: https://python-myfitnesspal.readthedocs.io/en/latest/_sources/how_to/reports This Python code snippet shows how to retrieve MyFitnessPal report data starting from a specific date. It utilizes the 'datetime' module to define the start date and the 'myfitnesspal' client's get_report method. The output is an OrderedDict containing date-value pairs from the specified start date onwards. ```python import datetime may = datetime.date(2015, 5, 1) client.get_report("Net Calories", "Nutrition", may) # >> OrderedDict([(datetime.date(2015, 5, 14), 172.8), (datetime.date(2015, 5, 13), 173.1), (datetime.date(2015, 5, 12), 127.7), # (datetime.date(2015, 5, 11), 172.7), (datetime.date(2015, 5, 10), 172.8), (datetime.date(2015, 5, 9), 172.4), # (datetime.date(2015, 5, 8), 172.6), (datetime.date(2015, 5, 7), 172.7), (datetime.date(2015, 5, 6), 172.6), # (datetime.date(2015, 5, 5), 172.9), (datetime.date(2015, 5, 4), 173.0), (datetime.date(2015, 5, 3), 172.6), # (datetime.date(2015, 5, 2), 172.6), (datetime.date(2015, 5, 1), 172.7)]) ``` -------------------------------- ### Get Cardiovascular Exercises using Python Source: https://python-myfitnesspal.readthedocs.io/en/latest/_sources/how_to/exercises Retrieves a list of cardiovascular exercises recorded for a specific day using the myfitnesspal Python library. It demonstrates initializing the client, fetching the day's data, and then accessing the cardiovascular exercises. The output is a list of dictionaries, each containing exercise details and nutrition information. ```python import myfitnesspal client = myfitnesspal.Client() day = client.get_date(2019, 3, 12) day.exercises[0].get_as_list() # >> [{'name': 'Walking, 12.5 mins per km, mod. pace, walking dog', 'nutrition_information': {'minutes': 60, 'calories burned': 209}}, {'name': 'Running (jogging), 8 kph (7.5 min per km)', 'nutrition_information': {'minutes': 25, 'calories burned': 211}}] ``` -------------------------------- ### Get Strength Exercises using Python Source: https://python-myfitnesspal.readthedocs.io/en/latest/_sources/how_to/exercises Retrieves a list of strength exercises recorded for a specific day using the myfitnesspal Python library. This snippet shows how to access the strength exercises, which are typically the second item in the `day.exercises` array. The output is a list of dictionaries, each detailing the exercise and its associated sets, reps, and weight. ```python import myfitnesspal client = myfitnesspal.Client() day = client.get_date(2019, 3, 12) day.exercises[1].get_as_list() # >> [{'name': 'Leg Press', 'nutrition_information': {'sets': 3, 'reps/set': 12, 'weight/set': 20}}, {'name': 'Seated Row, Floor, Machine', 'nutrition_information': {'sets': 3, 'reps/set': 12, 'weight/set': 20}}] ``` -------------------------------- ### Get measurements from past 30 days - Python myfitnesspal Source: https://python-myfitnesspal.readthedocs.io/en/latest/how_to/measurements Retrieves body measurements from the past 30 days using the myfitnesspal Client. Requires authentication via myfitnesspal.Client() and returns an OrderedDict with datetime.date objects as keys and measurement values as floats. Example retrieves weight measurements over a 30-day period. ```python import myfitnesspal client = myfitnesspal.Client() weight = client.get_measurements('Weight') weight ``` -------------------------------- ### Get Food Item Details using MyFitnessPal API (Python) Source: https://python-myfitnesspal.readthedocs.io/en/latest/_sources/how_to/food_search This snippet shows how to retrieve detailed information for a specific food item using its MyFitnessPal ID. It requires the 'myfitnesspal' library and returns an object containing details such as serving sizes and nutritional information like saturated fat. ```python import myfitnesspal client = myfitnesspal.Client() item = client.get_food_item_details("89755756637885") item.servings # > [<1.00 x Sandwich>] item.saturated_fat # > 10.0 ``` -------------------------------- ### Get measurements since specific date - Python myfitnesspal Source: https://python-myfitnesspal.readthedocs.io/en/latest/how_to/measurements Retrieves body measurements from a specified start date onwards using the myfitnesspal Client. Takes a measurement type name and a datetime.date object as parameters. Returns an OrderedDict with dates and corresponding measurement values, useful for tracking changes over custom time periods. ```python import datetime may = datetime.date(2015, 5, 1) body_fat = client.get_measurements('Body Fat', may) body_fat ``` -------------------------------- ### Get Daily and Meal Nutritional Totals with myfitnesspal Source: https://python-myfitnesspal.readthedocs.io/en/latest/how_to/diary Accesses the `totals` property of Day or Meal objects to get a summary of nutritional information like calories, carbohydrates, fat, protein, sodium, and sugar. This provides a quick overview of consumption for the day or a specific meal. ```python day.totals # >> {'calories': 2001, # 'carbohydrates': 369, # 'fat': 22, # 'protein': 110, # 'sodium': 3326, # 'sugar': 103} dinner.totals # >> {'calories': 945, # 'carbohydrates': 170, # 'fat': 11, # 'protein': 53, # 'sodium': 2190, # 'sugar': 17} ``` -------------------------------- ### Get Food Item Details by ID - Python Source: https://python-myfitnesspal.readthedocs.io/en/latest/how_to/food_search This code snippet shows how to retrieve detailed information for a specific food item using its MyFitnessPal ID. It requires the `myfitnesspal` library and a valid `mfp_id`. The input is a food item ID string, and the output provides details like servings and nutritional information (e.g., saturated fat). ```python import myfitnesspal client = myfitnesspal.Client() item = client.get_food_item_details("89755756637885") item.servings item.saturated_fat ``` -------------------------------- ### Get MyFitnessPal Measurements (Python) Source: https://python-myfitnesspal.readthedocs.io/en/latest/_sources/how_to/measurements Retrieves user measurements from MyFitnessPal. This function can fetch data for the past 30 days, since a specific date, or within a date range. It requires the `myfitnesspal` library and returns measurements as an ordered dictionary. ```python import myfitnesspal import datetime client = myfitnesspal.Client() # Get measurements for the past 30 days weight_last_30_days = client.get_measurements('Weight') print(weight_last_30_days) # Get measurements since a specific date may_1_2015 = datetime.date(2015, 5, 1) body_fat_since_may = client.get_measurements('Body Fat', may_1_2015) print(body_fat_since_may) # Get measurements within a date range this_week = datetime.date(2015, 5, 11) last_week = datetime.date(2015, 5, 4) weight_this_week = client.get_measurements('Weight', this_week, last_week) print(weight_this_week) ``` -------------------------------- ### Access Entries within a Meal Source: https://python-myfitnesspal.readthedocs.io/en/latest/_sources/how_to/diary Get a list of food entries within a specific meal using the 'entries' property of a Meal object. Each entry represents a food item consumed during that meal and includes its nutritional breakdown. ```python dinner.entries # >> [, # , # ] ``` -------------------------------- ### Get Report Data Within Date Range using Python MyFitnessPal Source: https://python-myfitnesspal.readthedocs.io/en/latest/how_to/reports Demonstrates retrieving report data within a specific date range by passing two date parameters to client.get_report(). The method returns an OrderedDict containing only the data between the specified dates. The order of date arguments does not matter - the method handles them appropriately. ```python thisweek = datetime.date(2015, 5, 11) lastweek = datetime.date(2015, 5, 4) client.get_report("Net Calories", "Nutrition", thisweek, lastweek) # >> OrderedDict([(datetime.date(2015, 5, 11), 1721.6), (datetime.date(2015, 5, 10), 1722.4), (datetime.date(2015, 5,9), 1720.2), # (datetime.date(2015, 5, 8), 1271.0), (datetime.date(2015, 5, 7), 1721.2), (datetime.date(2015, 5, 6), 1720.8), # (datetime.date(2015, 5, 5), 1721.8), (datetime.date(2015, 5, 4), 1274.2)]) ``` -------------------------------- ### Fetch MyFitnessPal Report Data (Date Range) - Python Source: https://python-myfitnesspal.readthedocs.io/en/latest/_sources/how_to/reports This Python snippet retrieves MyFitnessPal report data within a specified date range. It uses the 'datetime' module to define the start and end dates for the report query. The 'get_report' method accepts these dates, and the function returns an OrderedDict with data points falling within that range. ```python import datetime thisweek = datetime.date(2015, 5, 11) lastweek = datetime.date(2015, 5, 4) client.get_report("Net Calories", "Nutrition", thisweek, lastweek) # >> OrderedDict([(datetime.date(2015, 5, 11), 1721.6), (datetime.date(2015, 5, 10), 1722.4), (datetime.date(2015, 5,9), 1720.2), # (datetime.date(2015, 5, 8), 1271.0), (datetime.date(2015, 5, 7), 1721.2), (datetime.date(2015, 5, 6), 1720.8), # (datetime.date(2015, 5, 5), 1721.8), (datetime.date(2015, 5, 4), 1274.2)]) ``` -------------------------------- ### Get measurements within date range - Python myfitnesspal Source: https://python-myfitnesspal.readthedocs.io/en/latest/how_to/measurements Retrieves body measurements between two specified dates using the myfitnesspal Client. Accepts measurement type and two datetime.date objects representing the date range. Date argument order does not matter. Returns an OrderedDict with measurements for dates falling within the specified range. ```python thisweek = datetime.date(2015, 5, 11) lastweek = datetime.date(2015, 5, 4) weight = client.get_measurements('Weight', thisweek, lastweek) weight ``` -------------------------------- ### Instantiate myfitnesspal Client (v1.x - Obsolete) Source: https://python-myfitnesspal.readthedocs.io/en/latest/_sources/upgrading Demonstrates how to instantiate the `myfitnesspal.Client` object in version 1.x of the library. This version required a username and relied on a system keyring for authentication. It is now considered obsolete. ```python import myfitnesspal client = myfitnesspal.Client('myusername') ``` -------------------------------- ### Search for Foods by Name - Python Source: https://python-myfitnesspal.readthedocs.io/en/latest/how_to/food_search This code snippet demonstrates how to search for food items using the myfitnesspal Python library. It initializes a client, calls the `get_food_search_results` method with a query, and then prints details of the first result. Dependencies include the `myfitnesspal` library. Input is a food name string; output is a list of food item objects. ```python import myfitnesspal client = myfitnesspal.Client() food_items = client.get_food_search_results("bacon cheeseburger") food_items print("{} ({}), {}, cals={}, mfp_id={}".format( food_items[0].name, food_items[0].brand, food_items[0].serving, food_items[0].calories, food_items[0].mfp_id )) ``` -------------------------------- ### Instantiate myfitnesspal Client (v2.x - Current) Source: https://python-myfitnesspal.readthedocs.io/en/latest/_sources/upgrading Shows the current method for instantiating the `myfitnesspal.Client` object in version 2.x. This version simplifies authentication by reading login details directly from the user's web browser, eliminating the need to pass a username during instantiation. ```python import myfitnesspal client = myfitnesspal.Client() ``` -------------------------------- ### Entry Class Constructor Source: https://python-myfitnesspal.readthedocs.io/en/latest/api/entry Creates a new Entry instance to store information about a single entry. The Entry class initializes with a name and nutrition dictionary containing nutritional values. ```APIDOC ## Entry Class Constructor ### Description Initializes an Entry object that stores information about a single entry with its associated nutrition data. ### Class Definition ``` class Entry(name: str, nutrition: Dict[str, float]) ``` ### Parameters #### Constructor Parameters - **name** (str) - Required - Name of the item - **nutrition** (Dict[str, float]) - Required - Dictionary containing nutrition values for the item ### Properties - **name** (str) - Name of the item - **totals** (Dict[str, float]) - Totals for the item - **short_name** (Optional[str]) - Short name of the item - **unit** (Optional[str]) - Unit of measurement - **quantity** (Optional[str]) - Quantity of the item ### Example Usage ```python from myfitnesspal.entry import Entry nutrition_data = { "calories": 150.0, "protein": 20.0, "carbs": 10.0, "fat": 5.0 } entry = Entry( name="Chicken Breast", nutrition=nutrition_data ) ``` ``` -------------------------------- ### MyFitnessPal Client Initialization and Properties Source: https://python-myfitnesspal.readthedocs.io/en/latest/api/client Demonstrates how to initialize the MyFitnessPal Client, optionally with a cookie jar, and access user-specific properties like user ID, metadata, access token, and effective username. The 'unit_aware' parameter controls unit sensitivity. ```python from myfitnesspal import Client from http.cookiejar import CookieJar # Initialize client with optional cookie jar and unit awareness cookie_jar = CookieJar() client = Client(cookie_jar=cookie_jar, unit_aware=True) # Access user properties user_id = client.user_id user_metadata = client.user_metadata access_token = client.access_token effective_username = client.effective_username ``` -------------------------------- ### Meal Class Initialization and Properties - Python Source: https://python-myfitnesspal.readthedocs.io/en/latest/api/meal Demonstrates the initialization of the Meal class and access to its core properties: name, entries, and totals. This class is part of the myfitnesspal library and requires Entry objects for initialization. ```python from typing import List, Dict from .entry import Entry class Meal(_name : str_, _entries : List[Entry]_): """Stores information about a particular meal.""" @property def entries(self) -> List[Entry]: """Entries for this meal.""" # Implementation details omitted for brevity pass @property def name(self) -> str: """Name of this meal.""" # Implementation details omitted for brevity pass @property def totals(self) -> Dict[str, float]: """Nutrition totals for all entries for this meal.""" # Implementation details omitted for brevity pass ``` -------------------------------- ### Search for Foods using MyFitnessPal API (Python) Source: https://python-myfitnesspal.readthedocs.io/en/latest/_sources/how_to/food_search This snippet demonstrates how to search for food items using the myfitnesspal Python client. It requires the 'myfitnesspal' library and returns a list of food items matching the search query, including their name, brand, serving size, calories, and MyFitnessPal ID. ```python import myfitnesspal client = myfitnesspal.Client() food_items = client.get_food_search_results("bacon cheeseburger") food_items # >> [, # , # , # , # , # , # ... print("{} ({}), {}, cals={}, mfp_id={}".format( food_items[0].name, food_items[0].brand, food_items[0].serving, food_items[0].calories, food_items[0].mfp_id )) # > Bacon Cheeseburger (Sodexo Campus), 1 Sandwich, cals = 420.0 ``` -------------------------------- ### Day Class Overview Source: https://python-myfitnesspal.readthedocs.io/en/latest/api/day The Day class stores meal entries for a particular day and provides access to various daily statistics and goals. ```APIDOC ## Class Day ### Description Stores meal entries for a particular day. ### Properties - **date** (date) - The date for which the day's entries are recorded. - **meals** (List[Meal]) - Returns a list of meals. - **entries** (Generator[Entry, None, None]) - Yields all entries from all meals. - **goals** (Dict[str, float]) - Returns goals. - **notes** (str) - Returns notes. - **water** (float) - Returns water intake. - **exercises** (List[Exercise]) - Returns list of exercises. ### Methods - **__getitem__**(value: str) -> Meal Returns a meal matching the provided name. - **keys()** -> List[str] Returns a list of meal names. - **get_as_dict()** -> Dict[str, List[MealEntry]] Returns a mapping of meal names to the list of entries for that meal. ``` -------------------------------- ### Access Individual Strength Exercise Properties using Python Source: https://python-myfitnesspal.readthedocs.io/en/latest/_sources/how_to/exercises Demonstrates accessing specific details of strength exercises obtained via the myfitnesspal API. This includes extracting the exercise name, and within the 'nutrition_information', accessing values for 'sets', 'reps/set', and 'weight/set'. ```python day.exercises[1].get_as_list()[0]['name'] # >> 'Leg Press' day.exercises[1].get_as_list()[0]['nutrition_information']['sets'] # >> 3 day.exercises[1].get_as_list()[0]['nutrition_information']['reps/set'] # >> 12 day.exercises[1].get_as_list()[0]['nutrition_information']['weight/set'] # >> 20 ``` -------------------------------- ### Accessing Exercise Data with Myfitnesspal Library Source: https://python-myfitnesspal.readthedocs.io/en/latest/api/exercise This snippet demonstrates how to interact with the Exercise class in the Python Myfitnesspal library. It shows how to access the exercise name, retrieve a list of exercise entries, and fetch a specific entry by its index. This class is useful for parsing and manipulating exercise data from Myfitnesspal. ```python from myfitnesspal.exercise import Exercise from typing import List # Assuming 'exercise_data' is an instance of the Exercise class # For example: # exercise_data = Exercise(name='Running', entries=[...]) # Accessing the name of the exercise exercise_name = exercise_data.name print(f"Exercise Name: {exercise_name}") # Accessing the list of entries entries_list = exercise_data.entries print(f"Number of entries: {len(entries_list)}") # Accessing a specific entry by index if entries_list: first_entry = exercise_data[0] print(f"First entry details: {first_entry}") # Getting exercises as a list of dictionaries exercises_as_list = exercise_data.get_as_list() print(f"Exercises as list: {exercises_as_list}") ``` -------------------------------- ### Day Object Dictionary-like Access Source: https://python-myfitnesspal.readthedocs.io/en/latest/_sources/how_to/diary Demonstrates accessing meals within a Day object using dictionary-like key access, where keys are meal names. This provides an alternative to index-based access for specific meals. ```python day.keys() # >> ['Breakfast', 'Lunch', 'Dinner', 'Snack'] lunch = day['Lunch'] print lunch # >> [, # ] ``` -------------------------------- ### Access Individual Cardiovascular Exercise Properties Source: https://python-myfitnesspal.readthedocs.io/en/latest/how_to/exercises Shows how to access specific properties of individual cardiovascular exercises retrieved from myfitnesspal. The code demonstrates accessing exercise name and nested nutrition information properties like minutes and calories burned using dictionary key notation. ```python day.exercises[0].get_as_list()[0]['name'] # >> 'Walking, 12.5 mins per km, mod. pace, walking dog' day.exercises[0].get_as_list()[0]['nutrition_information']['minutes'] # >> 60 day.exercises[0].get_as_list()[0]['nutrition_information']['calories burned'] # >> 209 ``` -------------------------------- ### Treat Day, Meal, and Entry Objects as Collections with myfitnesspal Source: https://python-myfitnesspal.readthedocs.io/en/latest/how_to/diary Demonstrates how Day, Meal, and Entry objects in the myfitnesspal library can be treated like Python collections. Day objects behave like dictionaries (allowing access by meal name), Meal objects like lists (allowing access by index), and Entry objects like dictionaries (allowing access by nutritional key). ```python day.keys() # >> ['Breakfast', 'Lunch', 'Dinner', 'Snack'] lunch = day['Lunch'] print lunch # >> [, # ] len(lunch) # >> 2 miser_wat = lunch[0] print miser_wat # >> print miser_wat['calories'] # >> 346 ``` -------------------------------- ### Entry Object Dictionary-like Access Source: https://python-myfitnesspal.readthedocs.io/en/latest/_sources/how_to/diary Illustrates accessing specific nutritional values within an Entry object using dictionary-like key access. This allows direct retrieval of values like 'calories' for a food item. ```python print miser_wat['calories'] # >> 346 ``` -------------------------------- ### Entry Properties Source: https://python-myfitnesspal.readthedocs.io/en/latest/api/entry Provides access to individual properties of an Entry object including name, totals, short name, unit, and quantity. These properties allow retrieval of specific entry attributes. ```APIDOC ## Entry Properties ### Description Properties provide access to individual attributes of an Entry object. ### Available Properties #### name (str) - **Type**: str - **Description**: Name of the item - **Access**: Read-only #### totals (Dict[str, float]) - **Type**: Dict[str, float] - **Description**: Totals for the item containing nutrition values - **Access**: Read-only #### short_name (Optional[str]) - **Type**: Optional[str] - **Description**: Short name or abbreviation of the item - **Access**: Read-only #### unit (Optional[str]) - **Type**: Optional[str] - **Description**: Unit of measurement for the item - **Access**: Read-only #### quantity (Optional[str]) - **Type**: Optional[str] - **Description**: Quantity of the item - **Access**: Read-only ### Usage Examples ```python # Access entry properties item_name = entry.name nutrition_totals = entry.totals short = entry.short_name measurement_unit = entry.unit item_quantity = entry.quantity ``` ``` -------------------------------- ### Retrieve Specific Recipe and Meal Details Source: https://python-myfitnesspal.readthedocs.io/en/latest/api/client Fetches detailed information for a specific recipe using its ID or for a specific meal using its ID and title. The recipe details adhere to the schema.org/Recipe format. ```python from myfitnesspal import Client client = Client() # Get details for recipe with ID 54321 recipe_details = client.get_recipe(recipeid=54321) # Get details for meal with ID 101 and title 'Breakfast' meal_details = client.get_meal(meal_id=101, meal_title='Breakfast') ``` -------------------------------- ### Submit New Food Item Source: https://python-myfitnesspal.readthedocs.io/en/latest/api/client Provides a function to add new food items to the MyFitnessPal database with detailed nutritional information, serving size, and public sharing options. Returns True upon successful submission. ```python from myfitnesspal import Client client = Client() # Submit a new food item success = client.set_new_food( brand='Generic Foods', description='Healthy Snack Bar', calories=150, fat=8.0, carbs=15.0, protein=5.0, fiber=3.0, sugar=7.0, serving_size='1 Bar', servingspercontainer=5.0 ) ``` -------------------------------- ### Entry.get_as_dict() Source: https://python-myfitnesspal.readthedocs.io/en/latest/api/entry Returns the entry's totals and information as a dictionary. This method provides a convenient way to access all entry data in dictionary format for serialization or further processing. ```APIDOC ## get_as_dict() → MealEntry ### Description Returns totals per-item as a dictionary representation of the entry. ### Method GET (retrieves data) ### Signature ```python get_as_dict() → MealEntry ``` ### Parameters None ### Returns - **MealEntry** (Dict) - Dictionary containing the entry's totals and information ### Response Example ```python entry_dict = entry.get_as_dict() # Returns a MealEntry dictionary with all entry information { "name": "Chicken Breast", "totals": { "calories": 150.0, "protein": 20.0, "carbs": 10.0, "fat": 5.0 }, "short_name": "Chicken", "unit": "g", "quantity": "100" } ``` ``` -------------------------------- ### Access Daily Water and Notes Source: https://python-myfitnesspal.readthedocs.io/en/latest/_sources/how_to/diary Retrieve the recorded water intake and any notes entered for a specific day using the 'water' and 'notes' properties of a Day object. ```python day.water # >> 1 day.notes # >> "This is the note I entered for this day" ``` -------------------------------- ### Access Individual Cardiovascular Exercise Properties using Python Source: https://python-myfitnesspal.readthedocs.io/en/latest/_sources/how_to/exercises Demonstrates how to access specific properties of a cardiovascular exercise entry obtained from the myfitnesspal API. After retrieving the exercise list, individual dictionary keys like 'name', 'minutes', and 'calories burned' can be accessed. ```python day.exercises[0].get_as_list()[0]['name'] # >> 'Walking, 12.5 mins per km, mod. pace, walking dog' day.exercises[0].get_as_list()[0]['nutrition_information']['minutes'] # >> 60 day.exercises[0].get_as_list()[0]['nutrition_information']['calories burned'] # >> 209 ``` -------------------------------- ### Access MyFitnessPal Daily Data Source: https://python-myfitnesspal.readthedocs.io/en/latest/_sources/how_to/diary Retrieve and display a specific day's nutritional summary from MyFitnessPal. This requires initializing the client and calling get_date with year, month, and day. The output is a Day object containing aggregated nutritional information. ```python import myfitnesspal client = myfitnesspal.Client() day = client.get_date(2013, 3, 2) day # >> <03/02/13 {'sodium': 3326, 'carbohydrates': 369, 'calories': 2001, 'fat': 22, 'sugar': 103, 'protein': 110}> ``` -------------------------------- ### Unit-Aware Data Retrieval Source: https://python-myfitnesspal.readthedocs.io/en/latest/_sources/how_to/diary Enables unit-aware retrieval of measurement data by initializing the client with `unit_aware=True`. This returns measurements with unit information, such as `Weight(g=76)` or `Energy(Calorie=346)`. ```python client = myfitnesspal.Client(unit_aware=True) day = client.get_date(2013, 3, 2) lunch = day['lunch'] print lunch # >> [ print miser_wat['calories'] # >> Energy(Calorie=346) ``` -------------------------------- ### Access Additional Day Information and Unit Awareness with myfitnesspal Source: https://python-myfitnesspal.readthedocs.io/en/latest/how_to/diary Retrieves additional daily data such as water intake (`day.water`) and notes (`day.notes`). It also demonstrates how to enable unit awareness by initializing the client with `unit_aware=True`, which returns nutritional values as specific unit objects (e.g., Weight(mg=508)). ```python day.water # >> 1 day.notes # >> "This is the note I entered for this day" client = myfitnesspal.Client(unit_aware=True) day = client.get_date(2013, 3, 2) lunch = day['lunch'] print lunch # >> [, miser_wat = lunch[0] print miser_wat['calories'] # >> Energy(Calorie=346) ``` -------------------------------- ### Fetch MyFitnessPal Report Data (Past 30 Days) - Python Source: https://python-myfitnesspal.readthedocs.io/en/latest/_sources/how_to/reports This Python code snippet demonstrates how to fetch report data for the past 30 days using the myfitnesspal client. It requires the 'myfitnesspal' library and initializes a client object. The function get_report is called with report name and category, returning an OrderedDict of dates and values. ```python import myfitnesspal client = myfitnesspal.Client() client.get_report(report_name="Net Calories", report_category="Nutrition") # >> OrderedDict([(datetime.date(2015, 5, 14), 1701.0), (datetime.date(2015, 5, 13), 1732.8), (datetime.date(2015, 5,12), 1721.8), # (datetime.date(2015, 5, 11), 1701.6), (datetime.date(2015, 5, 10), 1272.4), (datetime.date(2015, 5, 9), 1720.2), # (datetime.date(2015, 5, 8), 1071.0), (datetime.date(2015, 5, 7), 1721.2), (datetime.date(2015, 5, 6), 1270.8), # (datetime.date(2015, 5, 5), 1701.8), (datetime.date(2015, 5, 4), 1724.2), (datetime.date(2015, 5, 3), 1722.2), # (datetime.date(2015, 5, 2), 1701.0), (datetime.date(2015, 5, 1), 1721.2), (datetime.date(2015, 4, 30), 1721.6), # (datetime.date(2015, 4, 29), 1072.4), (datetime.date(2015, 4, 28), 1272.2), (datetime.date(2015, 4, 27), 1723.2), # (datetime.date(2015, 4, 26), 1791.8), (datetime.date(2015, 4, 25), 1720.8), (datetime.date(2015, 4, 24), 1721.2), # (datetime.date(2015, 4, 23), 1721.6), (datetime.date(2015, 4, 22), 1723.2), (datetime.date(2015, 4, 21), 1724.2), # (datetime.date(2015, 4, 20), 1273.6), (datetime.date(2015, 4, 19), 1721.8), (datetime.date(2015, 4, 18), 1720.4), # (datetime.date(2015, 4, 17), 1629.8), (datetime.date(2015, 4, 16), 1270.4), (datetime.date(2015, 4, 15), 1270.8), # (datetime.date(2015, 4, 14), 1721.6)]) ``` -------------------------------- ### Search and Retrieve Food Item Details Source: https://python-myfitnesspal.readthedocs.io/en/latest/api/client Enables searching for foods based on a query string, returning a list of 'FoodItem' objects. It also allows fetching detailed information for a specific food item using its MyFitnessPal ID. ```python from myfitnesspal import Client client = Client() # Search for 'Apple' search_results = client.get_food_search_results(query='Apple') # Get details for a food item with MFP ID 12345 food_details = client.get_food_item_details(mfp_id=12345) ``` -------------------------------- ### FoodItemServing Class Definition - Python Source: https://python-myfitnesspal.readthedocs.io/en/latest/api/fooditemserving Defines the FoodItemServing class used to represent a serving of a food item. It initializes with serving ID, nutrition multiplier, value, unit, and index, and provides properties to access these attributes. ```python class FoodItemServing: def __init__(self, _serving_id: str, _nutrition_multiplier: float, _value: float, _unit: str, _index: int): self._serving_id = _serving_id self._nutrition_multiplier = _nutrition_multiplier self._value = _value self._unit = _unit self._index = _index @property def serving_id(self) -> str: """Serving ID""" return self._serving_id @property def nutrition_multiplier(self) -> float: """Nutrition Multiplier""" return self._nutrition_multiplier @property def value(self) -> float: """Value""" return self._value @property def unit(self) -> str: """Unit""" return self._unit @property def index(self) -> int: """Index""" return self._index ``` -------------------------------- ### Meal Object List-like Access Source: https://python-myfitnesspal.readthedocs.io/en/latest/_sources/how_to/diary Shows how Meal objects behave like lists, allowing access to individual food entries by index. This is useful for iterating through or selecting specific items within a meal. ```python len(lunch) # >> 2 miser_wat = lunch[0] print miser_wat # >> ``` -------------------------------- ### Retrieve Saved Recipes and Meals Source: https://python-myfitnesspal.readthedocs.io/en/latest/api/client Fetches lists of all saved recipes and meals. For recipes, it returns a dictionary mapping recipe IDs to titles. For meals, it returns a dictionary mapping meal IDs to meal names. ```python from myfitnesspal import Client client = Client() # Get all saved recipes recipes = client.get_recipes() # Get all saved meals meals = client.get_meals() ``` -------------------------------- ### Note Class Representation in Python Source: https://python-myfitnesspal.readthedocs.io/en/latest/api/note This snippet shows the Python class definition for storing Myfitnesspal note data. It includes properties for the note's type and date, along with a method to return the data as a dictionary. ```python class Note: """Stores information about a note""" def __init__(self, _note_data : NoteDataDict_): # ... initialization logic ... pass _type: Optional[str] # Type _date: Optional[date] # Date def as_dict() -> dict: """Returns data as a dictionary.""" # ... method implementation ... pass ``` -------------------------------- ### Retrieve and Set Measurements Source: https://python-myfitnesspal.readthedocs.io/en/latest/api/client Allows retrieval of historical measurement data (e.g., 'Weight') within a specified date range, and setting new measurement values for today's date. Returns a dictionary of dates to measurement values when retrieving. ```python from datetime import date from myfitnesspal import Client client = Client() # Get weight measurements from the last month measurements = client.get_measurements(measurement='Weight', lower_bound=date(2023, 9, 26), upper_bound=date(2023, 10, 26)) # Set today's weight measurement client.set_measurements(measurement='Weight', value=75.5) ``` -------------------------------- ### Python MyFitnessPal Type Definitions Source: https://python-myfitnesspal.readthedocs.io/en/latest/api/types Defines various data structures for the MyFitnessPal API, such as user profiles, goals, preferences, and authentication tokens. These classes are used to represent the data exchanged with the MyFitnessPal service. ```python from typing import List, Dict, Optional, Any from typing_extensions import Literal class CommandDefinition(): """Represents a command definition in the MyFitnessPal API.""" function: Callable_ # Placeholder for callable type description: str is_alias: bool aliases: List[str] class GoalDisplayDict(): """Represents a goal display configuration.""" id: str display_type: str nutrients: List[str] class UnitPreferenceDict(): """Represents user preferences for units of measurement.""" energy: str weight: str distance: str height: str water: str class DiaryPreferencesDict(): """Represents user preferences for diary settings.""" default_foot_view: str meal_names: List[str] tracked_nutrients: List[str] class UnitValueContainer(): """A container for a value with an associated unit.""" unit: str value: float class GoalPreferencesDict(): """Represents user's goal preferences.""" workouts_per_week: int weekly_workout_duration: int weekly_exercise_energy: UnitValueContainer weight_change_goal: UnitValueContainer weight_goal: UnitValueContainer diary_goal_display: str home_goal_display: str macro_goal_format: str class LocationPreferencesDict(): """Represents user's location-based preferences.""" time_zone: str country_code: str locale: str postal_code: str state: str city: str class AdminFlagDict(): """Contains administrative flags for a user account.""" status: str has_changed_username: bool forgot_password_or_username: bool warnings: int strikes: int revoked_privileges: List class AccountDict(): """Represents user account information.""" created_at: str updated_at: str last_login: str valid_email: bool registration_source: str roles: List[str] admin_flags: AdminFlagDict class SystemDataDict(): """Contains system-related data for a user.""" login_streak: int unseen_notifications: int class UserProfile(): """Represents a user's public profile information.""" type: str starting_weight_date: str starting_weight: UnitValueContainer main_image_url: str main_image_id: Optional[Any] birthdate: str height: UnitValueContainer first_name: Optional[str] last_name: Optional[str] sex: Literal['M', 'F'] activity_factor: str headline: Optional[str] about: Optional[str] why: Optional[str] inspirations: List class UserMetadata(): """Aggregates all metadata related to a user.""" id: str username: str email: str goal_displays: List[GoalDisplayDict] unit_preferences: UnitPreferenceDict diary_preferences: DiaryPreferencesDict goal_preferences: GoalPreferencesDict location_preferences: LocationPreferencesDict account: AccountDict system_data: SystemDataDict step_sources: List profiles: List[UserProfile] class AuthData(): """Contains authentication tokens and related information.""" token_type: str access_token: str expires_in: int refresh_token: str user_id: str class MealEntry(): """Represents an entry within a meal, including nutrition details.""" name: str nutrition_information: Dict[str, float] class NoteDataDict(): """Represents a note entry, typically for food or exercise.""" body: str type: str date: str class FoodItemNutritionDict(): """Details the nutritional breakdown of a food item.""" calcium: float carbohydrates: float cholesterol: float fat: float fiber: float iron: float monounsaturated_fat: float polyunsaturated_fat: float potassium: float protein: float saturated_fat: float sodium: float sugar: float trans_fat: float vitamin_a: float vitamin_c: float class ServingSizeDict(): """Defines a serving size for a food item.""" id: str nutrition_multiplier: float value: float unit: str index: int class FoodItemDetailsResponse(): """Response object containing detailed information about a food item.""" description: str brand_name: Optional[str] verified: bool nutrition: FoodItemNutritionDict calories: float confirmations: int serving_sizes: List[ServingSizeDict] class NutritionInformation(): """Provides a summary of nutritional content, often as strings.""" calories: str carbohydrateContent: str fiberContent: str sugarContent: str sodiumContent: str proteinContent: str fatContent: str saturatedFatContent: str monunsaturatedFatContent: str ``` -------------------------------- ### Accessing Meal Entries - Python Source: https://python-myfitnesspal.readthedocs.io/en/latest/api/meal Shows how to retrieve a specific entry from a Meal object using its index. This method utilizes Python's item access protocol (__getitem__). ```python from typing import List, Dict from .entry import Entry class Meal(_name : str_, _entries : List[Entry]_): """Stores information about a particular meal.""" def __getitem__(self, value : int) -> Entry: """Returns a particular entry for this meal.""" # Implementation details omitted for brevity pass ``` -------------------------------- ### Access MyFitnessPal Meals for a Day Source: https://python-myfitnesspal.readthedocs.io/en/latest/_sources/how_to/diary Access all meals recorded for a specific day using the 'meals' property of a Day object. This returns a list of Meal objects, each potentially containing nutritional information. ```python day.meals # >> [, # , # , # ] ``` -------------------------------- ### Access Specific Food Entry by Index Source: https://python-myfitnesspal.readthedocs.io/en/latest/_sources/how_to/diary Access a particular food entry from a meal's list of entries using its index. This allows retrieving details for a single consumed item. ```python spaghetti = dinner.entries[0] spaghetti.name # >> Montebello - Spaghetti noodles, 6 oz. ``` -------------------------------- ### Access Specific Meal by Index Source: https://python-myfitnesspal.readthedocs.io/en/latest/_sources/how_to/diary Retrieve a specific meal from a day's meals by its index in the 'meals' list. This allows targeted access to the nutritional data of a particular meal, such as dinner. ```python dinner = day.meals[2] dinner # >> ```