JavaScript: Fetch Requests

This is the anatomy of a fetch request:

1// A
2async function createUser1() {
3  var newUser = {
4    firstName: "John"
5    lastName: "Doe"
6  }
7
8  //               B                      C
9  var response = await fetch("https://domain.com/users",
10    {
11      method: "POST", // D
12      headers: { 'Content-Type': 'application/json' }, // E
13      body: JSON.stringify(newUser) // F
14    }
15  )
16
17  var data = await response.json() // G
18
19  console.log(data)
20}
21
22/*
23  A: Because this request has to travel through the Internet,
24     reach a server, do some processing, and then return the
25     reponse all the way back to the user's browser, this
26     needs to be declared an asynchronous process. We don't
27     know how long this request is going to take to finish
28
29  B: This fetch request is the asynchronous part, so the await
30     keyword instructs the computer to begin waiting here
31
32  C: The URL where we are sending the request to
33
34  D: The HTTP method. We'll be using: GET, POST, PUT, DELETE
35
36  E: Specifying the Content-Type, so the server that receives
37     this quest can be informed that we're sending data in
38     the JSON format
39
40  F: This converts the JSON object to a String format before
41     sending the data
42
43  G: This formats the response back into a JSON object and
44     stores it in a variable
45*/

Examples

Get User 1

1async function getUser1() {
2  var response = await fetch("/users/1", { method: "GET" })
3
4  var data = await response.json() // Converts response to JSON
5
6  console.log(data)
7}
8
9getUser1() // Prints: { "firstName": "John", "lastName": "Doe" }

Get User 2

1async function getUser2() {
2  var response = await fetch("/users/2", { method: "GET" })
3
4  var data = await response.json() // Converts response to JSON
5
6  console.log(data)
7}
8
9getUser2() // Prints: { "firstName": "Jane", "lastName": "Doe" }

Get User w/ Parameter

1async function getUser(id) {
2  var response = await fetch("/users/" + id, { method: "GET" })
3
4  var data = await response.json() // Converts response to JSON
5
6  console.log(data)
7}
8
9getUser(2) // Prints: { "firstName": "Jane", "lastName": "Doe" }

Get All Users

1async function getUsers() {
2  var response = await fetch("/users", { method: "GET" })
3
4  var data = response.json(); // Converts response to JSON
5
6  console.log(data)
7}
8
9getUsers()
10// Prints: { "firstName": "John", "lastName": "Doe" }, { "firstName": "Jane", "lastName": "Doe" }

Get All Users From External Domain

1async function getUsers() {
2  var response = await fetch("https://domain.com/users", { method: "GET" })
3
4  var data = response.json(); // Converts response to JSON
5
6  console.log(data)
7}
8
9getUsers()
10// Prints: { "firstName": "Chad", "lastName": "Smith" }, { "firstName": "Karen", "lastName": "Smith" }

Create New User 1

1async function createUser1() {
2  var newUser = {
3    firstName: "John"
4    lastName: "Doe"
5  }
6
7  var response = await fetch("/users",
8    {
9      method: "POST",
10      headers: { 'Content-Type': 'application/json' },
11      body: JSON.stringify(newUser)
12    }
13  )
14
15  var data = await response.json()
16
17  console.log(data)
18}
19
20createUser1() // Prints: { "msg": "User created successfully" }

Create New User 2

1async function createUser2() {
2  var newUser = {
3    firstName: "Jane"
4    lastName: "Doe"
5  }
6
7  var response = await fetch("/users",
8    {
9      method: "POST",
10      headers: { 'Content-Type': 'application/json' },
11      body: JSON.stringify(newUser)
12    }
13  )
14
15  var data = await response.json()
16
17  console.log(data)
18}
19
20createUser() // Prints: { "msg": "User created successfully" }

Create New User w/ Param

1async function createUser(newUser) {
2  var response = await fetch("/users",
3    {
4      method: "POST",
5      headers: { 'Content-Type': 'application/json' },
6      body: JSON.stringify(newUser)
7    }
8  )
9
10  var data = await response.json()
11}
12
13var newUser = {
14  firstName: "Chad"
15  lastName: "Smith"
16}
17
18createUser(newUser) // Prints: { "msg": "User created successfully" }

Update User w/ Param

1async function updateUser(user) {
2  var response = await fetch("/users/1",
3    {
4      method: "PUT",
5      headers: { 'Content-Type': 'application/json' },
6      body: JSON.stringify(newUser)
7    }
8  )
9
10  var data = await response.json()
11}
12
13var user = {
14  firstName: "John"
15  lastName: "Blah"
16}
17
18updateUser(user) // Prints: { "msg": "User updated successfully" }

Destroy User w/ ID Param

1async function destroyUser(id) {
2  var response = await fetch("/users/" + id, { method: "DELETE" })
3
4  var data = await response.json()
5}
6
7destroyUser(1) // Prints: { "msg": "User destroyed successfully" }

Fetch requests, in effect, allow us to execute functions in someone else's application. Here's some examples:

  • Maybe the app is primarily an interface to store/fetch data to/from a database
  • Or maybe the application receives data, and generates a PDF for you to download, so you don't have to write that code