Skip to content
Home » Program to Fetch and Display Cat Facts using API with JavaScript

Program to Fetch and Display Cat Facts using API with JavaScript

This code snippet demonstrates how to fetch and display cat facts using an API in JavaScript. By making an HTTP request to the Cat Facts API, the program retrieves a specified number of cat facts and logs them to the console.

Code

fetch('http://catfacts-api.appspot.com/api/facts?number=99', { mode: 'no-cors'})
  .then(blob => blob.json())
  .then(data => {
    console.table(data);
    return data;
  })
  .catch(e => {
    console.log(e);
    return e;
  });

Code Explanation

The code starts by using the fetch() function to make a GET request to the Cat Facts API url: http://catfacts-api.appspot.com/api/facts?number=99. The fetch() function returns a Promise that resolves to the response generated by the server.

The { mode: 'no-cors' } parameter is passed to the fetch() function to indicate that the request should not enforce CORS (Cross-Origin Resource Sharing) restrictions. This allows the program to retrieve data from a different domain.

Once the Promise is resolved, the blob containing the response data is converted to JSON format using the .json() method. Another Promise is returned, which resolves with the fetched data.

Then, the console.table() function is used to display the fetched data in tabular format in the console. This function is a handy tool to visualize and explore tabular data.

Finally, the error handling is implemented using the .catch() method. If any error occurs during the fetch or conversion process, the error is caught and logged to the console.

Example:

Let’s say we want to fetch 99 cat facts using this program. We would execute the provided code snippet in a JavaScript environment, such as a browser’s developer console. After running the code, the fetched cat facts will be displayed in the console as a table.

javascript
fetch('http://catfacts-api.appspot.com/api/facts?number=99', { mode: 'no-cors' })
  .then(blob => blob.json())
  .then(data => {
    console.table(data);
    return data;
  })
  .catch(e => {
    console.log(e);
    return e;
  });

In this example, assuming the Cat Facts API is functional and accessible, the program will successfully fetch and display 99 cat facts.

Overall, this code snippet provides a simple yet effective way to use an API to fetch and display cat facts. It can be used as a starting point for building more complex applications or integrating cat facts into existing projects. Happy coding!

Also checkout the following codes.


How to Use Axios in JavaScript for API Requests Introduction: Learn how to use the axios library in JavaScript to make API requests easily.
Program to Understand JavaScript Function Binding