APIs in the cloud

INFO 153B/INFO 253B: Backend Web Architecture

Kay Ashaolu

API

  • Application Programming Interface

What is an API?

  • From Quora: An API (Application Programming Interface) is best thought of as a contract provided by one piece of computer software to another.

Simple API: Functions

def save_def(word, definition):

    # ...
    # working code
    # ...

    return

def get_def(word):
    # ...
    # working code
    # ...

    return definition

Simple API: Functions

  • Imagine that you didn't know how these functions were implemented
  • You only know that if you provide a word and a definition to save_def it will be saved, and if you provide a word to get_def you will recieve the definition
  • That is an API!

API as contract

  • The get_def and save_def functions can be considered as one piece of computer software
  • The rest of your code can be considered as another piece of computer software
  • The contract between those two pieces of software:
    • If you call the get_def function and pass it a string as a word
    • It will return the definition stored within the API

API as a contract example

# local.py: Local Implementation of API

dictionary = {}

def save_def(word, definition):
    dictionary[word] = definition

def get_def(word):
    return(dictionary[word])

API as a contract example

  • local.py defined two API actions: get_def and save_def
  • get_def accepts one piece of information: a string, and returns one piece of information: a string
  • save_def accepts two pieces of information: two strings, and returns nothing
  • Any Python script could import local.py and use these functions without knowing how they are implemented

Now what really is an API

  • When people say an API, they don't really mean what we just covered
  • So let's talk about what people really mean when they say "API"

Now what really is an API?

The Power of APIs

  • Web applications used to combine all of their functionality in their website
  • Now they separated their "functions" into independent APIs so that clients other than their own websites can use it
  • So now anyone (and any computer/client) can access that information

APIs Over HTTP

  • Let's take that function concept to the Internet
  • We can define functions that can be called "through the Internet" using the HTTP protocol
  • We can use the same protocol as we do for web servers to send and receive information

What is HTTP

  • HTTP - HyperText Transfer Protocol
  • Hypertext: "Text with links"
  • HTTP is the protocol where you transfer "text with links" all over a network (or a network of networks, like the internet)
  • Note: HTTPS: Secure HTTP = encrypted HTTP

HTTP Methods

  • HTTP defines a few "methods" that define the information that is sent to and from the client and the server for a particular endpoint
  • These "methods" provide a strong suggestion on how the given endpoint should interact with the server
  • We will get into the details later in this course 

HTTP Methods

    POST (i.e. C in CRUD - Create data)
    • Submits data to be processed to a specified resource
  • GET (i.e. R in CRUD - Retrieve data)
    • Requests data from a specified resource.
    • NOTE: ONLY method where input is expected in the URL
  • PUT (i.e. U in CRUD - Update Data
    • Update specified resource
  • DELETE (i.e. D in CRUD - Delete Data)
    • Deletes specified resource

API over HTTP considerations

  • Internet has the infrastructure to send "text with links" all over the world
  • We are now building these APIs to use this HTTP protocol to send structured data all over the world
  • But, will sending "text with links" work for this?
  • e.g. imagine writing a function where you receive this as an input and you wanted the temperature:
<a class="styles--weatherData--24HO9 weather-data Button--default--2gfm1" href="/weather/today/l/c6e9a92db240946a7b8379f2177f4d7613047e97ecb1192810d1a0c69f4c97f9" 
   target="_self" data-from-string="locationCard"><svg set="weather" skycode="31" theme="full" name="" class="Icon--icon--2aW0V Icon--fullTheme--3Fc-5" 
    data-testid="Icon" viewBox="0 0 200 200"><title>Clear Night</title><use xlink:href="#svg-symbol-moon" transform="matrix(2.07 0 0 2.07 -72 3)"></use>
  <use xlink:href="#svg-symbol-star" transform="translate(-4 -1)"></use>
  <use xlink:href="#svg-symbol-star" transform="matrix(.8 0 0 .8 62 78)">
  </use></svg><span class="styles--temperature--3YaGV">35°</span></a>

JSON

  • JavaScript Object Notation
  • A lightweight format that is used for data input and output
  • It's a subset of the JavaScript language
  • It's the way objects are built in JavaScript

JSON Examples

/* save_def input data */
{
    word: "baby",
    definition: "A small person"
}
/* get_def output data */
{
    definition: "A small person"
}
/* sample weather data*/
{
    temp: "35",
    unit: "Farenheit"
}

JSON Examples

  • The previous examples are how we could model the input parameters of the save_def function in JSON and the output result of the get_def function in JSON respectively
  • save_def takes two parameters:
    • word: for the word
    • definition: for the definition
  • get_def returns one result
    • definition: of the word sent to it

Note on Content-Types

  • The Content-Types of both request and response are important, especially for POST/PUT requests
  • As an API designer, you have the ability to dictate how clients use your API, including what kind of data that you want to send
  • In this class we are building endpoints that send and receive JSON so we can standardize our outputs and inputs by requiring "application/json" for both inputs and outputs

Example API Server Code

# api.py

from flask import Flask, request, Response
import json
import logging

app = Flask(__name__)

dictionary = {}

@app.route('/save_def', methods=["POST"])
def save_def():

    if request.headers['Content-Type'] == 'application/json':
        arguments = request.get_json()
        word = arguments.get("word")
        definition = arguments.get("definition")

        dictionary[word] = definition
        logging.info("Word {} with definition {} saved".format(word, definition))

    else:
        logging.warning("Invalid content type: only application/json is allowed")

    resp = Response('')
    return resp

Example API Server Code

@app.route('/get_def/<word>', methods=["GET"])
def get_def(word):
    # Note for GET Request, we get input parameters from URL, not
    # application/json
    # request body
    
    if word not in dictionary:
        definition = "Not Found"
        logging.warning("{} not found in dictionary".format(word))
    else:
        definition = dictionary[word]


    data = {"word": word, "definition": definition}
    resp = Response(json.dumps(data), mimetype='application/json')

    return resp

Example Client Code

# client.py

import requests
import json

server_url = "http://localhost:5050"

def save_def(word, definition):
    headers = {'Content-Type': 'application/json'}
    data =  {"word": word, "definition": definition }
    url =  f"{server_url}/save_def"
    r = requests.post(url, data=json.dumps(data), headers=headers)

def get_def(word):

    headers = {'Accept':'application/json'}
    url = f"{server_url}/get_def/{word}"
    r = requests.get(url, headers=headers)

    data = r.json()
    return data["definition"]

if __name__ == "__main__":
    print("Saving the definition: country: a nation with its own government, occupying a particular territory.")
    save_def(word="country", definition="a nation with its own government, occupying a particular territory.")
    print()

    print("Retrieving the definition of 'country'")
    print(get_def("country"))

Questions?