Program 16
Program 16
AIM: - Develop an express Web application that can interact with REST API to perform
CRUD operations on student data. (Use Postman)
Step1:-
1) Initialize the Project: Create a new directory for your project and initialize npm.
mkdir student-api-app
cd student-api-app
npm init -y
2) Install Dependencies: Install necessary packages such as Express and other middleware.
// app.js
const express = require('express');
const bodyParser = require('body-parser');
const axios = require('axios');
// Middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// Routes
app.get('/', (req, res) => {
res.send('Welcome to the Student API App');
});
// Start server
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
// app.js continued...
// Update a student by ID
app.put('/students/:id', (req, res) => {
const id = parseInt(req.params.id);
const { name, age } = req.body;
const student = students.find(s => s.id === id);
if (!student) {
return res.status(404).json({ message: 'Student not found' });
}
student.name = name;
student.age = age;
res.json(student);
});
// Delete a student by ID
app.delete('/students/:id', (req, res) => {
const id = parseInt(req.params.id);
students = students.filter(s => s.id !== id);
res.status(204).end();
});
Step 3:
Start the Server: Run the Node.js application using the node command followed by the name of
your main JavaScript file (in this case, app.js).
node app.js
Step 4:
Verify Server is Running: After running the command, you should see a message in the terminal
indicating that the server is running, similar to:
Output :
GET:
Open Postman.
Set the request type to GET.
Enter the URL: http://localhost:3000/students.
POST : Create a New Student
Open Postman.
Set the request type to POST.
Enter the URL: http://localhost:3000/students.
Go to the "Body" tab.
Select raw and set the body to JSON format.