Monday, December 5, 2022

Python - Project - Workout Tracking with Google Sheet (Day 38)

This is a 100 Days challenge to learn a new language (Python). 100 Days of Code - The Complete Python Pro Bootcamp 

I will post some notes to motivate myself to finish this challenge.


Goal



Build a program which takes your text input (normal english sentence).
Then use Nutritionix API to turn that text into precise nutrition analysis.
In the end, use Sheety API to insert those analysis to your Google Sheets.




Ex:
import requests
import os
import datetime
from dotenv import load_dotenv

# Load Environmental Variables from .env
load_dotenv()

# Nutritionix
NUTRITIONIX_ENDPOINT = "https://trackapi.nutritionix.com/v2/natural/exercise"
NUTRITIONIX_APP_ID = os.environ.get("NUTRITIONIX_APP_ID")
NUTRITIONIX_API_KEY = os.environ.get("NUTRITIONIX_API_KEY")
GNEDER = 'male'
WEIGHT_KG = 88
HEIGHT_CM = 183
AGE = 18

# Sheety
SHEETY_ENDPOINT = os.environ.get("SHETTY_ENDPOINT")
SHETTY_TOKEN = os.environ.get("SHETTY_TOKEN")


def get_exercise_analysis(query_text):
    # Setup authentication parts in headers
    headers = {
        "x-app-id": NUTRITIONIX_APP_ID,
        "x-app-key": NUTRITIONIX_API_KEY,
    }

    # Prepare Request Payload for API
    payload = {
        "query": query_text,
        'gender': GNEDER,
        'weight_kg': WEIGHT_KG,
        'height_cm': HEIGHT_CM,
        'age': AGE
    }

    # Sends a POST request.
    response = requests.post(NUTRITIONIX_ENDPOINT,json=payload, headers=headers)
    # Raises HTTPError, if one occurred.
    response.raise_for_status()
    # Returns the json-encoded content of a response, if any.
    res = response.json()
    return res['exercises']


def insert_data_to_google_sheet(name: str, duration: float, calories: float):
    # Setup authentication parts in headers
    headers = {
        "Authorization": f"Bearer {SHETTY_TOKEN}",
    }

    # Prepare Request Payload for API
    payload = {
        "workout": {
            "date": datetime.datetime.now().strftime("%d/%m/%Y"),
            "time": datetime.datetime.now().strftime("%X"),
            "exercise": name.title(),
            "duration": duration,
            "calories": calories
        }
    }

    # Sends a POST request.
    response = requests.post(SHEETY_ENDPOINT, json=payload, headers=headers)
    # Raises HTTPError, if one occurred.
    response.raise_for_status()

# Ask users to input
exercise_text = input("Tell me which exercises you did: ")

# Call Nutritionix web API to get the analysis based on the exercise text
exercise_data_list = get_exercise_analysis(exercise_text)

# Loop through all exercise data
for exercise in exercise_data_list:
    # Call Sheety web API to insert rows to our Google Sheet
    insert_data_to_google_sheet(
        exercise['name'],
float(exercise['duration_min']),
float(exercise['nf_calories'])
)


No comments:

Post a Comment