How to consume REST API in JavaScript

How to consume REST API in JavaScriptPhoto by Markus Spiske

Originally Posted On: https://exyte.com/blog/how-to-consume-rest-api-in-javascript

 

When it comes to JS, you can also look at the REST API integration as at connecting to data stored at a certain web address, and use relevant libraries.

JavaScript is one of the core programming languages used today. Thanks to APIs of the well-known REST type, you can easily use the existing protocols. Often, apps are closely connected with different APIs. If you need to access an API from your JavaScript (JS) application and want to know how this can be done, then you should read this article.

What Is a REST API?

First of all, let’s find what API means. This stands for an App Programming Interface, which is simply a range of procedures and tools to use for creating software apps. They are employed to make the development process easier and more effective. APIs are utilized very often nowadays.

An API is sort of an intermediate between an app and services that allow programs to communicate with each other. A developer builds an API on a server to allow clients to use it. Application Programming Interfaces may be developed by a third party, such as Facebook or Google to name a few. They allow accessing their app programming interfaces via JavaScript. You can, for example, utilize them for mapping to display certain maps on your pages.

REST is another thing you should learn. This abbreviation stands for Representational (provide a view) State (state of a page may change) Transfer (transferring of data). When using an app programming interface, a user needs to make an HTTP inquiry (request) to interact with a web service. There is a set of essential parameters to comply with, including the following:

  • Client-server type. It means that the client side handles UI, while the web-server takes care of the backend. Each of these components is independent, so it is possible to replace each of them without affecting the other one if needed;
  • Stateless. This means that no state of a client session is stored on the other side;
  • Cacheable. A user can cache the server’s responses.

When it comes to JavaScript, you can also look at the RESTful API integration as at connecting to data stored at a certain web address, which you can access using relevant libraries.

RESTful API integration

Another term to learn is a call in relation to an API, which means calling to a server using a certain API. This action can be done in a variety of ways, including XMLHttpRequest (XHR), Fetch, etc.

When it comes to JavaScript, it is essential to know about req res, where:

  • req means an object with some info about an HTTP request;
  • res is used to send back a response.

Make sure to get the basic idea of the following:

  • HTML (a markup language);
  • CSS (styling)
  • JavaScript (creating webpages).
Explanation of Requests

HTTP requests are similar to CRUD requests, which abbreviation stands for Create, Read, Update, Delete, but when it comes to REST, you will use the following:

  • POST request — add something to a server;
  • GET request — this one is the most commonly used type of request, allowing obtaining the info that you have been looking for;
  • PUT request — this is how you can add changes to existing data.
  • DELETE request — this is how you delete existing data.

When it comes to REST, the resources can be pointed via HTML protocol only. CRUD can only be applied to records in a database.

Endpoints

