[JS Basics] Fetch API and JSON: How to Communicate with the Server

In today's web development world, exchanging data between the browser (client) and the server is the backbone of every dynamic application. Imagine you're at a restaurant: you (the client) order from the menu, the waiter (API) takes your request to the kitchen (server). The kitchen prepares the dish (data) and the waiter brings it back to you.

In this scenario, the Fetch API is the modern, fast, and efficient waiter. And JSON is the "language" that both you and the kitchen understand so the dish is delivered exactly as requested.

How to send and receive data with the server using JavaScript

This article will help you master this powerful duo, from the most basic concepts to practical examples, enabling you to build robust and efficient web applications.

1. Breaking Down the Concepts: What are Fetch API and JSON?

To understand why they're a perfect pair, let's first look at each component.

JSON: The Global Data Communication Language 🌐

JSON (JavaScript Object Notation) is a super lightweight, text-based format for storing and exchanging data. Despite the name "JavaScript," JSON is language-independent and supported by almost all modern programming languages.

What is JSON?

Key features of JSON:

  • Easy to read and write: JSON syntax is very similar to JavaScript object notation, making it easy for humans to read and understand.
  • Easy for computers to parse: Programming languages can easily parse JSON data into native objects.
  • Data structures: JSON supports two main structures:
    • key: value: Similar to JavaScript objects.
    • [] Array: An ordered list of values.

Example of a user object in JSON:

{
  "id": 101,
  "name": "Nguyen Van A",
  "email": "nguyenvana@example.com",
  "isActive": true,
  "hobbies": ["đọc sách", "chơi game", "du lịch"]
}

Fetch API: The Next-Gen Data Transporter 📦

Fetch API is a modern interface, built into most browsers, that lets you make network requests to servers easily. It was created to replace the old, more complex XMLHttpRequest (XHR) object.

What is Fetch API?

Why is Fetch API superior?

  • Modern, clean syntax: Uses Promises, making asynchronous operations clear, readable, and avoiding "callback hell."
  • Flexible and powerful: Easily configure HTTP requests like GET, POST, PUT, DELETE and manage headers.
  • Web standard: Widely supported without the need for external libraries.

2. Why are Fetch and JSON a "Perfect Pair"?

The combination of Fetch and JSON creates a smooth and efficient workflow:

  1. On the Client (Browser): You want to send data (e.g., user registration info) to the server. You create a JavaScript object, then use JSON.stringify() to convert it to a JSON string.
  2. Send the request: You use the Fetch API to send this JSON string to the server via an HTTP request (usually POST or PUT).
  3. On the Server: The server receives the JSON string, parses it back into an object or data structure that the server-side language (like Node.js, Python, Java) can understand and process.
  4. Server response: After processing, the server usually responds with another JSON string (e.g., a success message or the newly created user data).
  5. Receive the response: Fetch API receives this response. You use the .json() method (a handy Fetch feature) to automatically parse the JSON string into a JavaScript object you can use immediately in your app.

This workflow is the gold standard for modern web apps, from simple pages to complex SPAs (Single Page Applications) built with React, Vue, or Angular.

3. Mastering Fetch API: From Basics to Advanced

Let's dive into practical examples to see the power of Fetch and JSON. We'll use the mock API from JSONPlaceholder for practice.

GET: Fetch Data from the Server

This is the most common operation. For example, fetching a list of users.

Method 1: Using .then() (Traditional Promise Syntax)

fetch('https://jsonplaceholder.typicode.com/users')
  .then((response) => {
    // Step 1: Check if the request was successful (status code 200-299)
    if (!response.ok) {
      throw new Error('Network response was not ok ' + response.statusText)
    }
    // Step 2: Convert the response body to JSON
    return response.json()
  })
  .then((users) => {
    // Step 3: Now `users` is a JavaScript array of user objects
    console.log(users)
    // Example: Get the first user's name
    console.log('First user name:', users[0].name)
  })
  .catch((error) => {
    // Handle errors if there are network issues or problems in the above steps
    console.error('An error occurred!', error)
  })

💡 Note: fetch() returns a Promise. The first .then() gives you a Response object, not the JSON data yet. You need to call response.json() to extract and parse the response body.

Method 2: Using async/await (Modern, More Readable Syntax) This is the preferred way today because it makes your code look like regular synchronous code.

async function getUsers() {
  try {
    const response = await fetch('https://jsonplaceholder.typicode.com/users')

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    const users = await response.json()
    console.log(users)
  } catch (error) {
    console.error('Unable to fetch user list:', error)
  }
}

// Call the function to execute
getUsers()

POST: Send New Data to the Server

Now, let's try creating a new post.

// The JavaScript data we want to send
const newPost = {
  title: 'This is a new post',
  body: 'The content of the post created using Fetch API.',
  userId: 1,
}

async function createPost(postData) {
  try {
    const response = await fetch('https://jsonplaceholder.typicode.com/posts', {
      method: 'POST', // Request method
      headers: {
        // Declare that the content we're sending is JSON
        'Content-Type': 'application/json',
      },
      // Convert the JavaScript object to a JSON string
      body: JSON.stringify(postData),
    })

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    // Get back the data the server created (usually includes an ID)
    const createdPost = await response.json()
    console.log('Post created successfully:', createdPost)
  } catch (error) {
    console.error('Unable to create post:', error)
  }
}

// Call the function to execute
createPost(newPost)

Key options explained:

  • method: 'POST': Specifies the action we want to perform.
  • headers: { 'Content-Type': 'application/json' }: Very important! This tells the server, "the data I'm sending in the body is in JSON format."
  • body: JSON.stringify(newPost): Converts the newPost JavaScript object into a JSON string to send over the network.

Conclusion: Fetch API and JSON are the Foundation

Fetch API and JSON are not just technologies; they are the foundation for interaction on the modern web. Mastering how they work together opens the door for you to build rich, dynamic, and seamless web applications.

  • JSON is a flexible data format, the "common language" between client and server.
  • Fetch API is a powerful, modern tool for transporting that data asynchronously.

Hopefully, this article has given you a comprehensive and in-depth look at this "power duo." Start practicing today and turn your app ideas into reality!

Related Posts

[JS Basics] ES6+ Features: What You Need to Know to Write Modern JavaScript

This article is the most detailed handbook on JavaScript Events. Learn how to listen for and respond to user actions on your website, helping you build more interactive and smoother web applications.

[JS Basics] What is an Array in JavaScript? The Most Effective Ways to Use Arrays

Master the Array data structure in JavaScript. This article provides comprehensive knowledge from concepts to practical usage for handling data efficiently.

[JS Basics] Functions in JavaScript: Concepts, Declarations, and Detailed Examples

Discover the power of Functions in JavaScript! Step-by-step guide on how to write and use functions effectively. Start learning now to level up your coding skills.

[JS Basics] Objects in JavaScript: Concepts & Effective Usage

A deep dive into how Objects work in JavaScript. Detailed guide on properties, methods, and how to use Objects to write clean and efficient code.