February 16, 2025

Md. Saad

In modern web development, interacting with REST APIs is a common task. Whether fetching data from a server, submitting forms, or performing CRUD operations, JavaScript provides various ways to consume RESTful services. In this blog, we'll explore how to build a REST API client in JavaScript using the Fetch API.
In modern web development, interacting with REST APIs is a common task. Whether fetching data from a server, submitting forms, or performing CRUD operations, JavaScript provides various ways to consume RESTful services. In this blog, we'll explore how to build a REST API client in JavaScript using the Fetch API.
REST (Representational State Transfer) is an architectural style defining constraints for creating web services. REST APIs follow a client-server architecture, where the client sends requests to the server, and the server responds with data. These APIs use standard HTTP methods to perform operations on resources, which are typically represented as URLs.
In a RESTful API, the five most commonly used HTTP methods correspond to CRUD (Create, Read, Update, Delete) operations:
These methods form the foundation of RESTful web services, ensuring structured and predictable interactions between clients and servers.
Also Read: How to use JavaScript Modules
The Fetch API is a built-in JavaScript feature that provides an easy way to make HTTP requests.
A GET request asks the server to return data for the specified resource without modification.
Suppose we want to get data from https://jsonplaceholder.typicode.com/posts/1, a dummy API. We can do so by sending a GET request to retrieve data and displaying it in the console. Here is an example:
async function getPost() {
try {
let response = await fetch('https://jsonplaceholder.typicode.com/posts/1');
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
let data = await response.json();
console.log('Retrieved Post:', data);
} catch (error) {
console.error('Error fetching post:', error);
}
}
getPost();A POST request sends data to the server to create a new resource, typically adding it to a database.
Suppose we want to send data to https://jsonplaceholder.typicode.com/posts/, a dummy API, to create a new post. We can do so by creating a new post and sending the POST request to the API. Here is an example :
async function createPost() {
const postData = {
title: 'New Post',
body: 'This is the content.',
userId: 1
};
try {
let response = await fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(postData)
});
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
let data = await response.json();
console.log('Post Created:', data);
} catch (error) {
console.error('Error creating post:', error);
}
}
createPost();A PUT request updates an existing resource entirely or creates it if it does not exist. We can use it to update an existing post by sending new data to the server. Here is a basic example:
async function updatePost() {
const updatedData = {
title: 'Updated Post',
body: 'Updated content.',
userId: 1
};
try {
let response = await fetch('https://jsonplaceholder.typicode.com/posts/1', {
method: 'PUT',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(updatedData)
});
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
let data = await response.json();
console.log('Post Updated:', data);
} catch (error) {
console.error('Error updating post:', error);
}
}
updatePost();A PATCH request modifies part of an existing resource without affecting the entire entity. Here is an example where we are updating specific fields of an existing post.
async function patchPost() {
const patchData = {
title: 'Partially Updated Title'
};
try {
let response = await fetch('https://jsonplaceholder.typicode.com/posts/1', {
method: 'PATCH',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(patchData)
});
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
let data = await response.json();
console.log('Post Partially Updated:', data);
} catch (error) {
console.error('Error updating post:', error);
}
}
patchPost();A DELETE request removes a specified resource from the server.
async function deletePost() {
try {
let response = await fetch('https://jsonplaceholder.typicode.com/posts/1', {
method: 'DELETE'
});
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
console.log('Post deleted successfully');
} catch (error) {
console.error('Error deleting post:', error);
}
}
deletePost();Building a REST API client in JavaScript is straightforward with the Fetch API. It provides a flexible and efficient way to make HTTP requests. By mastering these techniques, you'll be well-equipped to integrate RESTful services into your applications. Happy coding!
Want more tips on Javascript , Next.js and React.js? Follow staticmania.com.
Answer: A REST API (Representational State Transfer) is a web service that allows clients to communicate with servers using standard HTTP methods like GET, POST, PUT, PATCH, and DELETE. It is stateless, meaning each request from the client must contain all necessary information, and responses are typically returned in JSON format.
Answer: To make a GET request using the Fetch API, call fetch(url), check for a successful response, and parse the JSON data using response.json(). This allows you to retrieve and use data from an API in your application.
Answer: PUT replaces the entire resource with new data, while PATCH updates only the specified fields. PUT is used when you want to overwrite an existing record, whereas PATCH is used for partial updates to an existing resource.
Answer: To send a POST request, use fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) }). This sends the data as JSON to the server, typically creating a new resource.
Answer: Always check the response.ok before parsing JSON, use try...catch to handle network errors or invalid responses. This ensures your app gracefully manages failed API calls.
Answer: To delete a resource, send a DELETE request using fetch(url, { method: 'DELETE' }). If successful, the API usually returns a 204 No Content status, indicating the resource was removed.