TIL Python Basics Day 37 - Habit Tracking Project: API Post Requests & Headers / strftime()

이다연·2021년 1월 22일
0

Udemy Python Course

목록 보기
36/64
post-thumbnail

API Requests

  • Get: fetch data from API providers requests.get(parameters)
  • Post: give external system some piece of data (into google sheet, tweet etc)
  • Put: update data in the external service
  • Delete: delete

API Post Requests

import requests

#1. setup a new account at Pixela
pixela_endpoint = "https://pixe.la/v1/users"

user_params = {
    "token": "thisisatoken123",
    "username": "pythontested",
    "agreeTermsOfService": "yes",
    "notMinor": "yes"
}

response = requests.post(url=pixela_endpoint, json=user_params)
print(response.text)

API Request post & HTTP Header

  • requests.post(parameters)

  • Header is used for advanced authentication

You can attach your API key to a request in one of three ways:
Via the apiKey querystring parameter.
Via the X-Api-Key HTTP header.
Via the Authorization HTTP header. Bearer optional, do not base 64 encode.

We strongly recommend the either of latter 2 so that your API key isn't visible to others in logs or request sniffing.

graph_endpoint = f"{pixela_endpoint}/{USERNAME}/graphs"



graph_params = {
    "id": "graph",
    "name": "graph_python_studying",
    "unit": "hours",
    "type": "float",
    "color": "sora"
}

headers = {
    "X-USER-TOKEN": TOKEN
}

response = requests.post(url=graph_endpoint, json=graph_params, headers=headers)
print(response.text)

Format the string

strftime(): allows us to pass in str to get format into any format we need

today = datetime.now()
print(today.strftime("%Y%m%d")) #printed: 20210120
print(today.strftime("%Y*%m-%d")) #printed: 2021*01-20


yday = datetime(year=2021, month=1, day=19)
"date": yday.strftime("%Y%m%d") #printed: 20210119






Project: Habit Tracking

Purpose: Use Pixela API to create a pixel graph with header. Put, delete the data using requests and format the time data with strftime()

Final Code

https://pixe.la/v1/users/pydygraph/graphs/graph.html
Pixela

import requests
from datetime import datetime

# setup a new account at Pixela
pixela_endpoint = "https://pixe.la/v1/users"
TOKEN = ""
USERNAME = "pydygraph"
# user_params = {
#     "token": TOKEN,
#     "username": USERNAME,
#     "agreeTermsOfService": "yes",
#     "notMinor": "yes"
# }
#
# response = requests.post(url=pixela_endpoint, json=user_params)
# print(response.text)

# graph_endpoint = f"{pixela_endpoint}/{USERNAME}/graphs"
#
# graph_params = {
#     "id": "graph",
#     "name": "graph_python_studying",
#     "unit": "hours",
#     "type": "float",
#     "color": "sora"
# }
#
# headers = {
#     "X-USER-TOKEN": TOKEN
# }
#
# response = requests.post(url=graph_endpoint, json=graph_params, headers=headers)
# print(response.text)

#adding pixel data by getting an input

today = datetime.now()
yday = datetime(year=2021, month=1, day=19)
thedaybefore = datetime(year=2021, month=1, day=18)
graph_post_endpoint = f"{pixela_endpoint}/{USERNAME}/graphs/graph"

graph_post_params = {
    "date": today.strftime("%Y%m%d"),
    "quantity": input("How many hours did you study today?: ")
}

headers = {
    "X-USER-TOKEN": TOKEN
}

response = requests.post(url=graph_post_endpoint, json=graph_post_params, headers=headers)
print(response.text)

API put Requests

requests.put(parameters)

#/v1/users/<username>/graphs/<graphID>/<yyyyMMdd>
day = datetime(year=2020, month=12, day=1)
update_endpoint = f"{pixela_endpoint}/{USERNAME}/graphs/graph/{day.strftime('%Y%m%d')}"

update_params = {
    "quantity": "1.3"
}

headers = {
    "X-USER-TOKEN": TOKEN
}

response = requests.put(url=update_endpoint, json=update_params, headers=headers)
print(response.text)

API delete Requests

requests.delete(parameters)

day = datetime(year=2020, month=12, day=1)
delete_endpoint = f"{pixela_endpoint}/{USERNAME}/graphs/graph/{day.strftime('%Y%m%d')}"


headers = {
    "X-USER-TOKEN": TOKEN
}

response = requests.delete(url=delete_endpoint, headers=headers)
print(response.text)
profile
Dayeon Lee | Django & Python Web Developer

2개의 댓글

comment-user-thumbnail
2024년 1월 9일

Thank you for sharing this informative article on Python basics and Habit Tracking! Understanding API requests, especially post requests, is crucial in various projects.

The example you provided for API post requests is concise and clear. It's great to see practical demonstrations that help learners apply their knowledge. Additionally, the inclusion of HTTP headers and the use of strftime() for formatting strings add valuable insights to the learning process.

For those interested in further exploring the world of APIs, I would recommend checking out this article on trucking APIs by Cleveroad. It delves into the significance of APIs in the context of trucking, providing a broader perspective on their applications.

Looking forward to more Python basics insights in your future articles!

답글 달기
comment-user-thumbnail
2024년 1월 9일

Thank you for sharing this informative article on Python basics and Habit Tracking! Understanding API requests, especially post requests, is crucial in various projects.

The example you provided for API post requests is concise and clear. It's great to see practical demonstrations that help learners apply their knowledge. Additionally, the inclusion of HTTP headers and the use of strftime() for formatting strings add valuable insights to the learning process.

For those interested in further exploring the world of APIs, I would recommend checking out this article on trucking APIs by Cleveroad. It delves into the significance of APIs in the context of trucking, providing a broader perspective on their applications.

Looking forward to more Python basics insights in your future articles!

답글 달기