Using an API with JavaScript (A Beginners Guide to API)

Using an API with JavaScript (A Beginners Guide to API)

If you are faced with the task of accessing the API in your JavaScript application and don’t know where to start, this article will help you figure it out quickly.

How To Use an API with JavaScript (The Complete Beginner's Guide) Get an API key. Test the API Endpoints. Make your first app with API. If you are faced with the task of accessing the API in your JavaScript application and don’t know where to start, this article will help you figure it out quickly.

What is REST API (from a JavaScript perspective)?

To begin, let us define what is hidden under the API abbreviation. API (Application Programming Interface) can be considered as a set of rules that are shared by a particular service. These rules determine in which format and with which command set your application can access the service, as well as what data this service can return in a response. API acts as a layer between your application and external service.

REST API (Representational state transfer) is an API that uses HTTP requests for communication with web services and must comply with certain constraints. Full constraints list can be viewed at the link. Here are some of them:

  1. Client-server architecture – the client is responsible for the user interface, and the server is responsible for the backend and data storage. Client and server are independent of each other, and each of them can be replaced separately.
  2. Stateless – no data from the client is stored on the server-side. The session state is stored on the client-side.
  3. Cacheable – clients can cache server responses to improve performance.

From the JavaScript side, the REST API integration can be viewed as a connection to a data source located at a specific address on the Internet, which can be accessed in a certain way through certain libraries.

Prerequisites

We will try to keep things simple, so to work with queries we will use the axios library because of its simplicity and universality. Also, in order to understand what the article is about, you will need some basic knowledge of HTML and CSS and JavaScript syntax and datatypes.

CRUD and types of requests

CRUD is a programming concept denoting four basic actions (create, read, update, and delete) that can be performed on a data source. In a REST API, these actions correspond to Types of Requests or Request Methods:

  • POST: Create action. Adds new data to the server. Using this type of request, you can, for example, add a new ticket to your inventory.
  • GET: Read action. Retrieves information (like a list of items). This is the most common type of request. Using it, we can get the data we are interested in from those that the API is ready to share.
  • PUT: Update action. Changes existing information. For example, using this type of request, it would be possible to change the color or value of an existing product.
  • DELETE: Delete action. Deletes existing information.

Endpoints and CRUD

In order to work with REST APIs, it is important to understand the Endpoint concept. Usually, Endpoint is a specific address (for example, https://hotels-to-stay.com/best-hotels-paris), by referring to which (with certain request method) you get access to certain features/data (in our case – the list of best hotels in Paris). Commonly, the name (address) of the endpoint corresponds to the functionality it provides.

To learn more about endpoints and CRUD, we will look at simple API example within the RapidAPI service. This service is an API Hub providing the ability to access thousands of different APIs. Another advantage of RapidAPI is that you can access endpoints and test the work of the API directly in its section within the RapidAPI service.

We will go through the JAAS – JSON as a service. This API is used to generate and modify JSON objects, that is useful in coding practice.

In order to find JAAS API section, enter its name in the search box in the RapidAPI service or go to the “Data” category from “All Categories” list and select this API from the list. JAAS API through RapidAPI is free, so you can create as many JSON objects as you want.

This is image title

Once you select JAAS API, the first page you’ll see is the API Endpoints subsection. This includes most of the information needed to get started.

This is image title

We will go through all CRUD actions: create, read, update, delete. For each of these actions, JAAS API provides a corresponding endpoint.

This is image title

In order to demonstrate the entire CRUD functionality in JavaScript, we will complete the following steps:

  1. Make a POST request for the API used to create the object. We will save object id which was received in the answer.
  2. Make a GET request where we will use the id from the first step, thereby demonstrating GET requests and the fact that the object was created
  3. Make a PUT request where we substitute the modified object and demonstrate the answer.
  4. Make a DELETE request with the object id and show the answer.
  5. Make a GET request with id again to show that the DELETE method worked and the object is definitely not there.

1. So, let’s begin. Firstly we need to connect the axios library to our html file for easy work with queries.

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

Create a constant with an API address within the RapidAPI service.

// Constant URL value for JAAS API
const RAPIDAPI_API_URL = 'https://arjunkomath-jaas-json-as-a-service-v1.p.rapidapi.com/';

Next, we create an object/dictionary with constant headers for RapidAPI, which are required during accessing. Since these headers will be in each request, they also need to be put into a separate variable.

// Object with RapidAPI authorization headers and Content-Type header
const RAPIDAPI_REQUEST_HEADERS = {
  'X-RapidAPI-Host': 'arjunkomath-jaas-json-as-a-service-v1.p.rapidapi.com'
  , 'X-RapidAPI-Key': '7xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
  , 'Content-Type': 'application/json'
};

We create an object on which we will work (send in requests, modify) and a variable to store id.

// Variable to store ID
let STUDENT_ID = '';

// Object for examples
const student = {
  name: 'John'
  , surname: 'Doe'
  , age: 18
};

Now we will start the direct implementation of the first step from the list. We will make a POST request to the specified address with the object and headers. That is, here we create a student object on the server.

// Making a POST request using an axios instance from a connected library
axios.post(RAPIDAPI_API_URL, student, { headers: RAPIDAPI_REQUEST_HEADERS })
  // Handle a successful response from the server
  .then(response => {
            // Getting a data object from response that contains the necessary data from the server
            const data = response.data;
            console.log('data', data);

            // Save the unique id that the server gives to our object
            STUDENT_ID = data._id;
  })
  // Catch and print errors if any
  .catch(error => console.error('On create student error', error));

In the first parameter, we send the URL to the function. The second parameter is the data. The third parameter is the object with the headers for the request. Then we either get a successful response and output it to the browser console, or the request ends with an error and we also display it in the console. The response object contains many fields, but we are interested in the data field. As a result, in the console we get the following JSON output:

{
  "_id": "3060e599-b758-44cc-9eb4-8fda050b76d2",
  "created_at": 1563051939620,
  "body": {
  "name": "John",
  "surname": "Doe",
  "age": 18
  }
}

Now we have the variable STUDENT_ID containing the following line:

"3060e599-b758-44cc-9eb4-8fda050b76d2"

2. Let’s test a GET request.

// Making a GET request using an axios instance from a connected library
axios.get(`${RAPIDAPI_API_URL}/${STUDENT_ID}`, { headers: RAPIDAPI_REQUEST_HEADERS })
  .then(response => {
            console.log(response.data);
  })
  .catch(error => console.error('On get student error', error))

The first parameter is the union of the API URL and the id of the object that we want to receive. The second parameter is the necessary headers. Everything else as in the previous example.

As a result, we will see the following in the console:

{
  "_id": "3060e599-b758-44cc-9eb4-8fda050b76d2",
  "body": {
  "name": "John",
  "surname": "Doe",
  "age": 18
  },
  "created_at": 1563051939620
}

Everything works as expected. Let’s proceed.

3. Now we are testing a PUT request, that is, trying to modify an object created earlier on the server.

Imagine a situation where someone entered incorrect data, and our student John is not 18, but 20 years old. We will also need to keep his average score. To do this, we modify our object as follows:

student.age = 20;
student.score = 4.0;

Now John is 20, his average score is 4.0, and the student object now looks like this:

{
  "name": "John",
  "surname": "Doe",
  "age": 20,
  "score": 4
}

We need to inform the server about this information and for this task we use the following code snippet:

axios.put(`${RAPIDAPI_API_URL}/${STUDENT_ID}`, student, { headers: RAPIDAPI_REQUEST_HEADERS })
        .then(response => {
          console.log(response.data);
        })
        .catch(error => console.error('On change student error', error))

That is, we execute a PUT request, where the first parameter is the URL pointer to the desired object, the second parameter is the already updated student, and the third is the necessary headers.

As a result, after executing the code, we have the following response from the server:

{
  "_id": "3060e599-b758-44cc-9eb4-8fda050b76d2",
  "body": {
  "name": "John",
  "surname": "Doe",
  "age": 20,
  "score": 4
  }
}

_id is correct, data is updated.

4. Now we are testing the DELETE method, that is, deleting an object. In order to delete an object, simply execute the following code:

axios.delete(`${RAPIDAPI_API_URL}/${student.id}`, { headers: RAPIDAPI_REQUEST_HEADERS })
        .then(response => {
            console.log(response.data);
        })
        .catch(error => console.error('On change student error', error))

Parameters are specified as in the previous examples. The result is as follows:

{
  "_id": "3060e599-b758-44cc-9eb4-8fda050b76d2",
  "message": "Data Deleted"
}

We got a message saying that our object is deleted.

5. Great, but let’s see what happens if we try to retrieve the deleted object using the GET request:

// Making a GET request using an axios instance from a connected library
axios.get(`${RAPIDAPI_API_URL}/${STUDENT_ID}`, { headers: RAPIDAPI_REQUEST_HEADERS })
  .then(response => {
            console.log(response.data);
  })
  .catch(error => console.error('On get student error', error))

We received the answer that this object no longer exists. Everything works as we expected.

{
  "errors": [
  "Item not found"
  ]
}

How To Connect to an API (with JavaScript)

Now we know the basic elements of working with API in JavaScript, and we can create a step-by-step guide to creating a JavaScript app with API integration:

1. Get an API key

This is image title

An API key is usually a unique string of letters and numbers. In order to start working with most APIs, you must identify yourself (register) and get an API key. You will need to add an API key to each request so that the API can recognize you. On the example of RapidAPI – you can choose the method of registration that will be convenient for you. This can be a username, email, and password; Google, Facebook or Github account.

2. Test API Endpoints with JavaScript

This is image title

After we receive the API key, we can make a request to API endpoints (according to the rules in the documentation) to check if everything works as we expected. In the case of working with RapidAPI, immediately after registering with the service, we can go to the section of the API of our interest, subscribe to it and test endpoints directly on the API page. Next, we can quickly create a JavaScript snippet using the axios library with requests to the desired endpoint and test its work in the browser console.

3. Make your first JavaScript app with API

This is image title

After we check the endpoints, we can start creating an application, including the necessary API calls.

Example: How to Build a ‘Comment Sentiment Analyzer’ App (with APIs & JavaScript)

Now, let’s apply what we learned above and create a small service for analyzing the sentiment of user comments.

Let’s imagine that we have created such a bright product that causes such a strong reaction from users that they cannot hold back emotions when they write comments. To help our users determine the nature of their feelings about the product, we will expand the usual commenting form and add functionality to analyze the sentiments of their comments.

In this task, we will be helped by Text-Processing API, which is available through the RapidAPI service. This API works under freemium conditions, allowing a limited number of texts per day to be processed for free. Since we are going to process just a few comments for test purposes, that’s enough for us.

This is image title

To send requests, we will continue to use the axios library. You will also need the qs library to encode requests.

1. Get an API key

After registering with RapidAPI service, we will receive a service key, and this will be enough for us to start work with the Text-Processing API. You can register by clicking on the ’Sign Up’ button on RapidAPI menu.

This is image title

As mentioned earlier, you can register in any convenient way:

This is image title

2. Test the API Endpoints

To analyze the sentiment of user comments, we need the sentiment endpoint. We will test it directly in the browser by sending a negative test comment.

This is image title

As we can see, API returns JSON with a negative assessment, so apparently, everything works as it should.

3. Make your first app with API

Now we will create our small application for analyzing the sentiment of comments.

The project structure consists of three files: index.html, style.css, text-processing.js

  1. index.html – our HTML template
  2. style.css – styles for the HTML file
  3. text-processing.js – JavaScript logic file

Firstly, we need the index.html in which everything will be displayed:

Let’s break it down:

First, we need to connect our styles in the project:

<!-- Import our css styles -->
<link rel="stylesheet" href="styles.css">

Then, we’ll connect to the axios library for requests:

<!-- Import axios library -->
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

And also the qs library to transform data before sending:

<!-- Querystring library -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/qs/6.7.0/qs.min.js"></script>

And then our own JS script to tie it together:

<!-- Import our javascript file -->
<script src="text-processing.js"></script>

and here it is all together (index.html):

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Text Processing</title>

  <!-- Import our css styles -->
  <link rel="stylesheet" href="styles.css">
</head>
<body>
  <div class="main">
        <h2 class="main-header">Comment text analysys</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-button" onclick="onAnalyzeButtonClick()">Analyze...</button>
        </section>
        <section class="main-result">
            <p id="main-result-block" class="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>

Next, let’s create some simple styling for the 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; }

And finally, let’s create our JavaScript file (text-processing.js):

To begin with, let’s write constants such as the request URL and request headers (as we did before):

// 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': '7xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
  , 'Content-Type': 'application/x-www-form-urlencoded'
};

