*
Previous JavaScript Modules JavaScript question answers 241-260 Next

๐Ÿ”— Connecting JavaScript with REST APIs

๐Ÿ”— Connecting JavaScript with REST APIs

Connecting JavaScript with RESTful APIs involves making HTTP requests to retrieve or send data to a server. The most modern and recommended method is the Fetch API, which uses Promises to handle asynchronous operations. Other options include using the third-party library Axios or the older XMLHttpRequest (XHR) method

๐Ÿ“˜ What is a REST API?

A REST (Representational State Transfer) API allows communication between client and server using HTTP methods like GET, POST, PUT, and DELETE. It typically returns data in JSON format.

๐Ÿงช Basic Example Using fetch()

// GET request
fetch('https://jsonplaceholder.typicode.com/posts/1')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

// POST request
fetch('https://jsonplaceholder.typicode.com/posts', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    title: 'Hello',
    body: 'This is a test post',
    userId: 1
  })
})
  .then(response => response.json())
  .then(data => console.log(data));

โš™๏ธ Using async/await

async function getPost() {
  try {
    const response = await fetch('https://jsonplaceholder.typicode.com/posts/1');
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error('Fetch error:', error);
  }
}
getPost();

1. Using the Fetch API

The fetch() method is a browser-native, Promise-based function for making network requests.

Sending a GET request

To fetch data, you simply pass the API endpoint URL to fetch(). The request is asynchronous, so you must use .then() to handle the response when it arrives.

javascript

fetch('https://jsonplaceholder.typicode.com/users')
  .then(response => {
    // Check if the request was successful
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    // Parse the JSON data from the response
    return response.json();
  })
  .then(data => {
    console.log(data); // Process and use the data
  })
  .catch(error => {
    console.error('There was a problem with the fetch operation:', error);
  });

Sending a POST request

For a POST request, you must provide a second argument, an options object, to specify the HTTP method, headers, and body.

javascript

const newUserData = {
  name: 'John Doe',
  username: 'johndoe',
  email: 'johndoe@example.com'
};

fetch('https://jsonplaceholder.typicode.com/users', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(newUserData)
})
  .then(response => response.json())
  .then(data => {
    console.log('Success:', data);
  })
  .catch(error => {
    console.error('Error:', error);
  });

Using async/await

Using async/await provides a cleaner, more readable way to handle promises, especially when dealing with multiple asynchronous calls.

javascript

async function fetchUser(userId) {
  try {
    const response = await fetch(`https://jsonplaceholder.typicode.com/users/${userId}`);
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    const user = await response.json();
    return user;
  } catch (error) {
    console.error('Fetch error:', error);
  }
}

fetchUser(1).then(user => console.log(user));

2. Using the Axios library

Axios is a popular third-party library known for simplifying HTTP requests and offering additional features like request/response interceptors and better error handling out of the box.

Installation

You can install Axios via npm or include it from a CDN.

bash

npm install axios

Sending a GET request

javascript

import axios from 'axios';

axios.get('https://jsonplaceholder.typicode.com/users')
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error('There was an error!', error);
  });

Sending a POST request

javascript

import axios from 'axios';

const newUserData = {
  name: 'Jane Doe',
  username: 'janedoe',
  email: 'janedoe@example.com'
};

axios.post('https://jsonplaceholder.typicode.com/users', newUserData)
  .then(response => {
    console.log('Success:', response.data);
  })
  .catch(error => {
    console.error('Error:', error);
  });

โœ… Best Practices

  • Always handle errors using try/catch or .catch()
  • Use async/await for cleaner syntax
  • Set appropriate headers (e.g., Content-Type)
  • Validate and sanitize user input before sending
  • Use environment variables for API keys

Common considerations

  • Handle JSON data: REST APIs most commonly communicate using JSON. In JavaScript, use JSON.parse() to convert a JSON string from a response into a JavaScript object, and JSON.stringify() to convert a JavaScript object into a JSON string for a request body.
  • Error handling: Always implement proper error handling using .catch() with Fetch, or try/catch with async/await, to manage potential network errors, server errors (4xx or 5xx status codes), or other unexpected issues.
  • Authentication and security: For secure APIs, include authentication tokens (such as a Bearer token) in the request headers. Always use HTTPS to encrypt data in transit.
  • Cross-Origin Resource Sharing (CORS): When your JavaScript client code is on a different domain than the REST API, you may encounter CORS issues. The server must be configured to allow requests from your client's origin.
  • API design: Pay attention to REST conventions such as using appropriate HTTP methods (e.g., GET for fetching, POST for creating, PUT/PATCH for updating, DELETE for deleting) and consistent endpoint naming.

๐Ÿ” Authentication

Many APIs require authentication using tokens:

fetch('https://api.example.com/data', {
  headers: {
    'Authorization': 'Bearer YOUR_API_TOKEN'
  }
});

๐Ÿ“ฆ Tools and Libraries

  • Axios โ€“ A popular HTTP client with a simpler API than fetch()
  • Postman โ€“ For testing and exploring APIs
  • JSONPlaceholder โ€“ A free fake API for testing

๐Ÿ”— References

Back to Index
Previous JavaScript Modules JavaScript question answers 241-260 Next
*
*