Using API's

INFO 253A: Frontend 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) {
	let 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 a single parameter:
    • "q" to query for the city
  • 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"

API HTTP Response

HTTP/1.1 401 Unauthorized
Server: openresty
Date: Fri, 02 Nov 2018 12:34:35 GMT
Content-Type: application/json; charset=utf-8
Content-Length: 107
Connection: keep-alive
X-Cache-Key: /data/2.5/weather?q=berkeley,ca
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
Access-Control-Allow-Methods: GET, POST

Connection #0 to host api.openweathermap.org left intact
{"cod":401, "message": "Invalid API key.
	Please see http://openweathermap.org/faq#error401 for more info."}

We got a 401 error

From website: Starting from 9 October 2015 our API requires a valid APPID for access. Note that this does not mean that our API is subscription-only now - please take a minute to register a free account to receive a key.

We got a 401 error

  • Remember that 400s HTTP response codes mean that there is a client error
  • So we made a mistake
  • Now this openweathermap API requires an appid and it's telling you to sign up and generate one

But what is an appid?

  • Many API's require some sort of identification so that the API knows who is making the requests
  • Typically the backend will assign id's by user or by application (one user could have several applications)
  • Statistics, rate limiting, blocking, and levels of authorization are all possible when you require application ids to be passed on every request

How do you typically get an appid?

  • First you will need to go to the website that hosts the application and go through their signup process
  • Next look for somewhere where they tell you how to use their API: typically they will show you how to generate a new application id
  • Let's do this now: Openweathermap signup

Now we have an appid!

  • af578739923ac7f173a6054b24c606ea
  • We can now add our appid in our curl query to get a 200 response back

How to call an API

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
  • For POST requests, we cannot do this

Questions?

APIs - Frontend Webarch

By kayashaolu

APIs - Frontend Webarch

Course Website: https://www.ischool.berkeley.edu/courses/info/253a

  • 532