learning from 100 Days of Code: The Complete Python Pro Bootcamp for 2022
Requests Document - HTTP for Humans
What's API and How to get it?
An Application Programming Interface(API)
is a set of commands, functions, protocols, and objects that programmers can use to create software or interact with an external system.
- fing API Endpoint & parameters if need
ex.api.coinbase.com
make request
ex. parameters = { "lat": MY_LAT, "lng": MY_LONG, "formatted": 0, } response = requests.get("https://api.sunrise-sunset.org/json", params=parameters)
- get response code
ex. response.raise_for_status() > HTTP situations: 1XX: Hold on 2XX: Here you go 3XX: Go away 4XX: You screwed up 5XX: I screwed up
Kanye_quote
def get_quote():
response = requests.get(url="https://api.kanye.rest")
response.raise_for_status()
kanye_quote = response.json()["quote"]
if len(kanye_quote.split(" ")) > 18:
canvas.itemconfig(quote_text, text=kanye_quote, font=("Arial", 20, "bold"))
else:
canvas.itemconfig(quote_text, text=kanye_quote)
ISS Tracker
import requests
from datetime import datetime
import smtplib
import time
MY_LAT = 22.620856
MY_LONG = 120.311922
MY_ADDRESS = YOUR ADDRESS
PASSWORD = YOUR PASSWORD
def is_overhead():
response = requests.get(url="http://api.open-notify.org/iss-now.json")
response.raise_for_status()
data = response.json()
iss_latitude = float(data["iss_position"]["latitude"])
iss_longitude = float(data["iss_position"]["longitude"])
return abs(iss_longitude - MY_LONG) <= 5 and abs(iss_latitude - MY_LAT)
def is_night():
parameters = {
"lat": MY_LAT,
"lng": MY_LONG,
"formatted": 0,
}
response = requests.get("https://api.sunrise-sunset.org/json", params=parameters)
response.raise_for_status()
data = response.json()
sunrise = int(data["results"]["sunrise"].split("T")[1].split(":")[0]) - 16
sunset = int(data["results"]["sunset"].split("T")[1].split(":")[0]) + 8
time_now = datetime.now().hour
return not time_now > sunrise and time_now < sunset
while True:
time.sleep(60)
if is_overhead() and is_night():
with smtplib.SMTP("smtp.gmail.com") as connect:
connect.starttls()
connect.login(user=MY_ADDRESS, password=PASSWORD)
connect.sendmail(from_addr=MY_ADDRESS,
to_addrs="TARGET ADDRESS",
msg="Subject:GET ISS!\n\nYou can see ISS now.")