Sunday, November 6, 2022

Python - API endpoint and parameters (Day 33)

This is a 100 Days challenge to learn a new language (Python). 100 Days of Code - The Complete Python Pro Bootcamp 

I will post some notes to motivate myself to finish this challenge.


Application Programming Interfaces



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.


HTTP Status Code



    1XX: Information
    2XX: Successful Response
    3XX: Redirection Message
    4XX: Client Error
    5XX: Server Error

Reference: Link


requests module



requests is an elegant and simple HTTP library for Python.


API Endpoint



It is an URL to tell our program that where to get data.

Ex: Get ISS Location through Web API
import requests

# Sends a GET request.
response = requests.get("http://api.open-notify.org/iss-now.json")

# Raises HTTPError, if one occurred.
response.raise_for_status()

# Returns the json-encoded content of a response, if any.
data = response.json()

print(data)


Result:
{
'iss_position': {'longitude': '37.1042', 'latitude': '-44.8634'},
'message': 'success', 'timestamp': 1667726746
}



Challenge - Kanye Quote App



Use Tkinter to build a GUI app, and integrate it with kanye.rest Web API to get the quote once the emoji is clicked.




Ex: 
from tkinter import *
import requests


def get_quote():
    """Get quote from kanye.rest web api"""

    # Sends a GET request.
    response = requests.get("https://api.kanye.rest/")

    # Raises HTTPError, if one occurred.
    response.raise_for_status()

    # Returns the json-encoded content of a response, if any.
    data = response.json()

    # Update canvas text
    canvas.itemconfig(quote_text, text=data["quote"])


# Init
root = Tk()
root.title("Kanye Says...")
root.config(padx=50, pady=50)

# Init canvas
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)

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

# Start the Event Loop
root.mainloop()



API Parameters



Able to give input to the Web API and get the data back based on the input.

Ex: Get sunrise and sutset info by the current location
import requests

MY_LAT = 49.282730
MY_LNG = -123.120735

# Prepare parameters for API
parameters = {"lat": MY_LAT, "lng": MY_LNG, "formatted": 0}

# Sends a GET request.
response = requests.get("https://api.sunrise-sunset.org/json",
params=parameters)

# Raises HTTPError, if one occurred.
response.raise_for_status()

# Returns the json-encoded content of a response, if any.
data = response.json()

print(data)


Result:
{
'results': {
'sunrise': '2022-11-06T15:07:22+00:00',
'sunset': '2022-11-07T00:44:52+00:00',
'solar_noon': '2022-11-06T19:56:07+00:00',
'day_length': 34650,
'civil_twilight_begin': '2022-11-06T14:35:13+00:00',
'civil_twilight_end': '2022-11-07T01:17:01+00:00',
'nautical_twilight_begin': '2022-11-06T13:57:13+00:00',
'nautical_twilight_end': '2022-11-07T01:55:01+00:00',
'astronomical_twilight_begin': '2022-11-06T13:20:05+00:00',
'astronomical_twilight_end': '2022-11-07T02:32:09+00:00'
}, 'status': 'OK'
}



Project - ISS Overhead Notifier



#1 Get ISS location by Web API
http://open-notify.org/Open-Notify-API/ISS-Location-Now/

#2 Get your city Location
https://www.latlong.net/

#3 Determine it is night by Web API
https://sunrise-sunset.org/api

#4 If ISS is overhead and it is night time, send an eamil to yourself to notify you to look up

#5 Run #4 every 60 seconds

Ex:
import requests
from datetime import datetime
import smtplib
import time

GMAIL_SMTP_SERVER_ADDRESS = "smtp.gmail.com"
GMAIL_SMTP_TLS_PORT = 587
GOOGLE_APP_PWD = "your google app pwd"
MY_EMAIL_ADDRESS = "your email address"
MY_LAT = 49.282730
MY_LONG = -123.120735


def send_email(receiver, message):
    """Send an custom email to the receiver"""

    # Create a connection to SMTP Provider
    with smtplib.SMTP(
        host=GMAIL_SMTP_SERVER_ADDRESS, port=GMAIL_SMTP_TLS_PORT
    ) as connection:

        # Make this connection secure
        connection.starttls()

        # Login with your Google App Password
        connection.login(user=MY_EMAIL_ADDRESS, password=GOOGLE_APP_PWD)

        # Send an email
        connection.sendmail(from_addr=MY_EMAIL_ADDRESS,
to_addrs=receiver, msg=message)


def get_iss_location():
    """Get ISS current location from web api"""

    # Sends a GET request.
    response = requests.get(url="http://api.open-notify.org/iss-now.json")
    # Raises HTTPError, if one occurred.
    response.raise_for_status()
    # Returns the json-encoded content of a response, if any.
    return response.json()


def is_iss_overhead():
    """Determine if ISS is overhead or not"""

    data = get_iss_location()
    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 (
        iss_latitude - 5 <= MY_LAT <= iss_latitude + 5
        and iss_longitude - 5 <= MY_LONG <= iss_longitude + 5
    ):
        return True

    return False


def get_sunrise_and_sunset_info(lat, lng):
    """Get the sunrise and sunset info from web api"""

    # Prepare parameters for API
    parameters = {
        "lat": lat,
        "lng": lng,
        "formatted": 0,
    }
    # Sends a GET request.
    response = requests.get("https://api.sunrise-sunset.org/json",
params=parameters)
    # Raises HTTPError, if one occurred.
    response.raise_for_status()
    # Returns the json-encoded content of a response, if any.
    return response.json()


def is_night_time():
    """Determine if it is night time from the current location"""

    data = get_sunrise_and_sunset_info(MY_LAT, MY_LONG)
    sunrise = int(data["results"]["sunrise"].split("T")[1].split(":")[0])
    sunset = int(data["results"]["sunset"].split("T")[1].split(":")[0])

    time_now = datetime.now()

    # If it is dard, then send an email to myself (Look Up)
    if time_now.hour < sunrise or time_now.hour > sunset:
        return True

    return False


while True:
    # Delay 60 seconds
    time.sleep(60)

    # Send an email if iss is overhead and it is night time
    if is_iss_overhead() and is_night_time():
        send_email(
            MY_EMAIL_ADDRESS,
            "Subject: Look Up\n\nISS is overhead!\n",
        )


No comments:

Post a Comment