read restful api in javascript

Here is an example of how to read a RESTful API in JavaScript using the Fetch API:

index.tsx
// Define the endpoint URL
const url = 'https://jsonplaceholder.typicode.com/posts';

// Fetch the data from the API
fetch(url)
  .then(response => {
    // Check if the response is successful
    if (response.ok) {
      return response.json();   // Parse the response body as JSON
    } else {
      throw new Error('Network response was not ok.');
    }
  })
  .then(data => {
    // Use the data returned from the API
    console.log(data);
  })
  .catch(error => {
    console.error('There was an error fetching the data.', error);
  });
543 chars
21 lines

In this example, we are using the fetch() method to make a GET request to the specified endpoint URL. The response is then checked to ensure it is successful, and the response body is parsed as JSON using the json() method. Finally, the data is logged to the console.

Note that the fetch() method returns a Promise, which allows us to use .then() and .catch() methods to handle both successful and failed responses.

gistlibby LogSnag