Contents

  • Javascript, JQuery, JSON
  • HTTP, REST, Web Servers

Javascript

  • Scripting/Interpreted/JIT compiled
  • Multi-paradigm: imperative, object-based, functional
  • Dynamically typed, weakly typed
  • Small and lightweight
  • Capabilities provided by object libraries
  • Browser based, or server-side (Node.js)
  • C/Java based syntax
  • Standardized as ECMAScript

History

  • Designed in 10 days in 1995
  • By Brendan Eich, who later co-founded Mozilla
  • For Netscape Navigator web browser

Data Types

  • Number
  • String
  • Boolean
  • Object
  • Null
  • Undefined
							// 64 bit floating point numbers
const PI = 3.14159;
var a = 72;

/* Unicode strings, immutable */
var firstName = "Dorothy";
var lastName = 'Dingl\u0BD0erry';
var someʘther = "I see you";

/* Boolean */
var ok = true;

// price is undefined, there is no literal for undefined
var price;

// null acts as 0 or false
var myObject = null;
							
						
							// Objects have properties and methods
var car = {
	doors: 5,
	make: "Tesla",
	model: "P100D",
	drive: function() { console.log("Driving my " + this.make); } 
};

var obj1 = { id: 2394340, name: "Bob", aliases: ["Robert","Jake"] };
var obj2 = {};
obj2.name = "Carol"; 
obj2["age"] = 5;

var obj3 = new Object();

// ??
var obj4 = {a: 5, 5:73, "":"hi"};
							
						
							// Built-in "Native" objects
								
// Array -- variable length list
var colors = ["Red", "Orange", "Yellow"];
var sizes = ["Small", "Medium", 27];
var x = colors[0];
console.log("Num sizes = " + sizes.length);

// Date
var now = new Date();

// Math
var num = Math.random();

// Regex
var patt = /#[a-fA-F0-9]{6}/
							
						
							// Built-in "Native" objects
							
// Function
var adder = new Function("a","b","return a + b");
var ans = adder(4,7);

// Map
// Set
// Generator
// JSON
// ...
							
						

Control Structures

Pretty much like Java: if-else, switch, for, foreach, while, do-while

Note consequences of loose typing:

							1 == "1"		// true
0 == false		// true
3 === 3			// true
3 === "3"		// false

if(4)
    console.log("Yup");
							
						

Functions/Methods

  • Functions are first-class objects
  • Primitives are passed by value (number, boolean and string)
  • Objects are passed as a copy of the reference
  • If a function is declared inside an object, then it's a method. "this" is then a reference to the enclosing object

Function Patterns

							// Plain old function
function square(n){				// square(6)
	return n * n;
}

// Function expression (anonymous function)
var cube = function(x) { return x**3; };	// cube(7)

// Immediately invoked function expression (IIFE or "iffy")
var area = (function(w,h) { 			// area
	return w * h; 
}(5,2));
							
						

Lots More

  • Constructor Functions
  • Inheritance
  • try-catch
  • Generators
  • Closures

Browser Object Model

Window object has:

  • Document (DOM)
  • History
  • Location
  • Navigator
  • Screen
  • Storage
  • Console
  • GlobalEventHandlers
							var dim = [window.screen.width, window.screen.height];
window.console.log("Your screen is set to " + dim);

console.log("This window could go back " + (window.history.length - 1) + " pages");

window.onload = function() {console.log("Your DOM is ready!");}

window.onmousedown = function() {console.log("hi");};
							
						

Document Object Model

Eloquent Javascript

DOM Nodes

  • Document (Node.DOCUMENT_NODE)
  • Element (Node.ELEMENT_NODE)
  • Attribute
  • Text (Node.TEXT_NODE)
  • Comment (Node.COMMENT_NODE)
							var type = document.childNodes[1].nodeType;	// 1 (html element)
							
						

Accessing Elements

							// Select individual elements
var node = document.getElementById("mainContent");
node     = document.querySelector("div.questions");

// Select multiple elements (returns a NodeList collection object)
var nodes = document.querySelectorAll("div.row");
nodes     = document.getElementsByClassName("row");
nodes     = document.getElementsByTagName("li");

// Traverse
var node2 = node.parentNode;
node2     = node.previousSibling;
node2     = node.nextSibling;
node2     = node.firstChild;
node2     = node.lastChild;
							
						

Modifying Elements

							// Set class attribute
