Do you think IIT Guwahati certified course can help you in your career?
No
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.
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.
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
Step 2: Navigate to the created folder
cd restful-api-in-expressJS/
Step 3: Initializing it with a package.json file
npm init -y
Step 4: Installing Express.js
npm install express
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
app.js file was created successfully.
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
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.
GET Request
Used to retrieve data from a specified resource, like fetching a list of items or a single item.
PUT Request
Updates an existing resource or creates a new one if it doesn't exist at a specific URL.
DELETE Request
Removes a resource specified by its URL, usually deleting a record or data entry from the server.
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.