Did you know that you can make web requests in vanilla JavaScript? That’s right, you don’t need to install any libraries to make a web request. That’s not all: we’re not talking about the old, complex XMLHttpRequest tool.
The fetch API allows you to make Ajax requests in plain old JavaScript. It’s a useful tool for retrieving data and making changes to data on a web server.
In this guide, we’re going to discuss what the fetch API is and how you can make web requests using the API. We’ll talk through two examples: a GET request and a POST request.
What Is the Fetch API?
JavaScript has been capable of sending network requests for a long time now. The XMLHTTPRequest tool provided the resources you needed to retrieve data from a server and update information from a server.
While this tool was effective, it was also quite verbose and complicated to use. Fetch, on the other hand, is a new alternative which makes it simpler to make web requests.
The fetch API is supported in all modern browsers. This means that once you learn how to use it, you will not have to worry about browser compatibility when making web requests.
How to Make a GET Request Using Fetch
The best way to illustrate how fetch works is by example. For this tutorial, we’re going to use the web service JSONPlaceholder. This is an API that comes with pre-written dummy data that we can use to test out our web requests.
The following code creates a GET request to retrieve the first post from JSONPlaceholder:
fetch('https://jsonplaceholder.typicode.com/posts/1') .then(response => response.json()) .then(json => console.log(json))
This code returns:
{ body: "quia et suscipit suscipit recusandae consequuntur expedita et cum reprehenderit molestiae ut ut quas totam nostrum rerum est autem sunt rem eveniet architecto", id: 1, title: "sunt aut facere repellat provident occaecati excepturi optio reprehenderit", userId: 1 }
Let’s break down our code. On the first line, we have used the fetch()
method to initiate a web request to the JSONPlaceholder API. We’ve then used the .then()
method to tell our code what to do after our web request has been made.
In our first .then()
method, we convert the response returned by the API into JSON. This makes our data more readable. We use another .then()
method to log the response to the console. This shows us the post with the ID 1 from the JSONPlaceholder API.
How to Make a POST Request
GET is not the only request type you can make with the fetch API. There’s also functionality that supports POST, PUT, and DELETE requests. The syntax for these is the same, so we’re just going to walk through one example: how to make a POST request.
When you’re making a POST, PUT, or DELETE request, there are usually three pieces of information you need to specify:
- The URL to which you are making the request.
- The method you are using to make the request (in this case, POST)
- The data you want to send to the server
Here’s a code snippet that would create a new comment using the JSONPlaceholder API:
const data = { name: "Leslie Tudor", email: "leslie.tudor@email.com", body: "This is an example post by Career Karma!", postId: 1 } const options = { method: "POST", body: JSON.stringify(data), headers: { "Content-Type": "application/json" } }; fetch('https://jsonplaceholder.typicode.com/comments', options) .then(response => response.json()) .then(json => console.log(json))
Our code returns our newly-created post in JSON format:
{ body: "This is an example post by Career Karma!", email: "leslie.tudor@email.com", id: 501, name: "Leslie Tudor", postId: 1 }
In our code, we first declare a data object. This stores the data that we want to send over to the server. In this case, we are sending over data about a comment made by a user called Leslie Tudor.
We then declare another object which stores the options that are associated with our fetch request. This object specifies the method we are using to make our request (POST), the data we want to send, as well as the headers we want to send.
Finally, we use the fetch()
method to actually make our request. Like in our first example, we use .then()
methods to retrieve the response, convert it to JSON, then print it to the console.
How to Handle Errors Using JavaScript Fetch
It’s an unfortunate fact that some web requests don’t work as intended. Maybe the data is structured incorrectly, or maybe there is a server issue. It’s important that we anticipate these events upfront so that we can handle them if and when they arise.
There’s a method called .catch()
which you can use to catch any errors that have been returned by your code. Combined with the Promise.reject()
method, you can use it to handle errors:
fetch('https://jsonplaceholder.typicode.com/comments/999, options) .then(response => { if (response.ok) { console.log(response.json()); return response.json(); } else { return Promise.reject({ statusText: response.statusText }) } }) .catch(error => console.log("ERROR:", error.statusText));
This code returns:
"ERROR:", "Not Found"
In our code, we’ve used the response.ok method to check if our request has succeeded. In this example, we’ve tried to retrieve a comment that does not exist, comment #999. This causes the contents of our else
statement to be executed, which returns a rejected promise. This promise contains the error message returned by the JSONPlaceholder API.
We’ve then used a .catch()
statement to receive this error and print it to the console.
Conclusion
The fetch API makes it easy to make web requests in JavaScript. The API is part of vanilla JavaScript so there’s no need to install or reference any libraries. What’s more, you can use the fetch API to make GET, POST, PUT, and DELETE requests.
Now you’re ready to start making web requests using the fetch API like a professional developer!
About us: Career Karma is a platform designed to help job seekers find, research, and connect with job training programs to advance their careers. Learn about the CK publication.