DEV Community 👩‍💻👨‍💻

Ty
Ty

Posted on

Using api's with react

If there is a frontend, there has to be a backend for your website. Throughout my course with Flatiron, we utilized api's for our backend. Wether we made our own api with rails or used an external api, at least our project utilized some sort of api.

While there are multiple api's any commercial use would need an api key. This api key would allow for only your product / website to be able to use a certain api. However there are plenty of free api sites that do not need an api key to use.

GitHub logo public-apis / public-apis

A collective list of free APIs for use in software and web development.

Public APIs Run tests Validate links

A collective list of free APIs for use in software and web development.

A public API for this project can be found here!

For information on contributing to this project, please see the contributing guide.

Please note a passing build status indicates all listed APIs are available since the last update. A failing build status indicates that 1 or more services may be unavailable at the moment.

Index

Animals

API Description Auth HTTPS CORS
Cat

I would use this website as a starter on learning api's!

When using react, you would use a fetch method to get the info that you need. You have many ways in order to fetch from the api. I would prefer to either handle it by a button press, or an asynchronous event such as ComponentDidMount.

While using ComponentDidMount, you would do a simple fetch request and save it to your state. The fetch would run automatically on page load.

An example code of the fetch to an api would look like this

fetch("https://www.themealdb.com/api/json/v1/1/random.php")
        .then(resp => resp.json())
        .then(data => {
            this.setState({food: data})
        })
Enter fullscreen mode Exit fullscreen mode

Here, I am using a free api called themealdb in order to get a random recipe. This would allow me to save one random food into my food state which I can call at anytime throughout the page or even pass it down to other pages as well.

This api does not need an api key, but if it did need an api key, make sure to store it in your development environment table instead of the actual code. You want your api to be hidden to the public so no one can use that key besides you!

Top comments (0)

🌚 Friends don't let friends browse without dark mode.

Sorry, it's true.