APIs

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 can access that information

The Power of APIs Example

  • Without API: An app finds the current weather in London by opening http://www.weather.com/ and reading the web page like a human does, interpreting the content.
  • With API: An app finds the current weather in London by sending a message to the weather.com API (in a structured format like JSON). The weather.com API then replies with a structured response.

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
  • Caveat: Instead of sending HTML/CSS/JS, we send and receive a more structured data representation, like XML or JSON
  • We have been doing this throughout this class already

JSON

  • JavaScript Object Notation
  • A lightweight format that is used for data interchanging
  • 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"
}

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 definitoin
  • 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
  • If you do plan on your server accepting data from an HTML form, you will need to accept Content-Type "x-www-form-urlencoded"
  • However, we are focusing on the backend, so we can standardize our outputs and inputs by requiring "application/json" for both inputs and outputs

Example API Server Code

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
        status_code = 200
        logging.info("Word {} with definition {} saved".format(word, definition))

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

    resp = Response('', status=status_code)
    return resp

Example API Server Code

@app.route('/get_def', methods=["GET"])
def get_def():
    # Note for GET Request, we get input parameters from URL, not
    # application/json nor applicaiton/x-www-form-urlencoded
    # request body
    word = request.args.get("word")

    if word not in dictionary:
        definition = "Not Found"
        status_code = 404
        logging.warning("{} not found in dictionary".format(word))
    else:
        definition = dictionary[word]
        status_code = 200


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

    return resp

Example Client Code

import requests
import json

server_url = "http://localhost:5000"

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

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

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

Questions?