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.
The API is an interface or rather a sort of barrier between our program and an external system.
If we want to get data from a particular external service, then we need to know what location that data is stored.
API request is kind of similar to going to the bank and tring to get some money out, so trying to withdraw some data from ther vault. bank teller is kind of acting like the API.
It's the interface between me and the external system.
import requests
response = requests.get(url="http://api.open-notify.org/iss-now.json")
print(response)
#output
<Response [200]>
The 404 response code basically means that the thing that we're looking for doesn't exist.
Basically when we're trying to retrieve something from a website and it doesn't actually have the thing we're looking for.
1XX: Hold on
2XX: Here you go
3XX: Go away
4XX: You screwed up
5XX: I screwed up
response = requests.get(url="http://api.open-notify.org/iss-now.json")
print(response.status_code)
#output : 200
response = requests.get(url="http://api.open-notify.org/is-now.json") # Invalid endpoint
print(response.status_code)
#output : 404
response = requests.get(url="http://api.open-notify.org/iss-now.json")
if response.status_code != 200:
raise Exception("Bad response from ISS API")
response = requests.get(url="http://api.open-notify.org/iss-now.json")
if response.status_code == 404:
raise Exception("That resource does not exist.")
elif response.status_code == 401:
raise Exception("You are not authorised to access this data.")
instead of using those things, we can use .raise_for_status()
.
import requests
response = requests.get(url="http://api.open-notify.org/is-now.json")
response.raise_for_status()
#output
requests.exceptions.HTTPError: 404 Client Error: Not Found for url: http://api.open-notify.org/is-now.json
import requests
response = requests.get(url="http://api.open-notify.org/iss-now.json")
data = response.json()
print(data)
#output
{'message': 'success', 'timestamp': 1646050671, 'iss_position': {'longitude': '74.3475', 'latitude': '-51.3724'}}
import requests
response = requests.get(url="http://api.open-notify.org/iss-now.json")
data = response.json()["iss_position"]
print(data)
# output : {'longitude': '83.0557', 'latitude': '-51.6139'}
data = response.json()["iss_position"]["longitude"]
print(data)
# output : 83.0557
import requests
response = requests.get(url="http://api.open-notify.org/iss-now.json")
data = response.json()
longitude = data["iss_position"]["longitude"]
latitude = data["iss_position"]["latitude"]
iss_position = (longitude, latitude)
print(iss_position)
# output : ('103.1059', '-49.4265')
from tkinter import *
import requests
def get_quote():
response = requests.get("https://api.kanye.rest")
response.raise_for_status()
quote = response.json()["quote"]
canvas.itemconfig(quote_text, text=quote)
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 Quote Goes HERE", 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()
get_quote()
함수 부분만 직접 작성한 거긴 한데
나름 tkinter
랑 친해졌나보다.. 안찾아보고 바로 구현해냄 ㅠ
This is a way that allows us to give an input when we are making our API request so that we can get different pieces of data back, depending on our input in the same way that we've given different inputs into the same function in order to get a defferent outcome.
import requests
MY_LAT = 51.495278
MY_LNG = -0.131699
parameters = {
"lat": MY_LAT,
"lng": MY_LAT,
"formatted": 0
}
response = requests.get("https://api.sunrise-sunset.org/json", params=parameters)
response.raise_for_status()
data = response.json()
sunrise = data["results"]["sunrise"]
sunset = data["results"]["sunset"]
print(sunrise)
print(sunrise.split("T"))
print(sunrise.split("T")[1].split(":"))
print(sunrise.split("T")[1].split(":")[0])
# output
# 2022-02-28T03:19:34+00:00
# ['2022-02-28', '03:19:34+00:00']
# ['03', '19', '34+00', '00']
# 03
import requests
from datetime import *
MY_LAT = 51.495278
MY_LNG = -0.131699
parameters = {
"lat": MY_LAT,
"lng": MY_LAT,
"formatted": 0
}
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(sunrise)
print(sunset)
time_now = datetime.now()
print(time_now.hour)
#output
03
14
22
import requests
from datetime import datetime
import smtplib
import time
MY_LAT = **.****** # Your latitude
MY_LONG = ***.****** # Your longitude
MY_EMAIL = "******@yahoo.com"
MY_PASSWORD = "**********"
def is_iss_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"])
#Your position is within +5 or -5 degrees of the ISS position.
if MY_LAT-5 <= iss_latitude <= MY_LAT+5 and MY_LONG-5 <= iss_longitude <=MY_LONG:
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
while True:
time.sleep(60)
if is_iss_overhead() and is_night():
connection = smtplib.SMTP("smtp.mail.yahoo.com")
connection.starttls()
connection.login(MY_EMAIL, MY_PASSWORD)
connection.sendmail(
from_addr=MY_EMAIL,
to_addrs=MY_EMAIL,
msg="Subject:Look Up\n\nThe ISS is above you in the sky."
)
밤이고, 국제우주정거장(ISS)이 머리 위에 있을 때 받을 수 있는 메일..