Learn how to build a REST API using Node.js and Express.js, handle HTTP requests, return JSON data, and test API endpoints with Postman.
API stands for Application Programming Interface. It allows different software applications to communicate with each other.
For example:
Website or mobile app
Processes the request
Uses the returned data
REST stands for Representational State Transfer. A REST-style API exposes resources through URLs and commonly uses HTTP methods to retrieve or modify those resources.
Examples of resources include:
/api/students to represent the collection of students
and /api/students/101 to represent one student.
| HTTP Method | Purpose | Example Endpoint |
|---|---|---|
| GET | Retrieve data | GET /api/students |
| POST | Create a resource | POST /api/students |
| PUT | Replace a resource | PUT /api/students/101 |
| PATCH | Partially update a resource | PATCH /api/students/101 |
| DELETE | Delete a resource | DELETE /api/students/101 |
Follow these steps to create the project.
mkdir student-api
cd student-api
npm init -y
This command creates a package.json file.
npm install express
Create a file named app.js and add the following code.
const express = require('express');
const app = express();
app.get('/api', (req, res) => {
res.json({
message: 'Welcome to our REST API'
});
});
app.listen(3000, () => {
console.log('API running at http://localhost:3000');
});
Run the server:
node app.js
Open:
http://localhost:3000/api
Expected response:
{
"message": "Welcome to our REST API"
}
Now create an API that returns a list of students and allows a client to retrieve one student by ID.
const express = require('express');
const app = express();
const students = [
{ id: 1, name: 'Amit', course: 'Node.js' },
{ id: 2, name: 'Rahul', course: 'JavaScript' },
{ id: 3, name: 'Priya', course: 'React' }
];
app.get('/api/students', (req, res) => {
res.json(students);
});
app.get('/api/students/:id', (req, res) => {
const id = Number(req.params.id);
const student = students.find(s => s.id === id);
if (!student) {
return res.status(404).json({
message: 'Student not found'
});
}
res.json(student);
});
app.listen(3000, () => {
console.log('API running on port 3000');
});
Get all students:
GET http://localhost:3000/api/students
Get student with ID 2:
GET http://localhost:3000/api/students/2
Example response:
{
"id": 2,
"name": "Rahul",
"course": "JavaScript"
}
The POST method is commonly used to create a new resource.
To read JSON request bodies, register express.json().
const express = require('express');
const app = express();
app.use(express.json());
const students = [
{ id: 1, name: 'Amit', course: 'Node.js' }
];
app.post('/api/students', (req, res) => {
const { name, course } = req.body;
if (
typeof name !== 'string' ||
!name.trim() ||
typeof course !== 'string' ||
!course.trim()
) {
return res.status(400).json({
message: 'Name and course are required'
});
}
const newStudent = {
id: students.length
? Math.max(...students.map(s => s.id)) + 1
: 1,
name: name.trim(),
course: course.trim()
};
students.push(newStudent);
res.status(201).json(newStudent);
});
app.listen(3000, () => {
console.log('API running on port 3000');
});
Send a POST request to
http://localhost:3000/api/students
with this JSON body:
{
"name": "Neha",
"course": "Python"
}
Example response:
{
"id": 2,
"name": "Neha",
"course": "Python"
}
The response uses status code 201 Created.
PUT is commonly used to replace the data of an existing resource. This example expects both the name and course to be supplied.
app.put('/api/students/:id', (req, res) => {
const id = Number(req.params.id);
const student = students.find(s => s.id === id);
if (!student) {
return res.status(404).json({
message: 'Student not found'
});
}
const { name, course } = req.body;
if (
typeof name !== 'string' ||
!name.trim() ||
typeof course !== 'string' ||
!course.trim()
) {
return res.status(400).json({
message: 'Name and course are required'
});
}
student.name = name.trim();
student.course = course.trim();
res.json({
message: 'Student updated successfully',
student: student
});
});
Send a PUT request to
http://localhost:3000/api/students/1
with a JSON body containing the updated name and course.
PATCH updates selected fields without requiring the client to send every field.
app.patch('/api/students/:id', (req, res) => {
const id = Number(req.params.id);
const student = students.find(s => s.id === id);
if (!student) {
return res.status(404).json({
message: 'Student not found'
});
}
const { name, course } = req.body;
if (name !== undefined) {
if (typeof name !== 'string' || !name.trim()) {
return res.status(400).json({
message: 'Name must be a non-empty string'
});
}
student.name = name.trim();
}
if (course !== undefined) {
if (typeof course !== 'string' || !course.trim()) {
return res.status(400).json({
message: 'Course must be a non-empty string'
});
}
student.course = course.trim();
}
res.json({
message: 'Student updated successfully',
student: student
});
});
For example, a PATCH request can update only the student's course.
The DELETE method is used to remove a resource.
app.delete('/api/students/:id', (req, res) => {
const id = Number(req.params.id);
const index = students.findIndex(s => s.id === id);
if (index === -1) {
return res.status(404).json({
message: 'Student not found'
});
}
students.splice(index, 1);
res.json({
message: 'Student deleted successfully'
});
});
Send a DELETE request to
http://localhost:3000/api/students/1.
| Status Code | Meaning | Example Use |
|---|---|---|
| 200 | OK | Data retrieved or an operation succeeded. |
| 201 | Created | A resource was created. |
| 204 | No Content | An operation succeeded without a response body. |
| 400 | Bad Request | Required fields are missing or invalid. |
| 404 | Not Found | The requested student does not exist. |
| 500 | Internal Server Error | An unexpected server-side problem occurred. |
Postman is an API client that allows you to send HTTP requests and inspect the responses.
node app.js.app.js file,
declare the shared students array once, and register
app.use(express.json()) before the routes.
Create a complete Express API with the following requirements:
student-api.Select the correct answer for each question.