DEV Community

Cover image for JavaScript Fetch API in Minutes!
Taiwo Shobo
Taiwo Shobo

Posted on

JavaScript Fetch API in Minutes!

Introduction:

  • The Fetch API is a powerful JavaScript tool used to interact with Web APIs.
  • Learn how to make GET, POST, PUT, PATCH, and DELETE requests.
  • This tutorial also covers async/await with Fetch and handling API responses.

How the Fetch API Works:

  • The fetch() function takes:
    1. A URL (required).
    2. An options object (optional), where you define request method, headers, and body.
  • It returns a Promise, allowing you to handle responses with .then() and errors with .catch().

Video Tutorial: Visit YouTube

Example:

fetch('<Your URL>')
  .then((response) => {
    // Handle success
  })
  .catch((error) => {
    // Handle error
  })
Enter fullscreen mode Exit fullscreen mode

Sending Requests:

1. GET Request:

  • Used to fetch data from an API. Example:
fetch('https://jsonplaceholder.typicode.com/users/1')
  .then((response) => response.json())
  .then((data) => console.log(data))
Enter fullscreen mode Exit fullscreen mode
  • Converts the response to JSON using .json() and logs user data like name and email.

2. POST Request:

  • Can be used to send data to an API (e.g., creating a new user).

To send a "POST" request using fetch, you need to define the second argument as an options object containing the following:

  • Method: Set the method property to "POST".
  • Headers: Include a Content-Type header set to "application/json".
  • Body: Use JSON.stringify() to convert the data you want to send into JSON format and assign it to the body property.
fetch('https://jsonplaceholder.typicode.com/users', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ name: 'John', email: 'john@example.com' }),
})
  .then((response) => response.json())
  .then((data) => console.log(data))
Enter fullscreen mode Exit fullscreen mode

3. PUT Request:

  • Replaces existing data or creates new data.
  • Similar to POST, but used to overwrite resources. Example:
fetch('https://jsonplaceholder.typicode.com/users/1', {
  method: 'PUT',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ name: 'Jane', email: 'jane@example.com' }),
})
  .then((response) => response.json())
  .then((data) => console.log(data))
Enter fullscreen mode Exit fullscreen mode

4. PATCH Request:

  • Partially updates data for a specific resource.
  • To update an existing user's name, you can use the PATCH.

Example:

fetch('https://jsonplaceholder.typicode.com/users/1', {
  method: 'PATCH',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ name: 'Jane' }),
})
  .then((response) => response.json())
  .then((data) => console.log(data))
Enter fullscreen mode Exit fullscreen mode

5. DELETE Request:

  • Removes a resource permanently.
  • To run a DELETE request with Fetch, you only need to specify the URL for the resource to delete and the method: 'DELETE' property as follows: Example:
fetch('https://jsonplaceholder.typicode.com/users/1', {
  method: 'DELETE',
}).then((response) => console.log('Deleted:', response))
Enter fullscreen mode Exit fullscreen mode

Difference Between PUT and PATCH Methods

The PUT method replaces the entire resource with the updated data, while the PATCH method modifies only the specified fields in the resource.

  • Use PUT for complete updates.
  • Use PATCH for partial updates.

Using Async/Await with Fetch:

  • Async/await simplifies working with Promises:
async function fetchData() {
  try {
    const response = await fetch('https://jsonplaceholder.typicode.com/users/2')
    const data = await response.json()
    console.log(data)
  } catch (error) {
    console.log(error)
  }
}

fetchData()
Enter fullscreen mode Exit fullscreen mode

Video Tutorial: Visit YouTube


Using Fetch API to Display Data in HTML

Here’s an example that demonstrates fetching and displaying user details on a webpage:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Fetch API Example</title>
  </head>
  <body>
    <h1>User Information</h1>
    <div id="user-info">
      <p id="user-name">Name: Loading...</p>
      <p id="user-email">Email: Loading...</p>
    </div>

    <script>
      // Fetch user data
      fetch('https://jsonplaceholder.typicode.com/users/1')
        .then((response) => response.json())
        .then((data) => {
          document.getElementById(
            'user-name'
          ).textContent = `Name: ${data.name}`
          document.getElementById(
            'user-email'
          ).textContent = `Email: ${data.email}`
        })
        .catch((error) => console.error('Error:', error))
    </script>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

Tips for Working with APIs:

  1. Always check the API documentation for required request methods, headers, and formats.
  2. Understand whether the API returns JSON, arrays, or other data structures.
  3. Practice with free APIs like https://jsonplaceholder.typicode.com.

Video Tutorial: Visit YouTube

Conclusion:

  • The Fetch API is versatile for making HTTP requests in JavaScript.
  • Use .then()/.catch() or async/await for handling responses.
  • Master GET, POST, PUT, PATCH, and DELETE to interact with any API effectively.

Top comments (0)