var node = document.getElementById("mainContent");
node.className = "big";

// Access text only
console.log(node.textContent);

// Change the contents of an element
node.innerHTML = "Some good stuff here!";

// Get/Set an attribute value
var nodes = document.getElementsByTagName("a");
nodes[0].getAttribute("href");

/* See also: hasAttribute(), removeAttribute() and the id property */
							
						

Adding Elements

							// Add a new list item
var newItem = document.createElement("li");
var newText = document.createTextNode("Product Name Here");
newItem.appendChild(newText);
var listNode = document.querySelector("ul#products");
listNode.appendChild(newItem);

/* See also: removeChild() */
							
						

Events

Using Event Listeners

from Javascript & jQuery Book

							function checkUsername() 
{
  var elMsg = document.getElementById('feedback');
  if (this.value.length < 5) 
  {
    elMsg.textContent = 'Username must be 5 characters or more';
  } else 
  {
    elMsg.textContent = '';
  }
}
// Select the text input element for the username
var elUsername = document.getElementById('username');
// When it loses focus call checkUsername()
elUsername.addEventListener('blur', checkUsername, false);
							
						

Problems?

QuirksMode.org

jQuery

A DOM manipulation library

  • Easier to access elements (re-using CSS Selectors)
  • Uses a productive programming style
  • Don't re-invent the wheel
  • Manage compatibility issues
  • Led to the addition of W3C's Selectors API
  • Provides effects, animations and other things if desired
							// Select and modify
$("li.sales").addClass("cheap");
// same as
window.jQuery("li.sales").addClass("cheap");

// Remove the hidden class from all dd elements
$("dd").removeClass("hidden");

// Chaining and effects 
// (from http://javascriptbook.com/code/c07/chaining.html)
$('li[id!="one"]').hide().delay(500).fadeIn(1400);

