How To Use An API With JavaScript (Beginner's Guide) (JavaScript API Tutorial)
How To Use An API With JavaScript (Beginner's Guide) (JavaScript API Tutorial)
Blog » API Tutorials » JavaScript API Tutorials » How To Use an API with JavaScript (The Complete Beginner’s Guide)
The modern web development world is impossible to imagine without JavaScript. Over the years of its growth, this language has gone from a small add-on to
Browse Most Popular APIs
a multifunctional and powerful tool. Today JavaScript successfully helps developers with both frontend and backend work.
Often the application functionality is mainly related to interaction with various APIs. If you are faced with the task of accessing the API in your JavaScript
application and don’t know where to start, this tutorial will help you figure it out quickly.
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.
10/8/23, 4:15 PM How To Use an API with JavaScript (Beginner's Guide) [JavaScript API Tutorial]
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 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.
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 examples 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.
10/8/23, 4:15 PM How To Use an API with JavaScript (Beginner's Guide) [JavaScript API Tutorial]
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
APIs mentioned in this article
this API from the list. JAAS API through RapidAPI is free, so you can create as many JSON objects as you want.
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. The API
Endpoints subsection includes navigation, a list of endpoints, the documentation of the currently selected endpoint, and a code snippet (available in 8
different programming languages) to help you get started with your code.
10/8/23, 4:15 PM How To Use an API with JavaScript (Beginner's Guide) [JavaScript API Tutorial]
We will go through all CRUD actions: create, read, update, delete. For each of these actions, JAAS API provides a corresponding endpoint.
10/8/23, 4:15 PM How To Use an API with JavaScript (Beginner's Guide) [JavaScript API Tutorial]
Browse APIs
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.
10/8/23, 4:15 PM How To Use an API with JavaScript (Beginner's Guide) [JavaScript API Tutorial]
Next, we create an object/dictionary with constant headers for RapidAPI, which are required during accessing. Since these headers
Browse willAPIs
Most Popular be in each request,
they also need to be put into a separate variable.
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 = '';
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.
// Save the unique id that the server gives to our object APIs mentioned in this article
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. Browse Most Popular APIs
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
}
}
"3060e599-b758-44cc-9eb4-8fda050b76d2"
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.
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:
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.
10/8/23, 4:15 PM How To Use an API with JavaScript (Beginner's Guide) [JavaScript API Tutorial]
As a result, after executing the code, we have the following response from the server:
APIs mentioned in this article
{
"_id": "3060e599-b758-44cc-9eb4-8fda050b76d2",
"body": {
"name": "John",
"surname": "Doe",
"age": 20,
"score": 4
}
Browse Most Popular APIs
}
4. Now we are testing the DELETE method, that is, deleting an object. In order to delete an object, simply execute the following code:
{
"_id": "3060e599-b758-44cc-9eb4-8fda050b76d2",
"message": "Data Deleted"
}
5. Great, but let’s see what happens if we try to retrieve the deleted object using the GET request:
We received the answer that this object no longer exists. Everything works as we expected.
APIs mentioned in this article
{
"errors": [
"Item not found"
]
}
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:
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.
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.
Browse APIs
Example: How to Build a ‘Comment Sentiment Analyzer’ App (with APIs & JavaScript)
Browse Most Popular APIs
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.
To send requests, we will continue to use the axios library. You will also need the qs library to encode requests.
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
APIs mentioned in this article
register by clicking on the ’Sign Up’ button on RapidAPI menu.
As mentioned earlier, you can register in any convenient way: Browse Most Popular APIs
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.
10/8/23, 4:15 PM How To Use an API with JavaScript (Beginner's Guide) [JavaScript API Tutorial]
As we can see, API returns JSON with a negative assessment, so apparently, everything works as it should.
Now we will create our small application for analyzing the sentiment of comments.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Text Processing</title>
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;
10/8/23, 4:15 PM How To Use an API with JavaScript (Beginner's Guide) [JavaScript API Tutorial]
}
.main-input-comment { margin-bottom: 20px; } APIs mentioned in this article
.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 { Browse Most Popular APIs
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 }
To begin with, let’s write constants such as the request URL and request headers (as we did before):
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.
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.
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.
We also need to create a handler function that will work when a button is pressed and combine everything we wrote before:
// 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 = '';
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:
10/8/23, 4:15 PM How To Use an API with JavaScript (Beginner's Guide) [JavaScript API Tutorial]
Browse APIs
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.
Related Links
• With NodeJS
• With VueJS
• With Python
• With PHP
• With Ruby
• With C#
• in Google Sheets
• How to Create a Node.JS/JavaScript API
Related JS Tutorials
• W3 JS tutorials
FAQ
« How to Use Interzoid’s Matching APIs for Data Quality (Exclusively on RapidAPI) APIs mentioned in this article
Kelly Arellano
Search
Comments
Alex says
JANUARY 21, 2020 AT 6:12 AM
Started with the guide and couldn’t find API “JAAS – JSON as a service”.
Reply
10/8/23, 4:15 PM How To Use an API with JavaScript (Beginner's Guide) [JavaScript API Tutorial]
Reply
Jason says
APRIL 6, 2020 AT 3:03 PM
Reply
Hi Jason,
It looks like the provider of the API has deleted that specific API. Is there a specific function you’re looking for?
Thanks!
Reply
lisa says
MAY 6, 2020 AT 7:33 AM
10/8/23, 4:15 PM How To Use an API with JavaScript (Beginner's Guide) [JavaScript API Tutorial]
hello thank you but your API example cannot work because they want a CC before you get the free limited API access
APIs mentioned in this article
Lisa
Reply
Hi Lisa,
Thanks
Reply
mb says
JUNE 2, 2020 AT 7:33 AM
Please update this article: we cant do the example with the JAAS – JSON as a service API.
Reply
zuki says
OCTOBER 8, 2020 AT 6:29 AM
Pls could you update your post and make a new one. thank you
Reply
10/8/23, 4:15 PM How To Use an API with JavaScript (Beginner's Guide) [JavaScript API Tutorial]
JAAS API is not available. Can you please update the tutorial using another API.
Thanks
Reply
Chris says
FEBRUARY 16, 2021 AT 9:09 PM
Tutorial sounds great in theory until I got stuck at Step 1 because JAAS isn’t found at RapidAPI.
Reply
Rapid API admins please either remove this tutorial or update it to include and API that is on the marketplace.
Reply
Couldn’t find the JAAS API mentioned. Not pretty useful tutorial.
Browse APIs »
API Guides
API Courses
API Glossary
API Testing
10/8/23, 4:15 PM How To Use an API with JavaScript (Beginner's Guide) [JavaScript API Tutorial]
API Management
APIs mentioned in this article
About
Build APIs
Careers
Contact Us
Write for Us
API Directory
Press Room
Privacy Policy
Terms of Use