exp10
exp10
Develop an express web application that can interact with REST API to perform
CRUD operations on student data. (Use Postman)
Solution :
Firstly we need to create a new folder and open the folder in the command
prompt and enter a command as below:
npminit -y
Open that folder in the vscode by entering code.
Next in the terminal we need to install all the packages we need, so we mainly use
express and sqlite3.
The Command to install express and sqlite3 is
npm install express sqlite3
Then create file named as the app.js and db.js
db.js
const sqlite3 = require('sqlite3').verbose();
// Function to initialize the database schema
function initializeDatabase() {
const db = new sqlite3.Database('./mydatabase.db', (err) => {
if (err) {
console.error(err.message);
} else {
console.log('Connected to the SQLite database.');
createStudentsTable(db);
}
});
// Close the database connection when the Node process exits
process.on('exit', () => {
db.close((err) => {
if (err) {
console.error(err.message);
} else {
console.log('Disconnected from the SQLite database.');
}
});
});
}
// Function to create the 'students' table if it doesn't exist
function createStudentsTable(db) {
const createTableQuery = `
CREATE TABLE IF NOT EXISTS students (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT,
age INTEGER,
grade TEXT
);
`;
module.exports = { initializeDatabase };
when we execute both the db.js then the database will be created that
is mydatabase.db
app.js
// Update a student
app.put('/students/:id', (req, res) => {
const id = req.params.id;
const{ name, age, grade } = req.body;
db.run('UPDATE students SET name = ?, age = ?, grade = ? WHERE id = ?',
[name, age, grade, id], function (err) {
if (err) {
return console.error(err.message);
}
res.json({ updatedID:id });
});
});
// Delete a student
app.delete('/students/:id', (req, res) => {
const id = req.params.id;
db.run('DELETE FROM students WHERE id = ?', id, function (err) {
if (err) {
return console.error(err.message);
}
res.json({ deletedID:id });
});
});
app.listen(port, () => {
console.log('Server running at http://localhost:${port}');
});
Output:
GET:
Open Postman.
Set the request type to GET.
Enter the URL: http://localhost:3000/students.