// Create a new p element node and add it
$("

My new text

").appendTo( "body" );
							// Apply an arbitrary function to each element
$("p.announcement li").each( function(index) {
	$(this).prepend(index + ": ");
});

// Events
$(function() {
  var el = $("div.requirements");
  el.on("mouseover click",function() {
    $("div.requirements :header").css("background-color","#FFFFFF");
  });
  el.on("mouseout",function() {
    $("div.requirements :header").css("background-color","#FCEAD1");
  });
});
							
						

jQuery Tour

jQuery Quick API Reference

AJAX

  • Asynchronous
  • HTML, XML or JSON
  • Web API's
  • Basic Javascript: XMLHttpRequest object
  • JQuery wraps this in e.g. ajax() or getJSON

JSON

json.org

							{"menu": {
  "id": "file",
  "value": "File",
  "popup": {
    "menuitem": [
      {"value": "New", "onclick": "CreateNewDoc()"},
      {"value": "Open", "onclick": "OpenDoc()"},
      {"value": "Close", "onclick": "CloseDoc()"}
    ]
  }
}}
							
						

JSON

curl https://api.github.com/search/repositories?q=json+language:javascript&sort=stars&order=desc GitHub API

							{
  "total_count": 16859,
  "incomplete_results": false,
  "items": [
    {
      "id": 1353110,
      "name": "json",
      "full_name": "trentm/json",
      "owner": {
        "login": "trentm",
        "id": 46866,
        "avatar_url": "https://avatars.githubusercontent.com/u/46866?v=3",
        "gravatar_id": "",
        "url": "https://api.github.com/users/trentm",
        "html_url": "https://github.com/trentm",
        "followers_url": "https://api.github.com/users/trentm/followers",
        "following_url": "https://api.github.com/users/trentm/following{/other_user}",
        "gists_url": "https://api.github.com/users/trentm/gists{/gist_id}",
        "starred_url": "https://api.github.com/users/trentm/starred{/owner}{/repo}",
        "subscriptions_url": "https://api.github.com/users/trentm/subscriptions",
        "organizations_url": "https://api.github.com/users/trentm/orgs",
        "repos_url": "https://api.github.com/users/trentm/repos",
        "events_url": "https://api.github.com/users/trentm/events{/privacy}",
        "received_events_url": "https://api.github.com/users/trentm/received_events",
        "type": "User",
        "site_admin": false
      },
      "private": false,
      "html_url": "https://github.com/trentm/json",
      "description": "A \"json\" command for massaging JSON on your Unix command line.",
      "fork": false,
      "url": "https://api.github.com/repos/trentm/json",
      "forks_url": "https://api.github.com/repos/trentm/json/forks",
      "keys_url": "https://api.github.com/repos/trentm/json/keys{/key_id}",
      "collaborators_url": "https://api.github.com/repos/trentm/json/collaborators{/collaborator}",
      "teams_url": "https://api.github.com/repos/trentm/json/teams",
      "hooks_url": "https://api.github.com/repos/trentm/json/hooks",
      "issue_events_url": "https://api.github.com/repos/trentm/json/issues/events{/number}",
      "events_url": "https://api.github.com/repos/trentm/json/events",
      "assignees_url": "https://api.github.com/repos/trentm/json/assignees{/user}",
      "branches_url": "https://api.github.com/repos/trentm/json/branches{/branch}",
      "tags_url": "https://api.github.com/repos/trentm/json/tags",
      "blobs_url": "https://api.github.com/repos/trentm/json/git/blobs{/sha}",
      "git_tags_url": "https://api.github.com/repos/trentm/json/git/tags{/sha}",
      "git_refs_url": "https://api.github.com/repos/trentm/json/git/refs{/sha}",
      "trees_url": "https://api.github.com/repos/trentm/json/git/trees{/sha}",
      "statuses_url": "https://api.github.com/repos/trentm/json/statuses/{sha}",
      "languages_url": "https://api.github.com/repos/trentm/json/languages",
      "stargazers_url": "https://api.github.com/repos/trentm/json/stargazers",
      "contributors_url": "https://api.github.com/repos/trentm/json/contributors",
      "subscribers_url": "https://api.github.com/repos/trentm/json/subscribers",
      "subscription_url": "https://api.github.com/repos/trentm/json/subscription",
      "commits_url": "https://api.github.com/repos/trentm/json/commits{/sha}",
      "git_commits_url": "https://api.github.com/repos/trentm/json/git/commits{/sha}",
      "comments_url": "https://api.github.com/repos/trentm/json/comments{/number}",
      "issue_comment_url": "https://api.github.com/repos/trentm/json/issues/comments{/number}",
      "contents_url": "https://api.github.com/repos/trentm/json/contents/{+path}",
      "compare_url": "https://api.github.com/repos/trentm/json/compare/{base}...{head}",
      "merges_url": "https://api.github.com/repos/trentm/json/merges",
      "archive_url": "https://api.github.com/repos/trentm/json/{archive_format}{/ref}",
      "downloads_url": "https://api.github.com/repos/trentm/json/downloads",
      "issues_url": "https://api.github.com/repos/trentm/json/issues{/number}",
      "pulls_url": "https://api.github.com/repos/trentm/json/pulls{/number}",
      "milestones_url": "https://api.github.com/repos/trentm/json/milestones{/number}",
      "notifications_url": "https://api.github.com/repos/trentm/json/notifications{?since,all,participating}",
      "labels_url": "https://api.github.com/repos/trentm/json/labels{/name}",
      "releases_url": "https://api.github.com/repos/trentm/json/releases{/id}",
      "deployments_url": "https://api.github.com/repos/trentm/json/deployments",
      "created_at": "2011-02-11T00:35:08Z",
      "updated_at": "2016-09-07T16:51:46Z",
      "pushed_at": "2016-06-03T22:24:31Z",
      "git_url": "git://github.com/trentm/json.git",
      "ssh_url": "git@github.com:trentm/json.git",
      "clone_url": "https://github.com/trentm/json.git",
      "svn_url": "https://github.com/trentm/json",
      "homepage": "http://trentm.com/json",
      "size": 1127,
      "stargazers_count": 1014,
      "watchers_count": 1014,
      "language": "JavaScript",
      "has_issues": true,
      "has_downloads": true,
      "has_wiki": true,
      "has_pages": true,
      "forks_count": 70,
      "mirror_url": null,
      "open_issues_count": 26,
      "forks": 70,
      "open_issues": 26,
      "watchers": 1014,
      "default_branch": "master",
      "score": 87.07138
    },
    {
      "id": 17044886,
      "name": "json",
      "full_name": "konklone/json",
      "owner": {
        "login": "konklone",
        "id": 4592,
        "avatar_url": "https://avatars.githubusercontent.com/u/4592?v=3",
        "gravatar_id": "",
        "url": "https://api.github.com/users/konklone",
        "html_url": "https://github.com/konklone",
        "followers_url": "https://api.github.com/users/konklone/followers",
        "following_url": "https://api.github.com/users/konklone/following{/other_user}",
        "gists_url": "https://api.github.com/users/konklone/gists{/gist_id}",
        "starred_url": "https://api.github.com/users/konklone/starred{/owner}{/repo}",
        "subscriptions_url": "https://api.github.com/users/konklone/subscriptions",
        "organizations_url": "https://api.github.com/users/konklone/orgs",
        "repos_url": "https://api.github.com/users/konklone/repos",
        "events_url": "https://api.github.com/users/konklone/events{/privacy}",
        "received_events_url": "https://api.github.com/users/konklone/received_events",
        "type": "User",
        "site_admin": false
      },
      "private": false,
      "html_url": "https://github.com/konklone/json",
      "description": "A free, in-browser JSON to CSV converter.",
      "fork": false,
      "url": "https://api.github.com/repos/konklone/json",
      "forks_url": "https://api.github.com/repos/konklone/json/forks",
      "keys_url": "https://api.github.com/repos/konklone/json/keys{/key_id}",
      "collaborators_url": "https://api.github.com/repos/konklone/json/collaborators{/collaborator}",
      "teams_url": "https://api.github.com/repos/konklone/json/teams",
      "hooks_url": "https://api.github.com/repos/konklone/json/hooks",
      "issue_events_url": "https://api.github.com/repos/konklone/json/issues/events{/number}",
      "events_url": "https://api.github.com/repos/konklone/json/events",
      "assignees_url": "https://api.github.com/repos/konklone/json/assignees{/user}",
      "branches_url": "https://api.github.com/repos/konklone/json/branches{/branch}",
      "tags_url": "https://api.github.com/repos/konklone/json/tags",
      "blobs_url": "https://api.github.com/repos/konklone/json/git/blobs{/sha}",
      "git_tags_url": "https://api.github.com/repos/konklone/json/git/tags{/sha}",
      "git_refs_url": "https://api.github.com/repos/konklone/json/git/refs{/sha}",
      "trees_url": "https://api.github.com/repos/konklone/json/git/trees{/sha}",
      "statuses_url": "https://api.github.com/repos/konklone/json/statuses/{sha}",
      "languages_url": "https://api.github.com/repos/konklone/json/languages",
      "stargazers_url": "https://api.github.com/repos/konklone/json/stargazers",
      "contributors_url": "https://api.github.com/repos/konklone/json/contributors",
      "subscribers_url": "https://api.github.com/repos/konklone/json/subscribers",
      "subscription_url": "https://api.github.com/repos/konklone/json/subscription",
      "commits_url": "https://api.github.com/repos/konklone/json/commits{/sha}",
      "git_commits_url": "https://api.github.com/repos/konklone/json/git/commits{/sha}",
      "comments_url": "https://api.github.com/repos/konklone/json/comments{/number}",
      "issue_comment_url": "https://api.github.com/repos/konklone/json/issues/comments{/number}",
      "contents_url": "https://api.github.com/repos/konklone/json/contents/{+path}",
      "compare_url": "https://api.github.com/repos/konklone/json/compare/{base}...{head}",
      "merges_url": "https://api.github.com/repos/konklone/json/merges",
      "archive_url": "https://api.github.com/repos/konklone/json/{archive_format}{/ref}",
      "downloads_url": "https://api.github.com/repos/konklone/json/downloads",
      "issues_url": "https://api.github.com/repos/konklone/json/issues{/number}",
      "pulls_url": "https://api.github.com/repos/konklone/json/pulls{/number}",
      "milestones_url": "https://api.github.com/repos/konklone/json/milestones{/number}",
      "notifications_url": "https://api.github.com/repos/konklone/json/notifications{?since,all,participating}",
      "labels_url": "https://api.github.com/repos/konklone/json/labels{/name}",
      "releases_url": "https://api.github.com/repos/konklone/json/releases{/id}",
      "deployments_url": "https://api.github.com/repos/konklone/json/deployments",
      "created_at": "2014-02-21T03:54:48Z",
      "updated_at": "2016-09-07T23:39:47Z",
      "pushed_at": "2016-07-21T05:32:16Z",
      "git_url": "git://github.com/konklone/json.git",
      "ssh_url": "git@github.com:konklone/json.git",
      "clone_url": "https://github.com/konklone/json.git",
      "svn_url": "https://github.com/konklone/json",
      "homepage": "http://konklone.io/json/",
      "size": 266,
      "stargazers_count": 312,
      "watchers_count": 312,
      "language": "JavaScript",
      "has_issues": true,
      "has_downloads": true,
      "has_wiki": false,
      "has_pages": true,
      "forks_count": 73,
      "mirror_url": null,
      "open_issues_count": 22,
      "forks": 73,
      "open_issues": 22,
      "watchers": 312,
      "default_branch": "gh-pages",
      "score": 75.97688
    },
    {
      "id": 16427212,
      "name": "json",
      "full_name": "koajs/json",
      "owner": {
        "login": "koajs",
        "id": 5055057,
        "avatar_url": "https://avatars.githubusercontent.com/u/5055057?v=3",
        "gravatar_id": "",
        "url": "https://api.github.com/users/koajs",
        "html_url": "https://github.com/koajs",
        "followers_url": "https://api.github.com/users/koajs/followers",
        "following_url": "https://api.github.com/users/koajs/following{/other_user}",
        "gists_url": "https://api.github.com/users/koajs/gists{/gist_id}",
        "starred_url": "https://api.github.com/users/koajs/starred{/owner}{/repo}",
        "subscriptions_url": "https://api.github.com/users/koajs/subscriptions",
        "organizations_url": "https://api.github.com/users/koajs/orgs",
        "repos_url": "https://api.github.com/users/koajs/repos",
        "events_url": "https://api.github.com/users/koajs/events{/privacy}",
        "received_events_url": "https://api.github.com/users/koajs/received_events",
        "type": "Organization",
        "site_admin": false
      },
      "private": false,
      "html_url": "https://github.com/koajs/json",
      "description": "pretty-printed JSON response middleware",
      "fork": false,
      "url": "https://api.github.com/repos/koajs/json",
      "forks_url": "https://api.github.com/repos/koajs/json/forks",
      "keys_url": "https://api.github.com/repos/koajs/json/keys{/key_id}",
      "collaborators_url": "https://api.github.com/repos/koajs/json/collaborators{/collaborator}",
      "teams_url": "https://api.github.com/repos/koajs/json/teams",
      "hooks_url": "https://api.github.com/repos/koajs/json/hooks",
      "issue_events_url": "https://api.github.com/repos/koajs/json/issues/events{/number}",
      "events_url": "https://api.github.com/repos/koajs/json/events",
      "assignees_url": "https://api.github.com/repos/koajs/json/assignees{/user}",
      "branches_url": "https://api.github.com/repos/koajs/json/branches{/branch}",
      "tags_url": "https://api.github.com/repos/koajs/json/tags",
      "blobs_url": "https://api.github.com/repos/koajs/json/git/blobs{/sha}",
      "git_tags_url": "https://api.github.com/repos/koajs/json/git/tags{/sha}",
      "git_refs_url": "https://api.github.com/repos/koajs/json/git/refs{/sha}",
      "trees_url": "https://api.github.com/repos/koajs/json/git/trees{/sha}",
      "statuses_url": "https://api.github.com/repos/koajs/json/statuses/{sha}",
      "languages_url": "https://api.github.com/repos/koajs/json/languages",
      "stargazers_url": "https://api.github.com/repos/koajs/json/stargazers",
      "contributors_url": "https://api.github.com/repos/koajs/json/contributors",
      "subscribers_url": "https://api.github.com/repos/koajs/json/subscribers",
      "subscription_url": "https://api.github.com/repos/koajs/json/subscription",
      "commits_url": "https://api.github.com/repos/koajs/json/commits{/sha}",
      "git_commits_url": "https://api.github.com/repos/koajs/json/git/commits{/sha}",
      "comments_url": "https://api.github.com/repos/koajs/json/comments{/number}",
      "issue_comment_url": "https://api.github.com/repos/koajs/json/issues/comments{/number}",
      "contents_url": "https://api.github.com/repos/koajs/json/contents/{+path}",
      "compare_url": "https://api.github.com/repos/koajs/json/compare/{base}...{head}",
      "merges_url": "https://api.github.com/repos/koajs/json/merges",
      "archive_url": "https://api.github.com/repos/koajs/json/{archive_format}{/ref}",
      "downloads_url": "https://api.github.com/repos/koajs/json/downloads",
      "issues_url": "https://api.github.com/repos/koajs/json/issues{/number}",
      "pulls_url": "https://api.github.com/repos/koajs/json/pulls{/number}",
      "milestones_url": "https://api.github.com/repos/koajs/json/milestones{/number}",
      "notifications_url": "https://api.github.com/repos/koajs/json/notifications{?since,all,participating}",
      "labels_url": "https://api.github.com/repos/koajs/json/labels{/name}",
      "releases_url": "https://api.github.com/repos/koajs/json/releases{/id}",
      "deployments_url": "https://api.github.com/repos/koajs/json/deployments",
      "created_at": "2014-02-01T02:55:44Z",
      "updated_at": "2016-09-06T09:38:02Z",
      "pushed_at": "2016-04-28T05:32:33Z",
      "git_url": "git://github.com/koajs/json.git",
      "ssh_url": "git@github.com:koajs/json.git",
      "clone_url": "https://github.com/koajs/json.git",
      "svn_url": "https://github.com/koajs/json",
      "homepage": null,
      "size": 20,
      "stargazers_count": 76,
      "watchers_count": 76,
      "language": "JavaScript",
      "has_issues": true,
      "has_downloads": true,
      "has_wiki": true,
      "has_pages": false,
      "forks_count": 6,
      "mirror_url": null,
      "open_issues_count": 1,
      "forks": 6,
      "open_issues": 1,
      "watchers": 76,
      "default_branch": "master",
      "score": 43.774273
    },
    {
      "id": 14747598,
      "name": "json-server",
      "full_name": "typicode/json-server",
      "owner": {
        "login": "typicode",
        "id": 5502029,
        "avatar_url": "https://avatars.githubusercontent.com/u/5502029?v=3",
        "gravatar_id": "",
        "url": "https://api.github.com/users/typicode",
        "html_url": "https://github.com/typicode",
        "followers_url": "https://api.github.com/users/typicode/followers",
        "following_url": "https://api.github.com/users/typicode/following{/other_user}",
        "gists_url": "https://api.github.com/users/typicode/gists{/gist_id}",
        "starred_url": "https://api.github.com/users/typicode/starred{/owner}{/repo}",
        "subscriptions_url": "https://api.github.com/users/typicode/subscriptions",
        "organizations_url": "https://api.github.com/users/typicode/orgs",
        "repos_url": "https://api.github.com/users/typicode/repos",
        "events_url": "https://api.github.com/users/typicode/events{/privacy}",
        "received_events_url": "https://api.github.com/users/typicode/received_events",
        "type": "User",
        "site_admin": false
      },
      "private": false,
      "html_url": "https://github.com/typicode/json-server",
      "description": "Get a full fake REST API with zero coding in less than 30 seconds (seriously)",
      "fork": false,
      "url": "https://api.github.com/repos/typicode/json-server",
      "forks_url": "https://api.github.com/repos/typicode/json-server/forks",
      "keys_url": "https://api.github.com/repos/typicode/json-server/keys{/key_id}",
      "collaborators_url": "https://api.github.com/repos/typicode/json-server/collaborators{/collaborator}",
      "teams_url": "https://api.github.com/repos/typicode/json-server/teams",
      "hooks_url": "https://api.github.com/repos/typicode/json-server/hooks",
      "issue_events_url": "https://api.github.com/repos/typicode/json-server/issues/events{/number}",
      "events_url": "https://api.github.com/repos/typicode/json-server/events",
      "assignees_url": "https://api.github.com/repos/typicode/json-server/assignees{/user}",
      "branches_url": "https://api.github.com/repos/typicode/json-server/branches{/branch}",
      "tags_url": "https://api.github.com/repos/typicode/json-server/tags",
      "blobs_url": "https://api.github.com/repos/typicode/json-server/git/blobs{/sha}",
      "git_tags_url": "https://api.github.com/repos/typicode/json-server/git/tags{/sha}",
      "git_refs_url": "https://api.github.com/repos/typicode/json-server/git/refs{/sha}",
      "trees_url": "https://api.github.com/repos/typicode/json-server/git/trees{/sha}",
      "statuses_url": "https://api.github.com/repos/typicode/json-server/statuses/{sha}",
      "languages_url": "https://api.github.com/repos/typicode/json-server/languages",
      "stargazers_url": "https://api.github.com/repos/typicode/json-server/stargazers",
      "contributors_url": "https://api.github.com/repos/typicode/json-server/contributors",
      "subscribers_url": "https://api.github.com/repos/typicode/json-server/subscribers",
      "subscription_url": "https://api.github.com/repos/typicode/json-server/subscription",
      "commits_url": "https://api.github.com/repos/typicode/json-server/commits{/sha}",
      "git_commits_url": "https://api.github.com/repos/typicode/json-server/git/commits{/sha}",
      "comments_url": "https://api.github.com/repos/typicode/json-server/comments{/number}",
      "issue_comment_url": "https://api.github.com/repos/typicode/json-server/issues/comments{/number}",
      "contents_url": "https://api.github.com/repos/typicode/json-server/contents/{+path}",
      "compare_url": "https://api.github.com/repos/typicode/json-server/compare/{base}...{head}",
      "merges_url": "https://api.github.com/repos/typicode/json-server/merges",
      "archive_url": "https://api.github.com/repos/typicode/json-server/{archive_format}{/ref}",
      "downloads_url": "https://api.github.com/repos/typicode/json-server/downloads",
      "issues_url": "https://api.github.com/repos/typicode/json-server/issues{/number}",
      "pulls_url": "https://api.github.com/repos/typicode/json-server/pulls{/number}",
      "milestones_url": "https://api.github.com/repos/typicode/json-server/milestones{/number}",
      "notifications_url": "https://api.github.com/repos/typicode/json-server/notifications{?since,all,participating}",
      "labels_url": "https://api.github.com/repos/typicode/json-server/labels{/name}",
      "releases_url": "https://api.github.com/repos/typicode/json-server/releases{/id}",
      "deployments_url": "https://api.github.com/repos/typicode/json-server/deployments",
      "created_at": "2013-11-27T13:21:13Z",
      "updated_at": "2016-09-08T13:29:50Z",
      "pushed_at": "2016-08-30T21:09:37Z",
      "git_url": "git://github.com/typicode/json-server.git",
      "ssh_url": "git@github.com:typicode/json-server.git",
      "clone_url": "https://github.com/typicode/json-server.git",
      "svn_url": "https://github.com/typicode/json-server",
      "homepage": "",
      "size": 729,
      "stargazers_count": 16204,
      "watchers_count": 16204,
      "language": "JavaScript",
      "has_issues": true,
      "has_downloads": true,
      "has_wiki": false,
      "has_pages": false,
      "forks_count": 1046,
      "mirror_url": null,
      "open_issues_count": 94,
      "forks": 1046,
      "open_issues": 94,
      "watchers": 16204,
      "default_branch": "master",
      "score": 33.84884
    },
							
						

jQuery AJAX Example

jQuery.getJSON()

							var jqxhr = $.getJSON( "example.json", function() {
  console.log( "success" );
  })
  .done(function() {
    console.log( "second success" );
  })
  .fail(function() {
    console.log( "error" );
  })
  .always(function() {
    console.log( "complete" );
  });
// Perform other work here ...
// Set another completion function for the request above
jqxhr.complete(function() {
  console.log( "second complete" );
});
							
						

HTTP

RFC 7230

“The Hypertext Transfer Protocol (HTTP) is a stateless application- level request/response protocol that uses extensible semantics and self-descriptive message payloads for flexible interaction with network-based hypertext information systems.”

Terms

  • stateless
  • application-level
  • extensible
  • request/response protocol exchanging messages over a reliable transport connection
  • generic interface protocol, independent of the types of resources provided

Message Format

								
	; HTTP/1.1 grammar
	
	HTTP-message   = start-line
			*( header-field CRLF )
			CRLF
			[ message-body ]
	
	start-line     = request-line / status-line
	
	request-line   = method SP request-target SP HTTP-version CRLF
	
	status-line    = HTTP-version SP status-code SP reason-phrase CRLF
	
	header-field   = field-name ":" OWS field-value OWS
							
	message-body   = *OCTET	
								
							

start-line examples

	request-line  = GET /~morses/cs46X/index.html HTTP/1.1 CRLF
						
	status-line   = HTTP/1.1 304 Not Modified CRLF
	
	request-line  = GET /~morses/cs46X/bad.html HTTP/1.1 CRLF
	
	status-line   = HTTP/1.1 404 Not Found CRLF
							

Request Methods

RFC 7231

	+---------+-------------------------------------------------+-------+
	| Method  | Description                                     | Sec.  |
	+---------+-------------------------------------------------+-------+
	| GET     | Transfer a current representation of the target | 4.3.1 |
	|         | resource.                                       |       |
	| HEAD    | Same as GET, but only transfer the status line  | 4.3.2 |
	|         | and header section.                             |       |
	| POST    | Perform resource-specific processing on the     | 4.3.3 |
	|         | request payload.                                |       |
	| PUT     | Replace all current representations of the      | 4.3.4 |
	|         | target resource with the request payload.       |       |
	| DELETE  | Remove all current representations of the       | 4.3.5 |
	|         | target resource.                                |       |
	| CONNECT | Establish a tunnel to the server identified by  | 4.3.6 |
	|         | the target resource.                            |       |
	| OPTIONS | Describe the communication options for the      | 4.3.7 |
	|         | target resource.                                |       |
	| TRACE   | Perform a message loop-back test along the path | 4.3.8 |
	|         | to the target resource.                         |       |
	+---------+-------------------------------------------------+-------+
							

Status Codes

RFC 7231

1xx (Informational)
The request was received, continuing process
2xx (Successful)
The request was successfully received, understood, and accepted

Status Codes (con't)

3xx (Redirection)
Further action needs to be taken in order to complete the request
4xx (Client Error)
The request contains bad syntax or cannot be fulfilled
5xx (Server Error)
The server failed to fulfill an apparently valid request

Status Codes

IANA Status Code Registry

Common Codes

	+------+-------------------------------+--------------------------+
	| Code | Reason-Phrase                 | Defined in...            |
	+------+-------------------------------+--------------------------+
	| 200  | OK                            | Section 6.3.1            |
	| 304  | Not Modified                  | Section 4.1 of [RFC7232] |
	| 400  | Bad Request                   | Section 6.5.1            |
	| 403  | Forbidden                     | Section 6.5.3            |
	| 404  | Not Found                     | Section 6.5.4            |
	| 500  | Internal Server Error         | Section 6.6.1            |
	| 503  | Service Unavailable           | Section 6.6.4            |
	+------+-------------------------------+--------------------------+
							

Request Header Fields

RFC 7231 Section 5

“A client sends request header fields to provide more information about the request context, make the request conditional based on the target resource state, suggest preferred formats for the response, supply authentication credentials, or modify the expected request processing. These fields act as request modifiers, similar to the parameters on a programming language method invocation.”

Response Header Fields

RFC 7231 Section 7

“The response header fields allow the server to pass additional information about the response beyond what is placed in the status-line. These header fields give information about the server, about further access to the target resource, or about related resources.”

Examples

Wikipedia

Use developer tools in a browser

Use command line tools, i.e. curl

Important Topics

Cacheable Methods

“Request methods can be defined as "cacheable" to indicate that responses to them are allowed to be stored for future reuse ... this specification defines GET, HEAD, and POST as cacheable, although the overwhelming majority of cache implementations only support GET and HEAD”

Safe Methods

			GET     HEAD     OPTIONS     TRACE
								

“Request methods are considered "safe" if their defined semantics are essentially read-only; i.e., the client does not request, and does not expect, any state change on the origin server as a result of applying a safe method to a target resource. Likewise, reasonable use of a safe method is not expected to cause any harm, loss of property, or unusual burden on the origin server.”

Idempotent Methods

			PUT     DELETE     GET     HEAD     OPTIONS     TRACE
									

“A request method is considered "idempotent" if the intended effect on the server of multiple identical requests with that method is the same as the effect for a single such request.”

Misc

  • GET and HEAD requests don't have a body
  • GET and HEAD should have no side effects
  • Header fields are extensible
  • Methods are extensible
  • HTTP defaults to TCP port 80

RESTful Web Interface

Representational State Transfer

REST is the architectural style of the Web

“The name 'representational state transfer' is intended to evoke an image of how a well-designed Web application behaves: a network of web pages (a virtual state-machine), where the user progresses through the application by selecting links (state transitions), resulting in the next page (representing the next state of the application) being transferred to the user and rendered for their use.”

A good examples

Lyft API (docs)

PayPal REST API

How can a website ...

  • remember who a visitor is?
  • require a password to see a page?
  • acquire user data from forms?
  • maintain state information?
  • Respond to user input dynamically?

Through HTTP and the browser

Details and specifics will come later