Working with APIs using fetch()

1. What is fetch()?

fetch() is a modern JavaScript function that allows you to make network requests (like GET, POST, etc.) to APIs. It returns a Promise, which resolves to the Response object.


2. Basic fetch() Example

Suppose we want to get some data from a public API: JSONPlaceholder (fake API for testing).

// URL of the API
const apiUrl = 'https://jsonplaceholder.typicode.com/posts/1';

// Fetch data from API
fetch(apiUrl)
  .then(response => {
    if (!response.ok) {
      throw new Error('Network response was not ok ' + response.status);
    }
    return response.json(); // Convert response to JSON
  })
  .then(data => {
    console.log('Data received:', data);
    // Example: access title
    console.log('Post Title:', data.title);
  })
  .catch(error => {
    console.error('Fetch error:', error);
  });

Explanation:

  1. fetch(apiUrl) → starts the network request.
  2. .then(response => response.json()) → converts the raw response into JSON.
  3. .then(data => {...}) → uses the JSON data.
  4. .catch(error => {...}) → handles errors if the request fails.

3. Using async/await (Cleaner Syntax)

async function getPost() {
  const apiUrl = 'https://jsonplaceholder.typicode.com/posts/1';
  try {
    const response = await fetch(apiUrl);
    if (!response.ok) {
      throw new Error('Network response was not ok ' + response.status);
    }
    const data = await response.json();
    console.log('Data received:', data);
    console.log('Post Title:', data.title);
  } catch (error) {
    console.error('Fetch error:', error);
  }
}

getPost();

✅ This version is easier to read and works just like synchronous code.


4. Posting Data to an API

Sometimes you want to send JSON data to an API (POST request):

const apiUrl = 'https://jsonplaceholder.typicode.com/posts';

const newPost = {
  title: 'My New Post',
  body: 'This is the content of the post',
  userId: 1
};

fetch(apiUrl, {
  method: 'POST',             // HTTP method
  headers: {
    'Content-Type': 'application/json' // Tell the server we're sending JSON
  },
  body: JSON.stringify(newPost) // Convert JS object to JSON string
})
  .then(response => response.json())
  .then(data => console.log('Created Post:', data))
  .catch(error => console.error('Error:', error));

✅ Notice JSON.stringify() is needed when sending JSON.


Summary:

  • fetch() → makes network requests.
  • response.json() → parses the response into JSON.
  • Use .then() for Promises or async/await for cleaner code.
  • Use JSON.stringify() to send JSON in POST requests.

Leave a Reply