Introduction
There was a time when XMLHttpRequest
was used to make API requests. It didn't include promises and it didn't allow for clean JavaScript code. When using jQuery, the cleanest syntax was used with jQuery.ajax ()
.
Now JavaScript has its own built-in way of making API requests. This is the Fetch API, a new standard for making server requests with promises, but it includes many other functions.
In this tutorial, you will create GET and POST requests using the Fetch API.
Prerequisites
To complete this tutorial, you will need the following:
- The latest version of Node installed on your computer.
- A basic understanding of JavaScript coding
- An understanding of promises in JavaScript.
Step 1: Introduction to the Fetch API syntax
To use the Fetch API, invoke the fetch
method, which accepts the API URL as a parameter:
fetch (url)
After the fetch()
method, include the then()
promise method:
. then(function () {
})
With the fetch()
method you get a promise. If the returned promise is resolve
, the function is executed inside the then()
method. That function contains the code to manage the data received from the API.
Below the then()
method, include the catch()
method:
. catch (function () {
});
The API that you invoked using fetch ()
may be down or other errors may occur. If this happens, the reject
promise will be displayed. The catch
method is used to handle reject
. The code inside catch ()
will be executed if an error occurs when invoking the API of your choice.
To summarize, using the Fetch API will look like this:
fetch (url)
.then (function () {
})
.catch (function () {
});
With a knowledge of the syntax for using the Fetch API, you can now continue to use fetch ()
in a true API.
Step 2: Use Fetch to get data from an API
The following code samples will be based on the REQ | RES . By using the API, you will get ten users and they will be displayed on the page using Vanilla JavaScript.
The idea is to get all the data from the Random User API and display it in the list elements within the author's list. First create an HTML file and add a header and an unordered list with the id
of Users:
<h1> Users </h1>
<ul id = "users"> </ul>
Now, add the script
tags to the bottom of your HTML file and use a DOM selector to capture the ul
. Use getElementById
with Users
as an argument. Remember that Users
is the id
for the ul
created earlier:
<script>
const ul = document.getElementById ('users');
</script>
Create a constant variable called url
that will hold the URL of the API that will display ten random users:
const url = 'https://reqres.in/api/users?per_page=10';
Having already set ul
and url
, it is time to create the functions that will be used to create the list items. Create a function called createNode
that takes a parameter called element
:
function createNode (element) {
}
Later, when createNode
is invoked, you will need to pass the name of an actual HTML element to create.
Inside the function, add the return
statement that returns the element
using document.createElement ()
:
function createNode (element) {
return document.createElement (element);
}
You will also need to create a function called append
that takes two parameters: parent
and el
:
function append (parent, el) {
}
This function will add the
to parent
using document.createElement
:
function append (parent, el) {
return parent.appendChild (el);
}
Both CreateNode
and append
are ready to go. Now using the Fetch API, invoke the Random User API using fetch ()
with url
as argument:
fetch (url)
.then (function (data) {
})
})
.catch (function (error) {
});
In the above code, you are invoking the Fetch API and passing the URL to the Random User API. Then a reply is received. However, the response that is obtained is not JSON, but an object with a series of methods that can be used depending on what you want to do with the information. To convert the returned object to JSON, use the json ()
method.
Add the then ()
method that will contain a function with a parameter called resp
:
fetch (url)
.then ((resp) =>)
The resp
parameter takes the value of the object returned from fetch (url)
. Use the json ()
method to convert resp
to JSON data:
fetch (url)
.then ((resp) => resp.json ())
JSON data still needs to be processed. Add another then ()
statement with a function that has an argument named data
:
. then (function (data) {
})
})
Inside this function, create a variable called Users
that is set equal to data.data
:
. then (function (data) {
let users = data.data;
For each author in Users
, you will want to create a list item that displays an image of them and displays their name. The map ()
method works great for this:
let users = data.data;
return users.map (function (u) {
})
With your map
function, create a variable called li
that will be set equal to createNode
with li
(the HTML element) as argument:
return users.map (function (u) {
let li = createNode ('li');
})
Repeat this to create a span
element and an img
element:
let li = createNode ('li');
let img = createNode ('img');
let span = createNode ('span');
The API provides a name for the author and an image to accompany the name. Set img.src
to author image:
let img = createNode ('img');
let span = createNode ('span');
img.src = u.avatar;
The span
element must contain the first name and last name of the author
. The innerHTML
property and string interpolation will allow you to do this:
img.src = u.avatar;
span.innerHTML = `$ {u.first_name} $ {u.last_name}`;
With the image and list element already created along with the span
element, you can use the append
function that was created earlier to display these elements on the page:
append (li, img);
append (li, span);
append (ul, li);
After both then ()
functions complete, you can add the catch ()
function. This function will log the possible error in the console:
. catch (function (error) {
console.log (error);
});
This is the complete code for the request you created:
function createNode (element) {
return document.createElement (element);
}
function append (parent, el) {
return parent.appendChild (el);
}
const ul = document.getElementById ('users');
const url = 'https://reqres.in/api/users?per_page=10';
fetch (url)
.then ((resp) => resp.json ())
.then (function (data) {
let users = data.data;
return users.map (function (u) {
let li = createNode ('li');
let img = createNode ('img');
let span = createNode ('span');
img.src = u.picture.medium;
span.innerHTML = `$ {u.first_name} $ {u.last_name}`;
append (li, img);
append (li, span);
append (ul, li);
})
})
.catch (function (error) {
console.log (error);
});
You just made a successful GET request using the Random User API and the Fetch API. In the next step, you will learn how to make POST requests.
Step 3: Manage POST requests
Fetch is finely tuned for GET requests, but it can use all other types of requests, change headers, and send data. To do this, you must set your object and pass it as the second argument to the fetch function.
Before creating a POST request, create the data that you want to send to the API. This will be an object called data
with the key name
and the value Morpheus
(or your name):
const url = 'https://reqres.in/api/users/';
let data = {
name: 'Morpheus',
"job": "leader"
}
Make sure to include a constant variable that contains the Random User API binding.
Since this is a POST request, you must explicitly indicate this. Create an object called fetchData
:
let fetchData = {
}
This object must include three keys: method
, body
, and headers
. The method
key must have the value 'POST'
. body
must be set equal to the data
object you just created. headers
must have the value of new Headers ()
:
let fetchData = {
method: 'POST',
body: data,
headers: new Headers ()
}
The Headers
interface is a property of the Fetch API, which allows you to perform various actions on the headers of HTTP requests and responses
Once this code is set, the POST request can be made using the Fetch API. It will include url
and fetchData
as arguments for your POST request fetch
:
fetch (url, fetchData)
The then ()
function will include the code that handles the response received from the Random User API server:
fetch (url, fetchData)
.then (function () {
// Handle response you get from the server
});
To create an object and use the fetch ()
function, there is also another option. Instead of creating an object like fetchData
, you can use the request constructor to create your request object. To do this, create a variable called request
:
const url = 'https://reqres.in/api/users/';
let data = {
name: 'Morpheus',
"job": "leader"
}
var request =
The request
variable must be set equal to new Request
. The new Request
construct includes two arguments: the API url ( url
) and an object. The object must also include the method
, body
, and headers
keys, as well as fetchData
:
var request = new Request (url, {
method: 'POST',
body: data,
headers: new Headers ()
});
Now request
can be used as the only argument to fetch ()
, as it also includes the API URL:
fetch (request)
.then (function () {
// Handle response we get from the API
})
In its entirety, your code will look like this:
const url = 'https://reqres.in/api/users/';
let data = {
name: 'Morpheus',
"job": "leader"
}
var request = new Request (url, {
method: 'POST',
body: data,
headers: new Headers ()
});
fetch (request)
.then (function () {
// Handle response we get from the API
})
You now know of two methods for creating and executing POST requests with the Fetch API.
Conclusion
Although the Fetch API is not yet supported by all browsers, it is a great alternative to XMLHttpRequest.
And with those friends we reached the end of the tutorial, I hope you enjoyed it and until next time! |