Calling REST API in React

Shubham Bartia
6 min readNov 26, 2020

What is REST API

API is the acronym for Application Programming Interface, which is a software intermediary that allows two applications to talk to each other.

For example, Each time you use an app like Facebook, send an instant message or check the weather on your phone, you’re using an API. Now you may wonder how? See all the previous examples told were exchanging their form of service through a third party resource which can mostly be a cloud, by this I mean all the above example take data from you, store and process it in a third party resource and then proceed the data to your destination.

Look at the above diagram, hopefully, it will make you understand the API workflow somehow.

If not let us understand API in this way, Think of an API as a waiter at a restaurant

At a restaurant, you are handed a menu of items that you can order. You can then add specific instructions about how you want those items prepared. Once you’ve made your decisions, you give your order to the waiter, saying, “I want the filet mignon, medium-rare, with a side of creamed spinach and a fully-loaded baked potato with no chives.”

The waiter writes down your order and delivers it to the kitchen team, who prepares your meal to your exact specifications.

Once your meal is prepared, the waiter picks it up from the kitchen and serves it to you at your table. You review it to make sure that you have received everything you requested — and then you eat.

The waiter’s role in this scenario closely mirrors the role of an API in the delivery of data on the modern web. Like a waiter, an API:

  1. Receives a set of instructions (a request) from a source (such as an application or engineer)
  2. Takes that request to the database
  3. Fetches the requested data or facilitates a set of actions
  4. Returns a response to the source

Then what do you mean by REST?

REST (REpresentational State Transfer) is an architectural style for developing web services. REST is popular due to its simplicity and the fact that it builds upon existing systems and features of the internet’s Hypertext Transfer Protocol (HTTP) in order to achieve its objectives, as opposed to creating new standards, frameworks, and technologies.

In simple it just the protocol or the set of rules that the API follows to make sure for a proper control flow of data from the source to the service and from service to the destination.

How it is helpful in programming?

Let us go by understanding a very basic real-life example here, Imagine you are going on a trip with your friend to someplace your like. Now the only problem here is that you don't have a car for taking all your friends at once, So what you think you will do now? Obviously, your answer will be either borrow a car from a friend or rent a car right? So you see the example here that says the need for API in programming, just like when you borrow a new resource for the trip(The car) you just have applied for an API call just to make things easy. In the same way, we make use of API in programming to make the resource available at a code from some other resource.

How to call API

A RESTful API uses commands to obtain resources. The state of a resource at any given timestamp is called a resource representation. A RESTful API uses existing HTTP methodologies defined by the RFC 2616 protocol, such as:

  • GET to retrieve a resource;
  • PUT to change the state of or update a resource, which can be an object, file, or block;
  • POST to create that resource; and
  • DELETE to remove it.

One of the main methods to fetch API in a programming language is used “fetch()” inbuild method, mainly available in JavaScipt and python. Fetch provides a generic definition of Request and Response objects (and other things involved with network requests). This will allow them to be used wherever they are needed in the future, whether it’s for service workers, Cache API, and other similar things that handle or modify requests and responses, or any kind of use case that might require you to generate your responses programmatically (that is, the use of computer program or personal programming instructions).

The fetch() the method takes one mandatory argument, the path to the resource you want to fetch. It returns that resolves to the Response to that request, whether it is successful or not. You can also optionally pass in an init options object as the second argument.

Format

fetch('http://example.com/movies.json')
.then(response => response.json())
.then(data => console.log(data));

Here we are fetching a JSON file across the network and printing it to the console. The simplest use of fetch() takes one argument — the path to the resource you want to fetch — and returns a promise containing the response (a Response object).

This is just an HTTP response, not the actual JSON. To extract the JSON body content from the response, we use the json() method (defined on the Body mixin, which is implemented by both the Request and Response objects.)

A better view of the fetch function

See fetch() for the full options available, and more details.

// Example POST method implementation:
async function postData(url = '', data = {}) {
// Default options are marked with *
const response = await fetch(url, {
method: 'POST', // *GET, POST, PUT, DELETE, etc.
mode: 'cors', // no-cors, *cors, same-origin
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: 'same-origin', // include, *same-origin, omit
headers: {
'Content-Type': 'application/json'
// 'Content-Type': 'application/x-www-form-urlencoded',
},
redirect: 'follow', // manual, *follow, error
referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
body: JSON.stringify(data) // body data type must match "Content-Type" header
});
return response.json(); // parses JSON response into native JavaScript objects
}

postData('https://example.com/answer', { answer: 42 })
.then(data => {
console.log(data); // JSON data parsed by `data.json()` call
});

Now when we have learned API and its basic form of calling in programming (In this example JavaScript). Let's move to our final step of calling it in an easy way to React...

Easy calling API in React

One of the best ways to call API in react is to use “AXIOS”. Now if you don't know what is react and why I have chosen only to react? please follow this link before reading any further.

n a nutshell, Axios is a Javascript library used to make HTTP requests from node.js or XMLHttpRequests from the browser that also supports the ES6 Promise API. Great, so from that we gather it does something that we can already do and that has recently been made significantly better.

Installing AXIOS in React

  • npm i axios

Installing AXIOS in React

  • import axios from "axios"

Performing a GET request

const axios = require('axios');// Make a request for a user with a given IDaxios.get('/user?ID=12345').then(function (response) {// handle successconsole.log(response);}).catch(function (error) {// handle errorconsole.log(error);}).then(function () {// always executed});

Performing a POST request

axios.post('/user', {firstName: 'Fred',lastName: 'Flintstone'}).then(function (response) {console.log(response);}).catch(function (error) {console.log(error);});

Now you might ask why Axios, when we have normal fetch(), so for this, have you noticed how clean they are in Axios when compare it with the general way of calling API using fetch()

Bonus

Try out the API operation through these free API links.

Example using json_placeholder API for testing using Axios

import React from 'react';
import axios from 'axios';
export default class UserList extends React.Component {
state = {
persons: []
}
componentDidMount() {
axios.get(`https://jsonplaceholder.typicode.com/users`)
.then(res => {
const users = res.data;
this.setState({ users });
})
}
render() {
return (
<ul>
{ this.state.users.map(user => <li>{user.name}</li>)}
</ul>
)
}
}

In the above code, At the top React & Axios library is imported. axios.get(URL) is used to get a promise which returns a response object. The received data in res.data is assigned to users. Information like status code and others can also be received with the response.

Conclusion

So today we leaned on API and React method of its calling, so far whatever you have learned can only be learned better and efficiently if you try some problem on your own. I have already given a list of the dummy API caller links so try it out via React and Axios. As always remember programming is an art and art gets better only when you do it or practice it again and again. With this, I am done for today. thank you.

--

--

Shubham Bartia

Full-stack Web Developer, loves to travel, party, read, write, crowd speaking and code