DEV Community

Matt Williams for Tech Dev Blog

Posted on • Originally published at techdevblog.io on

Add Some Whiskers to Your Website with the Cat Facts API

Add Some Whiskers to Your Website with the Cat Facts API

Are you ready to learn some furtastic cat facts?

First things first, let's talk about what an API is. An API, or Application Programming Interface, is like a messenger that sends a request for information from one software program to another. The other program then sends a response back, allowing the two programs to communicate and share data and functionality.

Now that we've got the basics out of the way, let's dive into the fun stuff: cat facts! There's an API called the "Cat Facts" API that allows you to access a database of, you guessed it, cat facts. And the best part? It's totally free to use!

For example, let's say you want to display a random cat fact on your webpage. You can use the fetch() function in JavaScript to make a request to the Cat Facts API, like this:

fetch('https://cat-fact.herokuapp.com/facts/random?animal_type=cat&amount=1', {
  headers: {
    'Content-Type': 'application/json'
  }
})
  .then(response => response.json())
  .then(data => {
    const catFact = data.text;
    document.getElementById('cat-fact').innerHTML = catFact;
  });
Enter fullscreen mode Exit fullscreen mode

This will make a request to the Cat Facts API, asking for a random cat fact. The API will respond with a JSON object containing the cat fact, which you can access by calling response.json(). Then, you can use the cat fact to update the element with the ID "cat-fact" on your webpage.

And that's it! With just a few lines of code, you can add some feline fun to your website. Just don't let your cat see you using their secrets for your own gain... they might not be too pleased.

I hope this helps get you started with the Cat Facts API. And if you want to try out different APIs, API Ninjas has a few, and ProgrammableWeb lists even more!

Happy coding!

Top comments (0)