Mod 1 > Week 1 > Day 1

At the end of this module you will be building a RESTful API that has both authentication and authorisation. We are going to build up to this final challenge in a gradual way. Our jouney will begin today with the building block of RESTful APIs - the Hyper Text Transfer Protocol (HTTP).

Pre-work

To get the most out of this module, make sure you watch this video

Pay close attention - you'll be quizzed.

If you're not comfortable with async JavaScript, callbacks and promises, make sure you study and practice these before arriving at the bootcamp. They'll be important for many of the exercises.

Overview of the day

We are going to use Postman to call some RESTful APIs and look in detail at the requests we send and responses we receive. Then we will look at performing these same requests using the browser's native fetch api.


Lesson 1 - The Anatomy of HTTP

Learning Objectives

Before we start

Materials needed

HTTP slides

Lesson

HTTP stands for the 'hyper text transfer protocol'. It is a protocol or 'way of doing things' which means if you meet a standard set of requirements you can implement HTTP in any language. Lets have a look at what goes into an HTTP request:

Method (Verb)

The method part of HTTP helps to communicate what this request is trying to do. The most commonly used verbs are GET & POST.

Method Function
GET to retrieve data
POST to create data
PUT to replace data
PATCH to update data
DELETE to remove data

❓ Can you see how to select these in postman?

Protocol

This is the part at the very beginning of the request. http:// this tells the browser we are making an http request. Protocols you might come across are:

Host

This is the address or place on the internet we are trying to reach. The host address (sometimes referred to as the domain address) of the HTTP request forms the main part of the address.

Path

This comes after the host address. This is the part of the address that is subject to the RESTful pattern. If we want to get all the albums from spotify then we would use the following address.

https://api.spotify.com/v1/albums

Parameters

There are often variables that contribute toward a RESTful address. These are called parameters if they are included in the path. In the example above if we include the id number at the end of the path, we will be returned the album with that id. The id can be different and will relate to the resource that we want to access. In the example below we can compose an address using the album id 12345, but if we wanted a different album we can change this.

https://api.spotify.com/v1/albums/12345

❓ What is the difference between the path and parameters?

Query parameters

Query parameters can be added to the end of an address. Adding a ? at the end of an address indicates that the following string is a list of key value pairs. In the example below after the '?' you should see a 'key' artist an equals = and then the 'value' Frank%20Zappa that makes a key=value pair. Look for the ampersand & that separates the key value pairs. Query parameters must be encoded so there are no special characters or spaces. This encoding is called URIEncoding the best API in the browser to use for this is window.encodeURIComponent.

"?artist=Frank Zappa&album=Hot Rats&track=Peaches Èn Ragalia"; // not URI encoded
window.encodeURIComponent("Peaches Èn Ragalia"); // returns Peaches%20%C3%88n%20Ragalia
("?artist=Frank%20Zappa&album=Hot%20Rats&track=Peaches%20%C3%88n%20Ragalia"); // safe query string

All this extra information will be included in the HTTP request. Query strings have a maximum size limit (specific to the browser) and therefore aren’t good for transmitting a large amount of information

❓ What are the 2 ways we can pass data in an HTTP request?

❓ What is the difference between a parameter and a query parameter?

Body

All HTTP requests can have a body. The body can contain different flavors of encoded data. In the table below you can see the following data encoded in different flavors:

{
    artist: "Frank Zappa",
    album: "Hot Rats",
    track: "Peaches Èn Ragalia"
}
flavor encoding
form-data artist=Frank+Zappa&album=Hot+Rats...
x-www-form-urlencoded artist=Frank%20Zappa&album=Hot%20Ra...
JSON string "{"artist":"Frank Zappa","album":"Hot Rats","track":"Peaches Èn Ragalia"}"
XML "<?xml version="1.0" encoding="UTF-8"?><root><artist>Frank Zappa</artist><album>Hot Rats</album><track>Peaches Èn Ragalia</track></root>"

