TIL Python Basics Day 38 - Workout Tracking Using Google Sheets

이다연·2021년 1월 25일
0

Udemy Python Course

목록 보기
37/64

Purpose:

Use Nutritionix API to get natural language input to turn it into json format information including consisting exercise, calrories etc. Use Sheety API to track down the information on google sheet.

API: Nutritionix

Document
Used to track calories for exercising.
Geting user's input in natural language and returning type of Excercise, Duration, Calories.

Article about Natural Language Process: Open AI

API: Sheety

Document
Sheety turns your spreadsheet into something called a Restful JSON API. It means you can access your spreadsheets data in a standard way using simple URLs and HTTP requests.

-Parameters have to be lower case.
-if having upper case + space in the parameter:
First Name(sheet) -> firstName(code)

-API transforms your headers into the "lowercase no-space" format and you can access them as such. So trying to access a column with a header "My Header" would work by querying the column "myheader".

Storing secrets in .env at repl

Document

## <repl>

#main.py

import os
token_id = os.getenv("API_ID")

#--------------------------------

#.env file

API_ID="secretid"

Project

final code

import requests
import datetime as dt

APP_ID = "8-"
API_KEY = "a8-"

exercise_endpoint = "https://trackapi.nutritionix.com/v2/natural/exercise"

user_params = {
     "query": input("Tell me which exercise you did: "),
     "gender": "female",
     "weight_kg": 77.0,
     "height_cm": 170.8,
     "age": 36
}

headers = {
    "x-app-id": APP_ID,
    "x-app-key": API_KEY,
    "Content-Type": "application/json"
}

response = requests.post(url=exercise_endpoint, json=user_params, headers=headers)
# print(response.text)
data = response.json()
print(data)

now = dt.datetime.now()

date = now.strftime("%d/%m/%G")
time = now.strftime("%X")
exercise = data['exercises'][0]['name']
duration = data['exercises'][0]['duration_min']
calories = data['exercises'][0]['nf_calories']

sheety_endpoint = "https://api.sheety.co/aa-/workoutTracking/workouts"

sheety_params = {
    "workout": {
        "date": date,
        "time": time,
        "exercise": exercise.title(),
        "duration": duration,
        "calories": calories,
    }
}

headers = {
    "Authorization": "Bearer Thisistokenforsheetyworkoutproject;)",
    "Content-Type": "application/json"
}

sheety_response = requests.post(url=sheety_endpoint, json=sheety_params, headers=headers)
print(sheety_response.text)

#delete the row
# requests.delete(url=f"{sheety_endpoint}/3")

Learning: API docs arent's always very well explained :(

profile
Dayeon Lee | Django & Python Web Developer

0개의 댓글