Table of contents
1.
Introduction
2.
What is RESTFUL API?
3.
What is ExpressJS?
4.
Setting Up a RestFul API in ExpressJS
4.1.
Step 1: Create a folder
4.2.
Step 2: Navigate to the created folder
4.3.
Step 3: Initializing it with a package.json file
4.4.
Step 4: Installing Express.js
4.5.
Step 5: Create a file
4.6.
Step 6: Creating the Express Application
4.7.
Step 7: Defining Routes and Handlers
4.8.
Step 8: Starting the Server
4.9.
Step 9: Testing
4.9.1.
POST Request
4.9.2.
GET Request
4.9.3.
PUT Request
4.9.4.
DELETE Request
5.
Frequently Asked Questions
5.1.
What is the difference between front-end and back-end development?
5.2.
What are some popular programming languages for web development?
5.3.
What is agile software development?
6.
Conclusion
Last Updated: Feb 5, 2025
Medium

RestFul API in ExpressJS

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

The internet's infrastructure now depends on data exchange between applications and services. A popular architectural style for creating networked applications, especially web services, is Representational State Transfer (REST). 

Express.js, a quick and straightforward web framework for Node.js, provides a strong framework for creating RESTful APIs. In this article, we will learn about RESTful APIs in Express.js. 

RestFul API in ExpressJS

What is RESTFUL API?

Before describing REST API, we need to understand what an API is. API stands for application programmable interface, a communication method that can be used between applications or computers to allow integration between themselves. An API call starts with one party requesting the API for a specific resource; the API then responds with a response containing the requested resource or execution status. 

There exist different architectures of APIs, and one of them is REST. REST stands for representational state transfer and utilizes HTTP to handle the communication. When using REST, two parties must be involved: a client that initiates a request and a server that responds with the requested resource or status code. In the REST architecture, a set of instructions is commonly used: GET, POST, PUT, PATCH, and DELETE. The named instructions manipulate or fetch data from a given resource.

What is ExpressJS?

Express.js is a framework that runs on the Node.js JavaScript runtime and can be used to develop large or small applications, primarily web services. Express.js uses 30 third-party dependencies required to power the framework; this includes functionalities similar to routing and parsing incoming data. 

Express.js runs Node.js, which allows the use of regular JavaScript outside of the web browser with the help of the Google V8 engine. Node.js provides an event-driven architecture containing an event loop that can simulate a multi-threaded environment using only one thread. Using the event loop, Node.js can split the work more efficiently in the case of I/O by placing the current task on hold. 

ExpressJS logo

Besides the event loop, Node.js has a thread pool called workers, which handles “expensive” tasks. The workers can then run a specific request without interfering with the event loop. JavaScript, which is the language that Express.js uses, is an interpreted language. JavaScript is expected to run slower than compiled languages like C++ or C since compiled code is converted directly to machine code executed in run time.

Setting Up a RestFul API in ExpressJS

Open Terminal on your PC.

Step 1: Create a folder

mkdir restful-api-in-expressJS
Create a folder(output)

Step 2: Navigate to the created folder

cd restful-api-in-expressJS/
Navigate to the created folder(output)

Step 3: Initializing it with a package.json file

npm init -y
Initializing it with a package.json file(Output)

Step 4: Installing Express.js

npm install express
Installing Express.js(output)

Step 5: Create a file

Create a JavaScript file in the project directory after installing Express.js. The Entry point for the Express application will be (app.js) this file.

touch app.js
Create a file(Output)

app.js file was created successfully.

file created(Output)

Step 6: Creating the Express Application


const express = require('express');
const app = express();
const port = 3000;

app.use(express.json());

app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});

Step 7: Defining Routes and Handlers

// Sample data for our API
let todos = [
{ id: 1, text: 'Hello Ninjas' },
{ id: 2, text: 'Coding Ninjas' },
  ];
 
  // Get all todos
  app.get('/api/aditya', (req, res) => {
res.json(todos);
  });
 
  // Get a specific todo by ID
  app.get('/api/aditya/:id', (req, res) => {
const id = parseInt(req.params.id);
const todo = todos.find((t) => t.id === id);
 
if (!todo) {
   return res.status(404).json({ message: 'Error' });
}
 
res.json(todo);
  });
 
  // Create a new todo
  app.post('/api/aditya', (req, res) => {
const newTodo = req.body;
todos.push(newTodo);
res.status(201).json(newTodo);
  });
 

  // Update a todo by ID
  app.put('/api/aditya/:id', (req, res) => {
const id = parseInt(req.params.id);
const updatedTodo = req.body;
const index = todos.findIndex((t) => t.id === id);
 
if (index === -1) {
   return res.status(404).json({ message: 'Error' });
}
 
todos[index] = updatedTodo;
res.json(updatedTodo);
  });
 
  // Delete a todo by ID
  app.delete('/api/aditya/:id', (req, res) => {
const id = parseInt(req.params.id);
const index = todos.findIndex((t) => t.id === id);
 
if (index === -1) {
   return res.status(404).json({ message: 'Error' });
}
 
todos.splice(index, 1);
res.sendStatus(204); 
  });

Step 8: Starting the Server

node app.js
Starting the Server(Output)

Step 9: Testing

  • Open Postman tool for Testing:
  • http://localhost:3000/api/aditya/ the section labeled "Enter Request URL."
  • Switch the the HTTP method to POST method.
  • Next, pick JSON (application/json).
  • Make the following body entry:
{
  id: 3, text: 'Coding'
}
  • Click the Send button.
  • The response will be displayed as 201 (Created).

POST Request

Creates a new resource, usually with data sent in the request body.

POST Request

GET Request

Used to retrieve data from a specified resource, like fetching a list of items or a single item.

GET Request

PUT Request

Updates an existing resource or creates a new one if it doesn't exist at a specific URL.

PUT Request

DELETE Request

Removes a resource specified by its URL, usually deleting a record or data entry from the server.

DELETE Request

Frequently Asked Questions

What is the difference between front-end and back-end development?

Front-end development aims to design a website's or application's user interface and user experience. It uses HTML, CSS, and JavaScript technologies. Back-end development utilizes languages like Python, Node.js, or Java to deal with server-side logic and database management.

What are some popular programming languages for web development?

Programming languages, including JavaScript, Python, Ruby, PHP, and Java, are famous for web development. JavaScript is essential for front-end web development, while back-end development can involve a variety of languages.

What is agile software development?

Agile software development methodology highlights flexibility, collaboration, and customer feedback. It involves iterative development, where software is developed incrementally in short cycles and allows for changes based on evolving requirements.

Conclusion

In this article, we learn about RestFul API in ExpressJS. We also learn about RestFul API and ExpressJS. We concluded the article by setting up RestFul API in ExpressJS.

To better understand the topic, refer to 

For more information, refer to our Guided Path on CodeStudio to upskill yourself in PythonData Structures and AlgorithmsCompetitive ProgrammingSystem Design, and many more! 

Head over to our practice platform, CodeStudio, to practice top problems, attempt mock tests, read interview experiences and interview bundles, follow guided paths for placement preparations, and much more!
Happy Learning!

Live masterclass