Monday, November 28, 2022

Python - API Keys, Authentication, and Environmental Variables (Day 35)

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.


What is API Keys



Previously, we are using some free web APIs and they are open to everyone without authentication.

But data/content is valuable in real world. Therefore there are plenty of data/content provider to provide web APIs to let subscribed users to use it. (Such as getting the weather historical data )

In order to know who is calling their web APIs, they need to authenticate users.

They will generate a unique API key to each end user, and that unique API key must be passed when making web API calls.


Weather web API




Ex: Get current weather of your city
import requests

OPEN_WEATHER_ENDPOINT = 'https://api.openweathermap.org/data/2.5/weather'
OPEN_WEATHER_API_KEY = 'your open weather api key'

# Prepare parameters for API
parameters = {
    "lat": 49.282730,
    "lon": -123.120735,
    "appid": OPEN_WEATHER_API_KEY,
}
# Sends a GET request.
response = requests.get(
    OPEN_WEATHER_ENDPOINT, params=parameters)
# Raises HTTPError, if one occurred.
response.raise_for_status()
# Returns the json-encoded content of a response, if any.
res = response.json()

print(f"Current Wearther: {res['weather'][0]['main']}")


Ex: Check if it will rain in your city in the next 12 hours (weather id > 700 means it will rain)
import requests

OPEN_WEATHER_ENDPOINT = 'https://api.openweathermap.org/data/2.5/forecast'
OPEN_WEATHER_API_KEY = 'your open weather api key'

# Prepare parameters for API
parameters = {
    "lat": 49.282730,
    "lon": -123.120735,
    # Next 4 * 3 hours
    "cnt": 4,
    "units": "metric",
    "appid": OPEN_WEATHER_API_KEY,
}
# Sends a GET request.
response = requests.get(
    OPEN_WEATHER_ENDPOINT, params=parameters)
# Raises HTTPError, if one occurred.
response.raise_for_status()
# Returns the json-encoded content of a response, if any.
res = response.json()

# Filter data if its weather id is larger than 700
raining_in_12_hours = [item for item in res["list"]
                       if item["weather"][0]["id"] > 700]

if len(raining_in_12_hours) > 0:
    print("It is going to rain. Remember to bring an Umbrella!")



Sending SMS



Ex: 
import requests
from twilio.rest import Client

OPEN_WEATHER_ENDPOINT = 'https://api.openweathermap.org/data/2.5/forecast'
OPEN_WEATHER_API_KEY = 'your open weather api key'
TWILIO_ACCOUNT_SID = 'your twilio account sid'
TWILIO_AUTH_TOKEN = 'your twilio auth token'

# Prepare parameters for API
parameters = {
    "lat": 49.282730,
    "lon": -123.120735,
    # Next 4 * 3 hours
    "cnt": 4,
    "units": "metric",
    "appid": OPEN_WEATHER_API_KEY,
}
# Sends a GET request.
response = requests.get(
    OPEN_WEATHER_ENDPOINT, params=parameters)
# Raises HTTPError, if one occurred.
response.raise_for_status()
# Returns the json-encoded content of a response, if any.
res = response.json()
# Filter data if its weather id is larger than 700
raining_in_12_hours = [item for item in res["list"]
                       if item["weather"][0]["id"] > 700]

if len(raining_in_12_hours) > 0:
    client = Client(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN)

    message = client.messages.create(
        body='It is going to rain. Remember to bring an Umbrella!',
        from_='twilio test number',
        to='your phone number'
    )

    # If there is a sid, SMS was sent successfully
    print(message.sid)



Environmental Variables



Normally, we don't want to put the web API token or key in our code. Reference

    export YOUR_ENV_NAME=your_env_value

Or Using python-dotenv

Ex: 
import requests
import os
from twilio.rest import Client
from dotenv import load_dotenv

# Load Environmental Variables from .env
load_dotenv()

OPEN_WEATHER_ENDPOINT = 'https://api.openweathermap.org/data/2.5/forecast'
OPEN_WEATHER_API_KEY = os.environ.get("OPEN_WEATHER_API_KEY")
TWILIO_ACCOUNT_SID = os.environ.get("TWILIO_ACCOUNT_SID")
TWILIO_AUTH_TOKEN = os.environ.get("TWILIO_AUTH_TOKEN")

# Prepare parameters for API
parameters = {
    "lat": 49.282730,
    "lon": -123.120735,
    # Next 4 * 3 hours
    "cnt": 4,
    "units": "metric",
    "appid": OPEN_WEATHER_API_KEY,
}
# Sends a GET request.
response = requests.get(
    OPEN_WEATHER_ENDPOINT, params=parameters)
# Raises HTTPError, if one occurred.
response.raise_for_status()
# Returns the json-encoded content of a response, if any.
res = response.json()
# Filter data if its weather id is larger than 700
raining_in_12_hours = [item for item in res["list"]
                       if item["weather"][0]["id"] > 700]

if len(raining_in_12_hours) > 0:
    client = Client(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN)

    message = client.messages.create(
        body='It is going to rain. Remember to bring an Umbrella!',
        from_='twilio test number',
        to='your phone number'
    )

    # If there is a sid, SMS was sent successfully
    print(message.sid)


No comments:

Post a Comment