General Assembly

Ajax & APIs

Wilson Espina

Review

What did we do last lesson?

Ajax & APIs

Learning Objective

Learning Objectives

At the end of this class, you will be able to:

  • Describe APIs and how to make calls and consume API data.
  • Intro to AJAX.
  • Access public APIs and get information back.
  • Implement an Ajax request with Fetch.
  • Create an Ajax request using jQuery.

Ajax & APIs

Agenda

  • Homework Review
  • Web Services
  • APIs
  • HTTP Refresher
  • Understanding Rest APIs
  • AJAX

Ajax & APIs

Homework Review

Ajax & APIs

Classroom Resources

  • Pull changes from the wilson-espina/jsd-9-resources repo to your computer
  • In your editor, open the following folder: Documents/JSD/jsd-9-resources/10-ajax-apis

Web Services

Ajax & APIS

Scope & Variables

Key Terms:

  • APIs: (Application Programming Interfaces) are used to provide functionality from a server in a specific manner using a simplified syntax.
  • Web Services allow two or more applications built on various programming languages to communicate with each other via the World Wide Web.
  • HTTP (HyperText Transfer Protocol) is the protocol (set of rules) used by the World Wide Web. It defines how messages are formatted and transmitted, and what actions Web servers and browsers should take in response to various commands.

Ajax & APIS

Web Services

Ajax & APIS

Web Services

A Web Service is a resource that’s made available over the internet.

  • Allows us to get data from external servers that we can incorporate into our web site or app.
  • Web services require a network.

Ajax & APIS

Web Services

AirBnb API

Ajax & APIS

Web Services

Web Services
  • Your app can incorporate data from the response from the Web Service.

Ajax & APIS

Open Web Services Examples

Web Services Examples

Web Services may be written in a variety of languages. They expose data via their APIs and communicate via the same protocols used for the World Wide Web.

Ajax & APIS

APIs

Ajax & APIS

API

API diagram

An API is the code that governs the access point(s) for the server.

Ajax & APIS

Web Service API

TFL API 1

Ajax & APIS

Web Service API

TFL API 2

Ajax & APIS

Endpoints

TFL endpoints

Ajax & APIS

Storing Data

  • When data is persisted, it is stored so that it can be accessed even after a program has completed. Usually, we mean storing the data in a database.
  • In computer programming, create, read, update, and delete (CRUD) are the four basic functions of persistent storage.
Database

Ajax & APIS

What we need to know to use an API

API what to know

Ajax & APIS

An API might require authentication

API who is this

Ajax & APIS

API Key

  • Non-guessable character string generated by a cryptography algorithm.
API key

Ajax & APIS

API Request with authorisation

API success

Ajax & APIS

Keep your API credentials private

API key
  • Don’t post to a public code repo.
  • Don't share with other developers outside of your organisation.
  • Don't leave you API key in a code comment!

Ajax & APIS

Your app might experience a delayed response

Facebook

Ajax & APIS

Your request may result in an error

API error

Code along

Lab - Practice with APIs

Exercise

Type of Exercise

  • Pairs

Location

  • Rick and Morty API

Timing

10 mins

  1. Go to: https://rickandmortyapi.com/documentation/#get-all-characters
  2. Review the documentation for Get all characters.
  3. Together with your partner, answer the following questions:
    • What is the endpoint that is used to return all of the characters?
    • How would you access the individual character's names?
    • Write pseudocode to retrieve the characters and append the names of each to an unordered list on your page.

Ajax & APIs

HTTP

Ajax & APIS

HTTP (hypertext transfer protocol)

  • System of rules for how web pages are transmitted between computers.
  • Defines the format of messages passed between HTTP clients and HTTP servers.
Client server

Ajax & APIS

HTTP (hypertext transfer protocol)

  • Client sends a request to the server.
  • Server sends a response back to a client.
Request response cycle

Ajax & APIS

Anatomy of a URL

Anatomy of URL

Ajax & APIS

HTTP Request and Response

HTTP Request response cycle

Ajax & APIS

HTTP (hypertext transfer protocol)

HTTP examples

Ajax & APIS

HTTP Request Structure

HTTP structure

Ajax & APIS

HTTP Request Methods ("HTTP Verbs")

HTTP VERB OPERATION

GET

Retrieve a new resource

POST

Create a new resource

PUT

Replace a resource

PATCH

Update an existing resource

DELETE

Delete a resource resource

Ajax & APIS

HTTP Request Methods ("HTTP Verbs")

HTTP VERB OPERATION

GET

Retrieve a new resource

POST

Create a new resource

PUT

Replace a resource

PATCH

Update an existing resource

DELETE

Delete a resource resource

  • GET and POST are most widely used.

