How to Call REST APIs in JavaScript

Step-by-step guide on how to call rest APIs in JavaScript. Perform GET, POST, PUT, PATCH, and DELETE requests most effectively.

What is a REST API?

REST API (Representational State Transfer Application Programming Interface) is a set of rules and conventions for building and interacting with web services.

In simpler words, it is a web service that,  uses HTTP/HTTPS protocols like a webpage but returns JSON as a response. It works as a bridge between the back end and the front end. Then the JSON can be used to build user interfaces in web and mobile apps. 

Calling APIs in Javascript is super simple compared to other languages like Java, Kotlin, or Swift. JSON stands for JavaScript Object Notation) so it follows a similar structure to the JavaScript Objects. JSON encoding and decoding is natively supported by JavaScript. 

For calling any rest API we need the following things

  • The API endpoint (and URL at which the web service is listed)
  • Request Method(GET, POST, PUT, PATCH, and DELETE etc)
  • Request Body, and query
  • Headers 

See here the endpoint is mandatory and the default request type is GET, if you need to call other methods then need to mention the request type. Some endpoints require queries, bodies, or headers depending on their requirements.

Where to get the APIs?

APIs are mainly consumed by frontend engineers, and for production applications, will provided by your backend service. But here as we are exploring how to call APIs in javascript, will will use a free public API from JSON Placeholder for learning. 

{JSON} Placeholder 

Is a free service that you can explore learning API calls.


Follow these steps to perform GET, POST, PUT, PATCH, and DELETE API calls in JavaScript. We will use JavaScript's built-in fetch function to do all these API calls.

GET Request

Get request is used to get data from the web service by hitting a web URL.

Example:

Here we will get some posts from the JSON placeholder fake API

Endpoint: https://jsonplaceholder.typicode.com/posts

Request Code:

function GetRequest(){
fetch('https://jsonplaceholder.typicode.com/posts')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok ' + response.statusText);
}
return response.json();
})
.then(data => console.log(data))
.catch(error => console.error('There has been a problem with your fetch operation:', error));
}

window.onload = GetApi(); //calls the api when the page loads

POST Request

A POST request is used to submit some data to the web service. You need to add the method and the request body, here the API needs a body in a JSON format like this

{
title: 'foo',
body: 'bar',
userId: 1,
}

Example:

Endpoint: https://jsonplaceholder.typicode.com/posts

Method: POST

Body:  Needs to send the JSON

function PostRequest() {
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
title: 'foo',
body: 'bar',
userId: 1,
}),
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));

}

window.onload = PostRequest(); //calls the api when the page loads

PUT Request

A PUT request is used to update the existing data completely. You need to add the method and the request body, here the API needs a body in a JSON format like this

{
id: 1,
title: 'updated title',
body: 'updated body',
userId: 1,
}

Example:

Endpoint: https://jsonplaceholder.typicode.com/posts/1

Method: PUT

Body:  Needs to send the JSON

function PutRequest() {
fetch('https://jsonplaceholder.typicode.com/posts/1', {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
id: 1,
title: 'updated title',
body: 'updated body',
userId: 1,
}),
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));

}

window.onload = PutRequest(); //calls the api when the page loads

PATCH Request

A PATCH request is used to update the existing data partially. You need to add the method and the request body, here the API needs a body in a JSON format like this

{
title: 'partially updated title',
}

Example:

Endpoint: https://jsonplaceholder.typicode.com/posts/1

Method: PATCH

Body:  Needs to send the JSON

function PatchRequest() {
fetch('https://jsonplaceholder.typicode.com/posts/1', {
method: 'PATCH',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
title: 'partially updated title',
}),
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));

}

window.onload = PatchRequest(); //calls the api when the page loads

DELETE Request

A DELETE request is used to delete some data. You need to add the method here.

Example:

Endpoint: https://jsonplaceholder.typicode.com/posts/1

Method: DELETE

function DeleteRequest() {
fetch('https://jsonplaceholder.typicode.com/posts/1', {
method: 'DELETE',
})
.then(response => {
if (response.ok) {
console.log('Post deleted successfully');
} else {
throw new Error('Network response was not ok ' + response.statusText);
}
})
.catch(error => console.error('Error:', error));

}

window.onload = DeleteRequest(); //calls the api when the page loads


Here these examples demonstrate the basic use of the REST API, with more complex uses you need to follow the API documentation given by your API provider. But the basics remain the same.