Now we create a request based on the text entered by the user:

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))
};

Here comment is the text that the user entered, and callback is a function that will do something with the response from the server in the future.

In the beginning, we created the data object based on the API documentation. Then we translated this object into a special format application/x-www-form-urlencoded using the Qs library.

As a result, we will need to make a request like in the previous examples:

  • get the result
  • call the callback function
  • and send to it a response from the server

Now we need a function that we can pass as a callback to the previous one, that is, a function that does something with the result, namely, it displays it to the user.

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;
};

Perhaps we also need a function that will do something if the user has not entered anything and pressed the button. Here we make the result block invisible by applying the class invisible to it and display the message.

const handleEmptyComment = () => {
  const resultBlockElement = document.getElementById('main-result-block');
  resultBlockElement.classList.add('invisible');
  return alert('Your comment is empty =(');
};

We also need to create a handler function that will work when a button is pressed and combine everything we wrote before:

// 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);
};

Finally, we get the following file:

// 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;
};

Our click handler (onAnalyzeButtonClick) is added to the button.

<button class="main-analyze-button" onclick="onAnalyzeButtonClick()">Analyze...</button>

The app is ready! We have implemented Anger Management with Javascript, and now every user will be able to understand what emotions their comments express:

This is image title

You may also like: What the difference between REST API and RESTful API?.

