Introduction
REST APIs allow applications to communicate with each other using HTTP requests and responses. Node.js is widely used for building fast and scalable REST APIs. In this chapter, you will practice creating REST API endpoints, handling GET, POST, PUT, PATCH, and DELETE requests, working with JSON data, route parameters, query parameters, status codes, and building a simple CRUD API step by step. Node.js REST API practice questions with solutions help to understand the concepts.
Question 1: How do you create a basic REST API using Node.js and Express?
Problem
Create a simple REST API with a /api endpoint that returns a JSON response.
Solution
Install Express:
npm init -y
npm install express
Create index.js:
const express = require("express");
const app = express();
app.get("/api", (req, res) => {
res.json({
success: true,
message: "Welcome to the Node.js REST API"
});
});
app.listen(3000, () => {
console.log(
"Server running on http://localhost:3000"
);
});
Run:
node index.js
Output
Open:
http://localhost:3000/api
You will receive:
{
"success": true,
"message": "Welcome to the Node.js REST API"
}
Step-by-Step Explanation
Import Express:
const express = require("express");
Create the Express application:
const app = express();
Create a GET endpoint:
app.get("/api", (req, res) => {
Send JSON:
res.json({
success: true,
message: "Welcome to the Node.js REST API"
});
Finally, start the server:
app.listen(3000);
Question 2: How do you create a GET REST API?
Problem
Create a REST API that returns a list of students.
Solution
const express = require("express");
const app = express();
const students = [
{
id: 1,
name: "Rahul",
course: "Node.js"
},
{
id: 2,
name: "Priya",
course: "JavaScript"
},
{
id: 3,
name: "Aman",
course: "Python"
}
];
app.get("/api/students", (req, res) => {
res.json({
success: true,
count: students.length,
students: students
});
});
app.listen(3000, () => {
console.log(
"Server running on http://localhost:3000"
);
});
Output
Request:
GET /api/students
Response:
{
"success": true,
"count": 3,
"students": [
{
"id": 1,
"name": "Rahul",
"course": "Node.js"
},
{
"id": 2,
"name": "Priya",
"course": "JavaScript"
},
{
"id": 3,
"name": "Aman",
"course": "Python"
}
]
}
Step-by-Step Explanation
Create an array:
const students = [
{
id: 1,
name: "Rahul",
course: "Node.js"
}
];
Create the GET route:
app.get("/api/students", (req, res) => {
Return the data:
res.json({
success: true,
count: students.length,
students: students
});
Question 3: How do you create a REST API using POST?
Problem
Create an API that accepts a student’s name and course and adds a new student.
Solution
const express = require("express");
const app = express();
app.use(express.json());
const students = [
{
id: 1,
name: "Rahul",
course: "Node.js"
}
];
app.post("/api/students", (req, res) => {
const newStudent = {
id: students.length + 1,
name: req.body.name,
course: req.body.course
};
students.push(newStudent);
res.status(201).json({
success: true,
message: "Student created successfully.",
student: newStudent
});
});
app.listen(3000, () => {
console.log(
"Server running on http://localhost:3000"
);
});
Request Body
Send a POST request to:
POST /api/students
JSON body:
{
"name": "Neha",
"course": "Data Analytics"
}
Response
{
"success": true,
"message": "Student created successfully.",
"student": {
"id": 2,
"name": "Neha",
"course": "Data Analytics"
}
}
Step-by-Step Explanation
This middleware allows Express to read JSON request bodies:
app.use(express.json());
The request body is available through:
req.body
For example:
req.body.name
and:
req.body.course
A new object is created:
const newStudent = {
id: students.length + 1,
name: req.body.name,
course: req.body.course
};
Then it is added:
students.push(newStudent);
Question 4: How do you use route parameters in a REST API?
Problem
Create an API that returns one student based on an ID.
Solution
const express = require("express");
const app = express();
const students = [
{
id: 1,
name: "Rahul",
course: "Node.js"
},
{
id: 2,
name: "Priya",
course: "JavaScript"
},
{
id: 3,
name: "Aman",
course: "Python"
}
];
app.get("/api/students/:id", (req, res) => {
const id = Number(req.params.id);
const student = students.find(
student => student.id === id
);
if (!student) {
return res.status(404).json({
success: false,
message: "Student not found."
});
}
res.json({
success: true,
student: student
});
});
app.listen(3000, () => {
console.log(
"Server running on http://localhost:3000"
);
});
Request
GET /api/students/2
Response
{
"success": true,
"student": {
"id": 2,
"name": "Priya",
"course": "JavaScript"
}
}
Step-by-Step Explanation
The :id is a route parameter:
/api/students/:id
Its value can be accessed using:
req.params.id
We convert it to a number:
const id = Number(req.params.id);
Then search the array:
const student = students.find(
student => student.id === id
);
If no student is found:
return res.status(404).json({
success: false,
message: "Student not found."
});
Question 5: How do you use query parameters in a REST API?
Problem
Create an API that allows users to filter students by course.
Solution
const express = require("express");
const app = express();
const students = [
{
id: 1,
name: "Rahul",
course: "Node.js"
},
{
id: 2,
name: "Priya",
course: "JavaScript"
},
{
id: 3,
name: "Aman",
course: "Node.js"
}
];
app.get("/api/students", (req, res) => {
const course = req.query.course;
if (!course) {
return res.json({
success: true,
students: students
});
}
const filteredStudents =
students.filter(
student =>
student.course.toLowerCase() ===
course.toLowerCase()
);
res.json({
success: true,
students: filteredStudents
});
});
app.listen(3000, () => {
console.log(
"Server running on http://localhost:3000"
);
});
Request
GET /api/students?course=Node.js
Response
{
"success": true,
"students": [
{
"id": 1,
"name": "Rahul",
"course": "Node.js"
},
{
"id": 3,
"name": "Aman",
"course": "Node.js"
}
]
}
Step-by-Step Explanation
The query parameter is:
?course=Node.js
Express provides it through:
req.query.course
We then filter the students:
students.filter(
student =>
student.course.toLowerCase() ===
course.toLowerCase()
);
Route Parameter vs Query Parameter
Route parameter:
/api/students/2
Query parameter:
/api/students?course=Node.js
Question 6: How do you update data using PUT?
Problem
Create an API that completely updates a student’s information.
Solution
const express = require("express");
const app = express();
app.use(express.json());
const students = [
{
id: 1,
name: "Rahul",
course: "Node.js"
},
{
id: 2,
name: "Priya",
course: "JavaScript"
}
];
app.put("/api/students/:id", (req, res) => {
const id = Number(req.params.id);
const student = students.find(
student => student.id === id
);
if (!student) {
return res.status(404).json({
success: false,
message: "Student not found."
});
}
student.name = req.body.name;
student.course = req.body.course;
res.json({
success: true,
message: "Student updated successfully.",
student: student
});
});
app.listen(3000, () => {
console.log(
"Server running on http://localhost:3000"
);
});
Request
PUT /api/students/1
Body:
{
"name": "Rahul Kumar",
"course": "Data Science"
}
Response
{
"success": true,
"message": "Student updated successfully.",
"student": {
"id": 1,
"name": "Rahul Kumar",
"course": "Data Science"
}
}
Step-by-Step Explanation
Find the student:
const student = students.find(
student => student.id === id
);
Update the values:
student.name = req.body.name;
student.course = req.body.course;
Return the updated resource.
Question 7: How do you partially update data using PATCH?
Problem
Create an API that changes only the course of a student without replacing the entire student object.
Solution
const express = require("express");
const app = express();
app.use(express.json());
const students = [
{
id: 1,
name: "Rahul",
course: "Node.js"
},
{
id: 2,
name: "Priya",
course: "JavaScript"
}
];
app.patch("/api/students/:id", (req, res) => {
const id = Number(req.params.id);
const student = students.find(
student => student.id === id
);
if (!student) {
return res.status(404).json({
success: false,
message: "Student not found."
});
}
if (req.body.name !== undefined) {
student.name = req.body.name;
}
if (req.body.course !== undefined) {
student.course = req.body.course;
}
res.json({
success: true,
message: "Student updated successfully.",
student: student
});
});
app.listen(3000, () => {
console.log(
"Server running on http://localhost:3000"
);
});
Request
PATCH /api/students/1
Body:
{
"course": "Data Analytics"
}
Response
{
"success": true,
"message": "Student updated successfully.",
"student": {
"id": 1,
"name": "Rahul",
"course": "Data Analytics"
}
}
Step-by-Step Explanation
We check whether name was supplied:
if (req.body.name !== undefined) {
student.name = req.body.name;
}
Then independently check course:
if (req.body.course !== undefined) {
student.course = req.body.course;
}
Therefore, only the supplied properties are changed.
PUT vs PATCH
PUT
→ Generally replaces/updates the resource representation.
PATCH
→ Partially updates the resource.
Question 8: How do you delete data using DELETE?
Problem
Create an API that deletes a student using the student’s ID.
Solution
const express = require("express");
const app = express();
const students = [
{
id: 1,
name: "Rahul",
course: "Node.js"
},
{
id: 2,
name: "Priya",
course: "JavaScript"
},
{
id: 3,
name: "Aman",
course: "Python"
}
];
app.delete("/api/students/:id", (req, res) => {
const id = Number(req.params.id);
const studentIndex = students.findIndex(
student => student.id === id
);
if (studentIndex === -1) {
return res.status(404).json({
success: false,
message: "Student not found."
});
}
const deletedStudent =
students.splice(studentIndex, 1)[0];
res.json({
success: true,
message: "Student deleted successfully.",
student: deletedStudent
});
});
app.listen(3000, () => {
console.log(
"Server running on http://localhost:3000"
);
});
Request
DELETE /api/students/2
Response
{
"success": true,
"message": "Student deleted successfully.",
"student": {
"id": 2,
"name": "Priya",
"course": "JavaScript"
}
}
Step-by-Step Explanation
Find the student’s index:
const studentIndex = students.findIndex(
student => student.id === id
);
If the index is -1, the student does not exist.
Otherwise:
students.splice(studentIndex, 1);
removes the student from the array.
Question 9: How do you use proper HTTP status codes in a REST API?
Problem
Create an API that uses appropriate status codes for successful creation, missing resources, and successful deletion.
Solution
const express = require("express");
const app = express();
app.use(express.json());
const students = [];
app.post("/api/students", (req, res) => {
const student = {
id: students.length + 1,
name: req.body.name,
course: req.body.course
};
students.push(student);
res.status(201).json({
success: true,
message: "Student created.",
student: student
});
});
app.get("/api/students/:id", (req, res) => {
const id = Number(req.params.id);
const student = students.find(
student => student.id === id
);
if (!student) {
return res.status(404).json({
success: false,
message: "Student not found."
});
}
res.status(200).json({
success: true,
student: student
});
});
app.delete("/api/students/:id", (req, res) => {
const id = Number(req.params.id);
const index = students.findIndex(
student => student.id === id
);
if (index === -1) {
return res.status(404).json({
success: false,
message: "Student not found."
});
}
students.splice(index, 1);
res.status(200).json({
success: true,
message: "Student deleted successfully."
});
});
app.listen(3000, () => {
console.log(
"Server running on http://localhost:3000"
);
});
Common Status Codes
| Status Code | Meaning |
|---|---|
200 | Request successful |
201 | Resource created |
204 | Successful request with no response body |
400 | Bad request |
401 | Authentication required/failed |
403 | Access forbidden |
404 | Resource not found |
500 | Internal server error |
Step-by-Step Explanation
When a new student is created:
res.status(201)
When data is successfully returned:
res.status(200)
When a student cannot be found:
res.status(404)
Question 10: How do you build a complete CRUD REST API?
Problem
Build a beginner-friendly REST API that supports:
- Create student
- Read all students
- Read one student
- Update student
- Delete student
Solution
Create index.js:
const express = require("express");
const app = express();
app.use(express.json());
let students = [
{
id: 1,
name: "Rahul",
course: "Node.js"
},
{
id: 2,
name: "Priya",
course: "JavaScript"
}
];
let nextId = 3;
// GET all students
app.get("/api/students", (req, res) => {
res.status(200).json({
success: true,
count: students.length,
students: students
});
});
// GET one student
app.get("/api/students/:id", (req, res) => {
const id = Number(req.params.id);
const student = students.find(
student => student.id === id
);
if (!student) {
return res.status(404).json({
success: false,
message: "Student not found."
});
}
res.status(200).json({
success: true,
student: student
});
});
// CREATE student
app.post("/api/students", (req, res) => {
const {
name,
course
} = req.body;
if (!name || !course) {
return res.status(400).json({
success: false,
message: "Name and course are required."
});
}
const student = {
id: nextId++,
name: name,
course: course
};
students.push(student);
res.status(201).json({
success: true,
message: "Student created successfully.",
student: student
});
});
// UPDATE student
app.put("/api/students/:id", (req, res) => {
const id = Number(req.params.id);
const student = students.find(
student => student.id === id
);
if (!student) {
return res.status(404).json({
success: false,
message: "Student not found."
});
}
const {
name,
course
} = req.body;
if (!name || !course) {
return res.status(400).json({
success: false,
message: "Name and course are required."
});
}
student.name = name;
student.course = course;
res.status(200).json({
success: true,
message: "Student updated successfully.",
student: student
});
});
// DELETE student
app.delete("/api/students/:id", (req, res) => {
const id = Number(req.params.id);
const index = students.findIndex(
student => student.id === id
);
if (index === -1) {
return res.status(404).json({
success: false,
message: "Student not found."
});
}
const deletedStudent =
students.splice(index, 1)[0];
res.status(200).json({
success: true,
message: "Student deleted successfully.",
student: deletedStudent
});
});
app.listen(3000, () => {
console.log(
"Server running on http://localhost:3000"
);
});
Run the API
node index.js
Output:
Server running on http://localhost:3000
Test 1: Get All Students
GET /api/students
Test 2: Get One Student
GET /api/students/1
Test 3: Create Student
POST /api/students
Body:
{
"name": "Aman",
"course": "Python"
}
Test 4: Update Student
PUT /api/students/1
Body:
{
"name": "Rahul Kumar",
"course": "Data Science"
}
Test 5: Delete Student
DELETE /api/students/2
CRUD Summary
| Operation | HTTP Method | Endpoint |
|---|---|---|
| Create | POST | /api/students |
| Read All | GET | /api/students |
| Read One | GET | /api/students/:id |
| Update | PUT | /api/students/:id |
| Delete | DELETE | /api/students/:id |
Step-by-Step Explanation
The application uses:
app.use(express.json());
to read JSON request bodies.
The API stores student information in an array:
let students = [
{
id: 1,
name: "Rahul",
course: "Node.js"
}
];
The GET endpoint reads the data:
app.get("/api/students", ...)
The POST endpoint creates a resource:
app.post("/api/students", ...)
The PUT endpoint updates a resource:
app.put("/api/students/:id", ...)
The DELETE endpoint removes a resource:
app.delete("/api/students/:id", ...)
This is a basic CRUD REST API.
Key Takeaways
- REST APIs allow different applications to communicate through HTTP.
- Node.js and Express can be used to create REST APIs.
- REST APIs commonly return JSON data.
GETis generally used to retrieve resources.POSTis generally used to create resources.PUTis generally used to replace or update a resource representation.PATCHis generally used for partial updates.DELETEis generally used to remove resources.express.json()allows Express to read JSON request bodies.req.bodycontains JSON data sent by the client.req.paramscontains route parameters.req.querycontains query parameters.- Route parameters are useful for identifying specific resources.
- Query parameters are useful for filtering, searching, sorting, and pagination.
res.json()sends a JSON response.- HTTP status
200commonly represents a successful request. - HTTP status
201commonly represents successful resource creation. - HTTP status
400indicates a bad request. - HTTP status
404indicates that a requested resource was not found. - A CRUD API provides Create, Read, Update, and Delete operations.
- REST APIs normally separate resources from the operations performed on them.
- A simple array can be used for practice, but production applications normally use a database.
- Proper validation and error handling are important in real-world REST APIs.
FAQs
1. What is a REST API in Node.js?
A REST API is an interface that allows applications to communicate using HTTP methods and resources.
For example:
GET /api/students
can return a list of students.
Node.js with Express is commonly used to build REST APIs.
2. What are the main HTTP methods used in REST APIs?
The commonly used methods are:
GET
POST
PUT
PATCH
DELETE
They are commonly used for retrieving, creating, updating, partially updating, and deleting resources.
3. What is the difference between PUT and PATCH?
PUT is generally used to replace or update the representation of a resource.
PATCH is generally used to make a partial update.
For example, changing only a student’s course can be done with:
PATCH /api/students/1
with:
{
"course": "Data Analytics"
}
4. What is req.body in Express?
req.body contains data sent in the request body.
For JSON requests, you normally need:
app.use(express.json());
Then:
req.body.name
can access the name property from the JSON body.
5. What is the difference between req.params and req.query?
req.params is used for route parameters.
Example:
/api/students/10
Access it with:
req.params.id
req.query is used for query parameters.
Example:
/api/students?course=Node.js
Access it with:
req.query.course
6. Why is JSON commonly used in REST APIs?
JSON is lightweight, readable, and supported by JavaScript and most modern programming languages.
Example:
{
"id": 1,
"name": "Rahul",
"course": "Node.js"
}
It is commonly used for sending structured data between clients and servers.
7. Can I build a REST API without a database?
Yes.
For learning purposes, you can store data in an array:
const students = [];
However, this data exists only while the Node.js process is running.
For production applications, persistent storage such as a database is normally required.
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