Those are certain addresses (for instance, https://facebook.com/profile). When entering those addresses using a certain method, users can access desired data (in our case – a Facebook profile).

Connecting to an API by Utilizing JavaScript

Below you will find simple instructions on the creation of JavaScript API combination: In our example, we are going to analyze comments from users. It is important to use a relevant API for the text-processing purpose. We used the one provided by the RapidAPI service.

For sending requests and encoding them, we need to use axios and qs libraries here.

Getting the Right API Key

It is a unique string of characters. To get access to most app programming interfaces, you must create a new API key, which you will add to each request for letting the API to recognize you. Some services allow you to register by using your accounts in social media networks and other means.

Testing Endpoints

Now that you have an API key, you can send your inquiry to endpoints and see how it works. Remember using the relevant documents provided by the API developer to learn its specific features. Usually, you should be able to find and choose a certain API category to use for testing without any problems.

We will test a sentiment endpoint by typing something negative – thereby, you will check out whether JSON data carries the relevant assessment.

Making a JavaScript App by Using a Reliable API

After completing the testing stage, you can start making an app. We will give you a quick example of how this can be done, and you, based on our experience, can do what you need.

In our example, we are going to analyze comments from users. It is important to use a relevant API for the text-processing purpose.

For sending requests and encoding them, we need to use axios and qs libraries here.

The project consists of the following:

  • index.html (the default page);
  • styles.css (the presentation of a page);
  • text-processing.js (for text processing).

To create index.html, the following should be done:

  • Importing styles;
  • Connecting to the libraries;
  • Adding the script.

Take a look at how our index.html combining all together looks like:

<!DOCTYPE html>
<html lang=”en>
<head>
<meta charset=”UTF-8>
<title>Text Processing</title>
<!– Import our css styles –>
<link rel=”stylesheethref=”styles.css>
</head>
<body>
<div class=”main>
<h2 class=”main-header>Comment text analysis</h2>
<section class=”main-input-comment>
<label for=”comment>Write your comment here:</label>
<textarea
name=”comment
id=”comment
class=”main-comment-area
placeholder=”Your comment…
>
</textarea>
<button class=”main-analyze-buttononclick=”onAnalyzeButtonClick()>Analyze…</button>
</section>
<section class=”main-result>
<p id=”main-result-blockclass=”main-result-block invisible>
<span>Result:</span>
<span id=”result></span>
</p>
</section>
</div>
<!– Import axios library –>
<script src=”https://unpkg.com/axios/dist/axios.min.js></script>
<!– Querystring library –>
<script src=”https://cdnjs.cloudflare.com/ajax/libs/qs/6.7.0/qs.min.js></script>
<!– Import our JavaScript file –>
<script src=”text-processing.js></script>
</body>
view rawindex.html hosted with ❤ by GitHub

Formatting can be added by using a style.css file.

* {
font-family: “Arial”, Arial, sans-serif;
font-weight: 400;
padding: 0
margin: 0;
border: 0;
}
body {
padding: 20px;
display: flex;
justify-content: center;
align-items: center;
}
label, textarea {
display: block;
}
.main {
padding: 10px;
width: 35%;
box-shadow: 0 0 10px rgba(0,0,0,0.5);
}
.main-header {
text-align: center;
margin-bottom: 20px;
}
.main-input-comment { margin-bottom: 20px; }
.main-comment-area {
width: 95%;
border: #ced4da 1px solid;
border-radius: 10px;
resize: none;
padding: 10px;
margin-bottom: 10px;
font-size: 16px;
}
.main-analyze-button {
width: 100%;
padding: 5px;
border: 1px solid #007bff;
background-color: #007bff;
border-radius: 7px;
color: white;
text-align: center;
font-size: 16px;
outline: none;
}
.main-analyze-button::-moz-focus-inner {border: 0;}
.main-analyze-button:hover {
background-color: #0069d9;
border-color: #0069d9;
cursor: pointer;
}
.main-result-block { text-align: center; }
.pos { color: green; }
.neg { color: darkred; }
.neutral { color: gray }
.invisible { display: none; }
view rawstyles.css hosted with ❤ by GitHub

Finally, it is time to create text-processing.js for achieving the following:

  • Obtaining a result;
  • Utilizing a callback function;
  • Sending the server’s response to it.
    // Text-Processing API Url
    const API_URL = ‘https://japerk-text-processing.p.rapidapi.com/sentiment/’;
    // RapidAPI request headers
    const REQUEST_HEADERS = {
    ‘X-RapidAPI-Host’: ‘japerk-text-processing.p.rapidapi.com’,
    ‘X-RapidAPI-Key’: ‘768d224b32mshbe5f76705cbfd9bp154850jsnba7a2201e140’,
    ‘Content-Type’: ‘application/x-www-form-urlencoded’
    };
    // Button click handler
    const onAnalyzeButtonClick = () => {
    // Getting a textarea element with a comment
    const commentElement = document.getElementById(‘comment’);
    // Getting comment text
    const commentText = commentElement.value.trim();
    // Handle empty comment
    if (!commentText) {
    return handleEmptyComment();
    }
    // Calling the API and passing the result with the displayResult as a callback function
    return analyzeComment(commentText, displayResult);
    };
    const analyzeComment = (comment, callback) => {
    // Creating an object to send to the server
    const data = {
    text: comment,
    language: ‘english’
    };
    // Encoding data for application/x-www-form-urlencoded content type
    const formattedData = Qs.stringify(data);
    // POST request to server
    axios.post(API_URL, formattedData, { headers: REQUEST_HEADERS })
    .then(response => {
    const data = response.data;
    // Calling a callback function with data from the server
    callback(data)
    })
    .catch(error => console.error(error))
    };
    const handleEmptyComment = () => {
    const resultBlockElement = document.getElementById(‘main-result-block’);
    resultBlockElement.classList.add(‘invisible’);
    return alert(‘Your comment is empty =(‘);
    };
    const displayResult = result => {
    // Remove invisible class for main-result-block
    const resultBlockElement = document.getElementById(‘main-result-block’);
    resultBlockElement.classList.remove(‘invisible’);
    // Setting the color of the result text depending on the response label
    const label = result.label;
    const resultElement = document.getElementById(‘result’);
    resultElement.setAttribute(‘class’, label);
    let resultText = ;
    // Choosing the result text depending on response label
    switch (label) {
    case ‘pos’:
    resultText = ‘Wow! Your comment is very positive!’;
    break;
    case ‘neg’:
    resultText = ‘Negative comment =(‘;
    break;
    case ‘neutral’:
    resultText = ‘Simple comment =)’;
    break;
    default:
    resultText = “Hmmm, can‘t understand your comment”;
    }
    // Setting the result text
    resultElement.textContent = resultText;
    };
    view rawtext-processing.js hosted with ❤ by GitHub
Bottom Line

If you do not have initial knowledge of HTML, CSS, and, of course, JavaScript, you will not be able to create the right integration. For instance, if you are a business owner who wants to enhance the functionality of their own app by the use of reliable app programming interfaces provided by third parties, you can ask for professional help.

However, if you are a developer or a user with sufficient knowledge of the programming languages, libraries, and other essential elements of the tech stack, you can use a wide variety of app programming interfaces with JS according to your goal.

Data & News supplied by www.cloudquote.io
Stock quotes supplied by Barchart
Quotes delayed at least 20 minutes.
By accessing this page, you agree to the following
Privacy Policy and Terms and Conditions.