Basics of Using API in Javascript - ByteScout
  • Home
  • /
  • Blog
  • /
  • Basics of Using API in Javascript

Basics of Using API in Javascript

The web development world is incomplete without Javascript as it has evolved from an essential add-on to a robust tool for developers in web development. It does not only work on the front or back-end but on both ends to create a prosperous website or application. Additionally, as the users need mechanisms to create a communication channel between their front-end and back-end, they create API endpoints to serve this purpose.

Table of Contents:

  1. What is an API?
  2. What is an Endpoint?
  3. API calls using HTTP request methods
  4. POST Method
  5. GET Method
  6. DELETE Method
  7. Error Handling

Basics of Using API in Javascript

It is important to note that the users store sensitive data such as keys, user passwords, and private data on the back-end and the user-interface (UI) on the front-end to secure their application or website.

What is an API?

API stands for Application Program Interface, which consists of rules for the communication between client and server-side of an application or the communication between two software. It determines the request methods, format, content type, and content body of the request and who can communicate with the API. Additionally, it uses access tokens or keys in the headers to further secure the endpoints.

This tutorial mainly covers the web API that uses the HTTP request for communication. In this case, the user or some event triggers an API call to a publicly available URL or endpoint to request some JSON data available there or accessible from there.

What is an Endpoint?

In order to use an API, the users must know the concept of the API endpoint. In most cases, the API endpoints are the specific addresses on which some data is present that the users want to access. Furthermore, it is a convention that the endpoints’ names correspond to the data or service it provides.  For instance, an endpoint such as https://example.com/api/users/ represents some users’ data, and the user can request that data using some API. Moreover, the responses that come from the endpoints are usually in JSON form.

Methods of requesting API

Following are the four basic API request methods and their explanation:

HTTP Request method Action Description
POST Create Creates a new data form or resource
PUT Update Updates an existing data or resource
GET Read Reads/ retrieves the requested resource or data.
DELETE Delete / Remove Deletes the requested resource or data

The Javascript Fetch() API

The fetch API is one of the API that the developers can use in Javascript to access the endpoints. Its javascript interface allows accessing and manipulating the endpoints’ data using requests and responses. Moreover, it provides a logical and easy implementation to fetch data from the HTTP endpoints asynchronously.

Below is the basic implementation of the fetch request:

fetch(‘https://example.com/api/users’)
.then(response => response.json)
.then(data => return data)
.catch(error => console.log(error);

In the above example, the fetch function fetches the data from example/api/users, converts it to the JSON format using the json() function, and console logs the obtained data. It is important to note that the fetch response itself is not in the JSON format, but the users can choose to extract the JSON from it using the above function.

API calls using HTTP request methods

Below is the implementation of fetch API for the above-discussed HTTP request methods:

POST Method

The users use the POST request to create some resource. Therefore, in the below code sample, the user wants to store a user’s data by calling /API/user/ endpoint.

var user_data = {
“name”: “Sarah”,
“username” : “sarah@gmail.com”,
“phone”: “+1234567890”,
“password”: “password1234”
}
async function request(){
const response = await fetch (‘https://exampletutorial.com/api/user, {
method : ‘POST’,
headers: {
      ‘Content-Type’: ‘application/json’
},
body: JSON.stringify(user_data);
});
const responseJSON = response.json();
console.log(responseJSON);
return responseJSON;
}

Explanation

In the above example, the user is first creating a JSON object which contains the information that the user wants to send to the endpoint. Like APIs, the endpoints have some specified rules for the requests as well. The rules include the body format, the data the endpoint needs to process the request, and the headers. However, the endpoint developers or creators inform the users before-hand about these rules to call the API. Therefore, no random user can manipulate the data according to their own will without knowing the communication protocols.

In the above example, the user assumes that the endpoint requires the user’s email, phone number, name, and password to create a new user, which he sends in a JSON object. However, the fetch API requires him to stringify it before sending it. Therefore, he uses the stringify function for it.

Await and Async

The developers use the await when they want to fetch the response before moving to the next instructions. As most of the functions are synchronous and the program moves on to execute the next instructions side by side without waiting for some promise to fulfill. This synchronous behavior makes the execution faster and smoother. However, in some scenarios, the instructions after the fetch function depend on the API’s response, and the synchronous execution produces errors in the program. Therefore, the developers use the “await” keyword to wait for the API’s response inside the asynchronous function.

Note: The users can only use “await” inside the async function.

PUT Method

The users use the PUT method to update any existing data or resource. The format of the request is similar to the above PUT request with the change of method option. The endpoint developers sometimes design their endpoints to create the resource using the request body or return an error if the resource does not exist already.

GET Method

The users use the GET request method to retrieve some data using the API. The GET request does not need the content body because it only requests data from the endpoint.

Below is the sample code to demonstrate its working:

async function request(){
const response = await fetch (‘https://exampletutorial.com/api/user, {
method : ‘GET’,
headers: {
      ‘Content-Type’: ‘application/json’
},
});

const responseJSON = response.json();
console.log(responseJSON);
return responseJSON;
}

In the above example, the user is requesting the user’s data from the endpoint, and the endpoint will send all the data it has stored in the database or some variable in the back-end as the API’s response.  The users can design their endpoints to make it possible for other users to request the specified data from them, such as the user should be able to retrieve data based on the user name.

DELETE Method

The users use the DELETE method to request the other software or the application’s server to delete the specific or complete data. It is also similar to the GET method above.

Error Handling

The fetch API returns promises and can sometimes fail because of the connectivity issue of the user’s network or the CORS error. Therefore, the user needs to have a method to handle the error and know that the fetch request has been successful.

Below is the example to demonstrate the code for error handling:

fetch(‘https://example.com/api/users’)
.then(response => {
         If (!response.ok){
             console.log(‘error occurred’);  //error occurred due to network issue etc
         }
         return response.json();
})
.catch(error => {
         console.log(‘error occurred in fetch’);     //error occurred due to issue in fetch function
}
   

About the Author

ByteScout Team ByteScout Team of Writers ByteScout has a team of professional writers proficient in different technical topics. We select the best writers to cover interesting and trending topics for our readers. We love developers and we hope our articles help you learn about programming and programmers.  
prev
next