Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

How to Use the JavaScript Fetch API to Put Data

If you're learning programming, you've probably come across the term "API" (Application Programming Interface) and wondered how to use it to send or receive data from a web server. In this tutorial, we'll focus on how to use one of the most popular APIs in JavaScript, the Fetch API, to update data on a web server. We'll be using the PUT method to update the data. Don't worry if you're not familiar with these terms or concepts; we'll explain everything along the way!

What is an API?

An API (Application Programming Interface) is a set of rules and protocols that allows different software applications to communicate with each other. In simpler terms, it's like a waiter in a restaurant who takes your order and brings you the food. In this case, the waiter is the API that takes your request (data) and delivers it to the kitchen (web server) to be processed.

What is the Fetch API?

The Fetch API is a modern, flexible feature of JavaScript that allows you to make requests to a web server and handle the server's responses, all within your JavaScript code. It is built into most modern web browsers and has become the go-to method for making API requests in JavaScript.

Before Fetch API, developers used XMLHttpRequest to make API requests. Fetch API is a more powerful and easier-to-use alternative to XMLHttpRequest.

How to use Fetch API with the PUT method

The Fetch API can be used with various HTTP methods, such as GET, POST, PUT, DELETE, etc. In this tutorial, we'll focus on using the Fetch API with the PUT method to update data on the server.

The PUT method is used to update an existing resource on the server. It is similar to the POST method, which is used to create a new resource on the server. The main difference is that PUT replaces the existing resource with the new data, while POST creates a new resource with the given data.

Here's a step-by-step guide on how to use the Fetch API with the PUT method:

1. Prepare the data you want to update

Before making the API request, you need to prepare the data you want to send to the server. The data should be in a specific format, usually JSON (JavaScript Object Notation). JSON is a lightweight data interchange format that is easy for humans to read and write and easy for machines to parse and generate.

const dataToUpdate = {
  id: 1,
  title: "Updated blog post",
  body: "This is the updated content of the blog post.",
  author: "John Doe"
};

In this example, we have an object representing a blog post that we want to update on the server. The object has four properties: id, title, body, and author.

2. Convert the data to a JSON string

Before sending the data to the server, we need to convert it into a JSON string. We can do this using the JSON.stringify() method:

const jsonString = JSON.stringify(dataToUpdate);

Now, jsonString contains the JSON representation of our dataToUpdate object.

3. Use the Fetch API to make the request

Now that our data is ready, we can use the Fetch API to send the request to the server. The basic syntax for using the Fetch API is as follows:

fetch(url, options)
  .then(response => {
    // Handle the response
  })
  .catch(error => {
    // Handle the error
  });

url is the endpoint (the location on the web server) where we want to send our request, and options is an object containing any additional information we want to provide with our request, such as headers or the request method (e.g., PUT).

In our example, we'll use the following url and options:

const url = 'https://jsonplaceholder.typicode.com/posts/1'; // Replace this with the real API endpoint

const options = {
  method: 'PUT',
  headers: {
    'Content-Type': 'application/json'
  },
  body: jsonString
};

We set the method to PUT, specify the Content-Type header as application/json (since we're sending JSON data), and set the body of the request to our jsonString.

Now, let's put it all together and make the request:

fetch(url, options)
  .then(response => {
    if (!response.ok) {
      throw new Error(`HTTP error ${response.status}`);
    }
    return response.json();
  })
  .then(updatedData => {
    console.log('Data updated:', updatedData);
  })
  .catch(error => {
    console.error('Error updating data:', error);
  });

Here, we use the Fetch API to send our request and handle the server's response. If the request is successful, we'll get a response object that contains the updated data. We can access this data by calling response.json(), which returns a promise that resolves to the actual data.

If there's an error with the request, we'll catch it and log the error message to the console.

Conclusion

In this tutorial, we learned how to use the JavaScript Fetch API to update data on a web server using the PUT method. We prepared our data, converted it to a JSON string, and used the Fetch API to send the request and handle the response.

The Fetch API is a powerful and flexible tool that makes it easy to work with APIs in JavaScript. By understanding how to use the Fetch API with different HTTP methods, you'll be able to create, read, update, and delete data on web servers, opening up a world of possibilities for your web applications.