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'])
)


Friday, December 2, 2022

Python - API Requests and Headers (Day 37)

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



Using Pixela to practice all HTTP Methods and headers for authentication.


Ex: Create an account (POST request)
import requests
import os
from dotenv import load_dotenv

# Load Environmental Variables from .env
load_dotenv()

PIXELA_ENDPOINT = "https://pixe.la/v1/"
USERNAME = os.environ.get("USERNAME")
TOKEN = os.environ.get("TOKEN")

# Prepare Request Payload for API
payload = {
    "username": USERNAME,
    "token": TOKEN,
    "agreeTermsOfService": "yes",
    "notMinor": "yes"
}

# Sends a POST request.
response = requests.post(f"{PIXELA_ENDPOINT}users", json=payload)
# Raises HTTPError, if one occurred.
response.raise_for_status()
# Print the Content of Response
print(response.text)


Ex: Create a graph (POST request)
import requests
import os
from dotenv import load_dotenv

# Load Environmental Variables from .env
load_dotenv()

PIXELA_ENDPOINT = "https://pixe.la/v1/"
USERNAME = os.environ.get("USERNAME")
TOKEN = os.environ.get("TOKEN")
GRAPH_ID = os.environ.get("GRAPH_ID")
GRAPH_NAME = os.environ.get("GRAPH_NAME")

# Prepare headers for API
headers = {
    "X-USER-TOKEN": TOKEN
}

# Prepare Request Payload for API
payload = {
    "id": GRAPH_ID,
    "name": GRAPH_NAME,
    "unit": "kilogram",
    "type": "float",
    "color": "ajisai",
}

# Sends a POST request.
response = requests.post(f"{PIXELA_ENDPOINT}users/{USERNAME}/graphs",
json=payload, headers=headers)
# Raises HTTPError, if one occurred.
response.raise_for_status()
# Print the Content of Response
print(response.text)


Ex: Get the graph (GET request)
import requests
import os
from dotenv import load_dotenv

# Load Environmental Variables from .env
load_dotenv()

PIXELA_ENDPOINT = "https://pixe.la/v1/"
USERNAME = os.environ.get("USERNAME")
GRAPH_ID = os.environ.get("GRAPH_ID")

# Sends a GET request.
response = requests.get(f"{PIXELA_ENDPOINT}users/{USERNAME}/graphs/{GRAPH_ID}")
# Raises HTTPError, if one occurred.
response.raise_for_status()
# Print the Content of Response
print(response.text)

# https://pixe.la/v1/users/frank-exp/graphs/graph-exp.html


Ex: Add a pixel to the graph (POST request)
import requests
import os
import datetime
from dotenv import load_dotenv

# Load Environmental Variables from .env
load_dotenv()

PIXELA_ENDPOINT = "https://pixe.la/v1/"
USERNAME = os.environ.get("USERNAME")
TOKEN = os.environ.get("TOKEN")
GRAPH_ID = os.environ.get("GRAPH_ID")

# Prepare headers for API
headers = {
    "X-USER-TOKEN": TOKEN
}

# Prepare Request Payload for API
payload = {
    "date":  datetime.datetime.now().strftime("%Y%m%d"),
    "quantity": "71.5"
}

# Sends a POST request.
response = requests.post(
    f"{PIXELA_ENDPOINT}users/{USERNAME}/graphs/{GRAPH_ID}",
json=payload, headers=headers)
# Raises HTTPError, if one occurred.
response.raise_for_status()
# Print the Content of Response
print(response.text)


Ex: Update the existing pixel of the graph (PUT request)
import requests
import os
import datetime
from dotenv import load_dotenv

# Load Environmental Variables from .env
load_dotenv()

PIXELA_ENDPOINT = "https://pixe.la/v1/"
USERNAME = os.environ.get("USERNAME")
TOKEN = os.environ.get("TOKEN")
GRAPH_ID = os.environ.get("GRAPH_ID")

# Prepare headers for API
headers = {
    "X-USER-TOKEN": TOKEN
}

# Prepare Request Payload for API
payload = {
    "quantity": "100.0"
}

now_in_pixela_format = datetime.datetime.now().strftime("%Y%m%d")

# Sends a PUT request.
response = requests.put(
    f"{PIXELA_ENDPOINT}users/{USERNAME}/graphs/{GRAPH_ID}/{now_in_pixela_format}",
json=payload, headers=headers)
# Raises HTTPError, if one occurred.
response.raise_for_status()
# Print the Content of Response
print(response.text)


Ex: Delete the existing pixel of the graph (DELETE request)
import requests
import os
import datetime
from dotenv import load_dotenv

# Load Environmental Variables from .env
load_dotenv()

PIXELA_ENDPOINT = "https://pixe.la/v1/"
USERNAME = os.environ.get("USERNAME")
TOKEN = os.environ.get("TOKEN")
GRAPH_ID = os.environ.get("GRAPH_ID")

# Prepare headers for API
headers = {
    "X-USER-TOKEN": TOKEN
}

now_in_pixela_format = datetime.datetime.now().strftime("%Y%m%d")

# Sends a DELETE request.
response = requests.delete(
    f"{PIXELA_ENDPOINT}users/{USERNAME}/graphs/{GRAPH_ID}/20221202",
headers=headers)
# Raises HTTPError, if one occurred.
response.raise_for_status()
# Print the Content of Response
print(response.text)