Consuming Restful Apis in reactjs

marrie

Marriane Akeyo

Posted on May 10, 2022

Consuming Restful Apis in reactjs

If you are a react developer and you would like to learn more about consuming restapis ,or you are having issues with consuming rest apis then this article is for you.
Rest apiscan be defined as endpoints which we use to fetch data to and from users in our react application.They are very usefull in creating a connection between our client and our backend.So when we talk about consuming restapis, we try to figure out how to call our endpoints in our frontend application so that when a user of aour application wants to make requests to our database he can do so easiy.

Consuming REST apis in react can be done in various ways .However, in this article we are going to discuss two most porpular ways known as Axios (a promise-based HTTP client) and Fetch API (a browser in-built web API).

Note:_ A good knowledge of ReactJS, React Hooks, JavaScript and CSS will come in handy as you work your way throughout this post's content._

Using the Fetch Api

The fetch() method is an in-built Javascript method for fetching resources from the server or an API endpoint.This method always takes in a compulsory URL argument containing the path to the resource you want to fetch and returns a promise that points to the request's response weather it was successful or not.

Parameters we can use for the Fetch API

  • Resource:This is the url with the path to the resource to be fetched.

  • headers
    This is for specifying any headers you would like to add to your request, usually contained in an object or an object literal.

  • body
    This is for specifying a body that you want to add to your request: this can be a Blob, BufferSource, FormData, URLSearchParams, USVString, or ReadableStream object.

  • mode
    This is for specifying the mode you want to use for the request, e.g., cors, no-cors, or same-origin.

  • credentials
    This for specifying the request credentials you want to use for the request, this option must be provided if you consider sending cookies automatically for the current domain.

Fetch request syntax

fetch('https://github.com/Marriane791?tab=repositories')
  .then(response => response.json())
  .then(data => console.log(data));

Enter fullscreen mode Exit fullscreen mode

In the code above , I used my personal github repository as an example url.The response is just a regular HTTP response and not the actual JSON. In order to get the JSON body content from the response, we’d have to change the response to actual JSON using the json() method on the response.

Using axios
Axios() is a promised based method which is commonly preffered when fetching api endpoints in javscript.Since it is a promised based method , we take advantage of the async await just as we shall see below to make our requests.Axios also contains an in-built feature that protects the client aganist cross-site fogery.It also enables the following:

  • Streamlined error handling.

  • Request and response interception.

  • Upload progress.

  • Response timeout .

  • Cancellation of requests
    Just to mention a few.The syntax includes:

axios.post(url,{data}).then(response => {
console.log(response.data)
});
Enter fullscreen mode Exit fullscreen mode

You can now freely view your application in the browser,right click then inspect your code to view the actual data being fetched from the api.
Example:
axios example

This is an example of a code snippet from an application I created called diagnostic disease prediction which can be found here which enables doctors to chat with each other.
The method getChats, contains all the logic to fetch our data from an endpoint.The method is then called in the useEffect method and the implementation continues.

💖 💪 🙅 🚩
marrie
Marriane Akeyo

Posted on May 10, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Consuming Restful Apis in reactjs
javascript Consuming Restful Apis in reactjs

May 10, 2022