There are more kinds of encoding for example binary which is for files but this is enough to be getting on with.

Header

The header is a very important part of the HTTP request. In the header you can pass all manor of meta information about the request. We will be putting authentication credentials in the header later on. For now we can focus on the Content-Type. Considering there are different ways we can encode the body content, we need to have a matching header that tells the receiver how to decode our body content. Without the body and Content-Type matching the server may error with a 406 "Not Acceptable" status code (we will look at status codes later).

Here is a list of all the different Content-Types that are supported: https://www.iana.org/

❓ In postman can you see where to set a header?

❓ Can you match the correct content types to the table of encodings above?

Response

The response object is similar to the request object. The main difference is a response will have a status code property. It is the responsibility of the developers building and maintaining a service to set the correct status code for a response before sending it back to the client.

Range Status
100 - 103 Informational response
200 - 226 Success
300 - 308 Redirection
400 - 451 Client Errors
500 - 598 Server Errors

You don't need to learn all the status codes (they're easy to Google) but knowing what in general a 2xx, 4xx or 5xx means is helpful.

Assignment

Below is a URL. Can you make an HTTP request to that URL using postman? Read the instructions that you get back from the server as each response is a different challenge piece that will lead to a final puzzle on https://applied.multiverse.io.

  1. Make a GET request to https://http-challenge.multiverse-coaches.io/
  2. Follow the instructions you receive from the response

Lesson 2 - Browser API calls with fetch

In this session we are just going to make sure everyone is comfortable using fetch in the browser to form more advanced HTTP requests. As well as using a tool like postman, we also want you to know how to send HTTP requests in your client-side javascript code.

Learning Objectives

Before we start

Create a new .html file with a script tag, write your code in the script tag.

Materials needed

Lesson

Postman is a great tool, very useful for working with new APIs. In this session we are going to learn to do the things we did with postman using the Promise based fetch API in the browser.

fetch(`https://api.thesneakerdatabase.com/v1/sneakers?limit=10`);

This is the most basic usage, thats a GET request (by default) to the address passed as an argument. We don't deal with the response. The response is async and is a raw response object.

fetch(`https://api.thesneakerdatabase.com/v1/sneakers?limit=10`).then((res) =>
    console.table(res)
);

the response object

❓ Can you see the status code?

❓ Are there any headers?

To parse the response into a more friendly JSON object we can call res.json() then we can access our data in a convenient format.

fetch(`https://api.thesneakerdatabase.com/v1/sneakers?limit=10`)
    .then((res) => res.json())
    .then((res) => console.log(res));

data from the response

Headers

We are going to be working with the headers of our requests so lets have a look at setting headers in the fetch API. Below we are going to POST some data to our endpoint like we did earlier with postman.

const url = "https://http-challenge.multiverse-coaches.io/apprentices";
const payload = {
    name: "Frank Zappa",
};
fetch(url, {
    method: "POST",
    headers: {
        "Content-Type": "application/json",
    },
    body: JSON.stringify(payload),
})
    .then((res) => res.text())
    .then((msg) => {
        const [yourId] = msg.match(/(?<=\/)[a-zA-Z0-9]+(?=')/);
        console.log(yourId, msg);
    })
    .catch(console.error);

Assignment

Can you repeat the calls that we made earlier to https://http-challenge.multiverse-coaches.io/ only this time have a script in an index.html page that opens in your browser, and makes use of fetch to make each call in sequence. You will need to retrieve the 'Your-Id' from the initial GET request and use it in the subsequence requests. Push your code to github and share a link to your repo with your coach.

🤷🏽‍♂️ Tips

const [yourId] = msg.match(/(?<=\/)[a-zA-Z0-9]+(?=')/);

Assignment Extension

Instead of your index.html simply being a page to load your javascript into, make it an actual interactive webpage. Use html inputs and event handlers to allow a user visiting your website to complete the html challenge with their own answers.

attendance log main|prev|next