Ajax & APIS

HTTP Response Structure

HTTP response structure

Code along

Ajax & APIS

HTTP Status Codes

404 examples

Ajax & APIS

HTTP Status Codes

CATEGORY RESPONSE CLASS COMMON EXAMPLES

2xx

Success

200 OK

201 Created

204 No Content

3xx

Redirection

301 Moved Permanently

302 Found (Moved temporarily)

4xx

Client Error

400 Bad Request

401 Unauthorized

404 Not Found

5xx

Server Error

500 Internal Server Error

Code along

Code Along
Code Along

Ajax & APIS

Understanding REST APIs

Ajax & APIS

RESTful APIs

  • REST, or Representational State Transfer, is an architectural style of Web Service APIs.
  • REST APIs use HTTP, the underlying protocol used by the World Wide Web, as the transport for messages between the client and server.
  • REST is a design pattern, a suggested way of organising the design of your application. It is not a rule like HTTP protocol.

Ajax & APIS

7 Restful Routes

When requesting information about a resource from an application, RESTful design patterns dictate that you should be able to do 7 key actions.

We call these the 7 restful routes and they are created by combining:

  • URL
  • HTTP Verb (in the HTTP Request)
  • Action

Ajax & APIS

7 Restful Routes

Consider the following 7 RESTFUL routes for requesting a resource of photos.

Photos site

Ajax & APIS

7 Restful Routes

URL HTTP VERB Action Result

/photos/

GET

Index

Display all photos

/photos/new

GET

New

Show a form to upload a new photo

/photos/create

POST

Create

Add a new photo to database, then redirect

/photos/:id

GET

Show

Show info about one photo

/photos/:id/edit

GET

Edit

Show edit for for one photo

/photos/:id

PUT

Update

Update a particular photo, then redirect

/photos/:id

DELETE

Destroy

Destroy a particular photo, then redirect

Ajax & APIS

Ajax

Ajax & APIS

AJAX

  • Asyncronous
  • JavaScript
  • And
  • XML (or JSON)

Ajax & APIS

AJAX

  • AJAX is a method of building interactive applications for the Web that processes user requests immediately, without re-rendering a whole page.
Interactive website

Ajax & APIS

AJAX - Advantages 😀

  • FASTER - AJAX allows easier and quicker interaction between user and website as pages are not reloaded for content to be displayed.
  • COMPACT - With AJAX, several application features can be handled using a single web page.
  • BACKEND SEPARATED FROM FRONTEND - Applications that use AJAX-heavy frontends means developers don't have to work on both sides of the stack at the same time.

Ajax & APIS

AJAX - Disadvantages 🙁

  • JAVASCRIPT CAN BE DISABLED - Some website users prefer to turn javascript functionality off on their browser, rendering the AJAX application totally useless.
  • MORE RELIANT ON UX - The fact that a page doesn't refresh means you have to be even more considerate of what a user is experiencing.

Ajax & APIS

Vanilla JavaScript Ajax

Ajax & APIS

FETCH = Ajax request in vanilla JavaScript


fetch(url)
    .then((response) => {
	  if (!response.ok) throw Error(response.statusText);
	  return response.json();
    })
    .then((responseData) => {
	  const data = JSON.stringify(responseData);
	  // do something with the data
    });
							

Code along

Code Along

Open up: 01-fetch-ajax-codealong

Code Along

Ajax & APIS

jQuery Ajax

Ajax & APIS

jQuery AJAX Method

METHOD DESCRIPTION

$.get()

Retrieve a new resource

$.ajax()

Create a new resource

Code along

Code Along

Open up: 01-fetch-ajax-codealong

Code Along

Lab - JQUERY AJAX

Exercise

Objective

  • Create an Ajax request using jQuery or Fetch.

Location

  • 02-fetch-ajax-exercise

Timing

10 mins

  1. Copy the code from the codealong to the main.js file.
  2. Change the URL to the one shown in the instructions.
  3. Verify that a new set of results is shown in the console.
  4. BONUS - Read the instruction in main.js for bonus tasks.

Ajax & APIS

Learning Objective

Learning Objectives - Review

  • Describe APIs and how to make calls and consume API data.
  • Understand API calls.
  • Consuming and working with API data.
  • Intro to AJAX.
  • Access public APIs and get information back.
  • Implement an Ajax request with Fetch.
  • Create an Ajax request using jQuery.

Ajax & APIS

Look Ahead to Next Lesson

  • Describe what asynchronous means in relation to JavaScript
  • Pass functions as arguments to functions that expect them.
  • Write functions that take other functions as arguments.
  • Build asynchronous program flow using Fetch

Ajax & APIS

Exit Ticket

(Lesson #10)