API

Info 253: 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: a function in JavaScript

function getMaximum(num1, num2) {
	/* ...
	   working code
	   ...
	*/

	return answer;
}
					

Simple API: a function in JavaScript

  • Imagine that you didn't know how that function was implemented
  • You only know that you enter two numbers in the function and you receive the greater of those two numbers
  • That is an API!

API as contract

  • The getMaximum function 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 getMaximum function and pass it two numbers as data
    • It will return a number that is the maximum of the numbers provided.

API as a contract example

../js/api.js

function getMaximum(num1, num2) {
	var answer = num1;

	if (num1 < num2) {
		answer = num2;
	}
	
	return answer;
}
					

API as a contract example

index.html

<!DOCTYPE html>
<html>
	<body>
		<button onclick="alert(getMaximum(5, 3))">
			Call API function getMaximum
		</button>
		<script src="../js/api.js"></script>
	</body>
</html>
					

API as a contract example

  • api.js defined an API action called getMaximum
  • It accepts two pieces of information: two numbers
  • It returns one piece of information: a number
  • Any web page can import api.js and by following the above contract can utilize the getMaximum function

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

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 Example

{
	"coord": {
		"weather": [ 
			{
				"id":800,
				"main":"Clear",
				"description":"clear sky",
				"icon":"01d"
			}
		],
		"base": "stations",
		"main": {
			"temp":294.787,
			"pressure":1024.49,
			"humidity":52,
			"temp_min":294.787,
			"temp_max":294.787,
			"sea_level":1032.69,
			"grnd_level":1024.49
		}, ...
					

JSON Example

  • The previous example was the response to a call to the OpenWeather API
  • We send a GET request to the OpenWeather API server sending two parameters:
    • "q" to query for the city
    • "appid" for an API key
  • We get the JSON response from the previous slide

How to call an API

Let's use curl!

curl -v "http://api.openweathermap.org/data/2.5/weather?\
q=Berkeley,ca&appid=af578739923ac7f173a6054b24c606ea"
					

How to call an API Response

Note the Content Type

HTTP/1.1 200 OK
Server: openresty
Date: Thu, 20 Oct 2016 22:54:46 GMT
Content-Type: application/json; charset=utf-8
Content-Length: 461

{
	"coord": {
		"weather": [ 
			{
				"id":800,
				"main":"Clear",
				"description":"clear sky",
				"icon":"01d"
				...
					

How to call an API

  • Since this API function call is using a GET request, we can use the address bar on a browser to call this API function

Now what?

  • API's are great for creating applications using data and adding functionality that wouldn't be possible without them
  • Think about Assignment 2 with the Mailgun server!
  • How do we build our own API's?

Let's use Python and Flask!

  • The only difference between a web server and an API server is that a web server typically returns HTML, CSS, and JavaScript, but an API server typically returns a structured data format, such as JSON or XML
  • So the only thing that changes in our code is the data that we are sending, and the Content Type

Our API Example

api.py (1/2)

from flask import Flask, request, render_template
import json
app = Flask(__name__,static_url_path="/static")

quote_db = {
    'sunday': "Life is about making an impact, not making an income. \
    –Kevin Kruse",
    'monday': "Whatever the mind of man can conceive and believe, it can achieve. \
    –Napoleon Hill",
    'tuesday': "Strive not to be a success, but rather to be of value. \
    –Albert Einstein",
    'wednesday': "You miss 100% of the shots you don’t take. \
    –Wayne Gretzky",
    'thursday': "Every strike brings me closer to the next home run. \
    –Babe Ruth",
    'friday': "We become what we think about. \
    –Earl Nightingale",
    'saturday': "Life is what happens to you while you’re busy making other plans. \
    –John Lennon",
}
					

Our API Example

api.py (2/2)

@app.route('/quote', methods=["POST"])
def quote_of_the_day():
    request_data = request.get_json()
    day_of_week = request_data['day_of_week']
    data = {'day': day_of_week, 'quote': quote_db[day_of_week]}
    return json.dumps(data)

					

What did we do?

  • We created an API with one function
  • We converted our web page we created on week 6 into an API that anyone can use
  • Just need to send a post request to the path /quote and send the parameters with content type "application/json" instead of "application/x-www-form-urlencoded"
  • How can we test it out? Let's use curl!

Using our API

curl -H "Content-Type: application/json" -X POST -d '{ "day_of_week" : "monday" }' \
http://localhost:5000/quote
					
  • In our API we send json and receive information via json

Questions?