TIL Python Basics Day 33 - API Endpoints & API Parameters / ISS Overhead Notifier

이다연·2021년 1월 18일
0

Udemy Python Course

목록 보기
32/64

API Endpoints & API Parameters / ISS Overhead Notifier

API: Application Programming Interface

  • to pull live data from websites

-is a set of commands, functions, protocols, and objects that programmers can use to create S/W or interact with an external system.

-barrier btw my program and external system. API prescribed to make a request to the external system for some piece of data with structured request according to all requirements that external system set out.

API Endpoint: URL (location)

API Request

  • no authentication needed, open to the public data

JSON data is transferring data across the internet. Minimalist piece of data.

JSON Viewer Awesome : chrome app, display Json data with easy readability

Responses

Errors and Exceptions

import requests 

response = requests.get(url=)
response.raise_for_status() 

1xx: Informational
2xx: Success
3xx: Redirection (No permission)
4xx: Client Error
5xx: Server Error

Task.1 Kanye quotes


Purpose: Use Kanye Quotes API to make Tkinter GUI Program

from tkinter import *
import requests
#
def get_quote():

    response = requests.get(url="https://api.kanye.rest/")
    response.raise_for_status()

    data = response.json()["quote"]
    canvas.itemconfig(quote_text, text=data)
    return data

window = Tk()
window.title("Kanye Says...")
window.config(padx=50, pady=50)

canvas = Canvas(width=300, height=414)
background_img = PhotoImage(file="background.png")
canvas.create_image(150, 207, image=background_img)
quote_text = canvas.create_text(150, 207, text="Kanye says...", width=250, font=("Arial", 30, "bold"), fill="white")
canvas.grid(row=0, column=0)

kanye_img = PhotoImage(file="kanye.png")
kanye_button = Button(image=kanye_img, highlightthickness=0, command=get_quote)
kanye_button.grid(row=1, column=0)


window.mainloop()

API Parameters

https://opentdb.com/api.php?amount=10&type=boolean

-API endpoint is everything before the question mark, after the question mark, are parameters

-Passing in different input as parameters so we can get different pieces of information back from the API provider.

-API Documentation will provide parameters requirements if one needed. Optional parameters have default values.

e.g. get Sunset & Sunrise time

Params (after endpoint) is a required parameters, which passes over the location. We made parameters in a dictionary format.

.split("divider") returns a list with divided values.
sunset = data['results']['sunset'].split("T")[0]
#printed '2021-01-18T07:55:39+00:00' -> '2021-01-18'

API: https://api.sunrise-sunset.org/json/
Documentation

import requests
from datetime import datetime

MY_LAT= 51.507351
MY_LONG= -0.127758

parameters = {
    "lat": MY_LAT,
    "lng": MY_LONG,
    "formatted": 0  #to turn off formatting, returns 24-hour clock format 
}

#sunrise&sunset
response = requests.get("https://api.sunrise-sunset.org/json", params=parameters)
response.raise_for_status()

data = response.json()
sunrise = data['results']['sunrise'].split("T")[1].split(":")[0]
sunset = data['results']['sunset'].split("T")[1].split(":")[0]

print(data)
#{'results': {'sunrise': '2021-01-18T07:55:39+00:00', 'sunset': '2021-01-18T16:26:38+00:00', ...

print(sunset) #16
print(sunrise) #07
time_now = datetime.now()
print(time_now.hour) #11



Project. ISS Overhead Notifier

Purpose: To fetch location data of ISS(International Space Station Current Location) using API, send email when it's flying overhead.

  • run every 60 sec with time module
while True:
    time.sleep(60) 
  • Be aware of data type when comparing each other
float
MY_LAT = 51.507351
iss_latitude = float(data["iss_position"]["latitude"]) 

int
sunrise = int(data["results"]["sunrise"].split("T")[1].split(":")[0])
time_now = datetime.now().hour

import requests
from datetime import datetime
import smtplib
import time

MY_LAT = 51.507351
MY_LONG = -0.127758

# #Your position is within +5 or -5 degrees of the ISS position.
def is_close():
    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"])
    if MY_LAT-5 <= iss_latitude <= MY_LAT+5 and MY_LONG-5 <= iss_longitude <= MY_LONG+5:
        return True

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])
    sunset = int(data["results"]["sunset"].split("T")[1].split(":")[0])

    time_now = datetime.now().hour

    if time_now >= sunset or time_now <= sunrise:
        return True

my_email = "testpythondy@gmail.com"
my_password = "d"
yahoo_email = "testpythondy@yahoo.com"
while True:
    time.sleep(60) #run every 60 sec
    if is_close() and is_night():
        with smtplib.SMTP("smtp.gmail.com") as connection:
            connection.starttls()
            connection.login(user=my_email, password=my_password)
            connection.sendmail(
                from_addr=my_email,
                to_addrs=my_email,
                msg="Subject: Loop Up! \n\n ISS is above you in the sky. "
        )
profile
Dayeon Lee | Django & Python Web Developer

0개의 댓글