Consuming an API

The following sends a POST request to the PQuotes API.

import requests

# api endpoint
url = "https://pquotes.p.rapidapi.com/api/quote"

# specify topic
payload = {"topic": "motivation"}
# rapidapi headers (key, host, and body type)
headers = {
	"content-type": "application/json",
	"X-RapidAPI-Key": "c4fb753596mshe0fd8cf8607e256p1eb9ebjsn7c61a5142004",
	"X-RapidAPI-Host": "pquotes.p.rapidapi.com"
}

# send post request to API with body and headers; convert response from json to obj
response = requests.post(url, json=payload, headers=headers).json()
# get text and author from response
text = response["quote"]
author = response["by"]

# print quote using python format string
print(f"Your inspirational quote of the day is:\n \"{text}\" -- {author}")
Your inspirational quote of the day is:
 "Believe you can and you’re halfway there." --  Theodore Roosevelt

Creating an API with Flask

from flask import Flask, request
import random

# create flask app
app = Flask(__name__)

# initialize array with quotes
quotes = [
    "GOD DID - DJ Khaled",
    "What do I do now - Alex Kumar",
    "You are your only limit - Kalani Cabral-Omana",
    "You give a man food, he's given lunch for the day. If you teach a man, then you like, can eat... I forgot what it was - Navan Yatavelli"
]


# function for retrieving random quote
def random_quote():
    return random.choice(quotes)


# GET endpoint on /get returns a quote
@app.route('/get', methods=['GET'])
def get():
    return {
        "status": "success",
        "data": {
            "quote": random_quote()
        }
    }


# POST endpoint on /post returns a message based on req body
@app.route('/post', methods=['POST'])
def post():
    data = request.json
    name = data["name"]
    return {
        "status": "success",
        "data": {
            "message": "Hello, " + name
        }
    }