Conclusion

In this article, we explored the possibilities of JavaScript when working with the REST API, studied the concept of CRUD and its implementation using JavaScript, and also created our own application that has the capabilities of AI text sentiment analysis.

Thank you for reading ! Please share if you liked it!

javascript api restapi crud axios

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Top 10 API Security Threats Every API Team Should Know

Learn what are the most important API security threats engineering leaders should be aware of and steps you can take to prevent them

Public ASX100 APIs: The Essential List

The method used for this initial research was to obtain a list of the ASX100 (as of 18 September 2020). Then work through each company looking at the following

Create Asp Net Web API for CRUD operation | CRUD Using Asp Net Api

LIKE | COMMENT | SHARE | SUBSCRIBE Web API CRUD Operations Using Asp Net MVC and Entity Framework Contents * Web API Project For CRUD Operations - Insert Upd...

What Are Good Traits That Make Great API Product Managers

What is API product management and what can you be doing to be a better API product manager — get aligned with SaaS and enterprise software requirements. This guide lays out what is API product management and some of the things you should be doing to be a good product manager.

Consume Web API Post method in ASP NET MVC | Calling Web API | Rest API Bangla Tutorial

LIKE | COMMENT | SHARE | SUBSCRIBE In this tutorial, I will discussed about how to consume Web API Get method and display records in the ASP.NET View. Here, ...