-
Import Necessary Modules: Start by importing the required libraries at the top of your
server.js
or your main application file.const express = require('express'); const bodyParser = require('body-parser'); const { Pool } = require('pg');
-
Initialize Express and PostgreSQL:
Configure PostgreSQL by establishing a connection using
pg
.const app = express(); const pool = new Pool({ user: 'your_username', host: 'localhost', database: 'schoolDB', password: 'your_password', port: 5432, }); // Middlewares app.use(bodyParser.json());
-
Define CRUD Routes:
a. GET all students:
app.get('/students', async (req, res) => { try { const result = await pool.query('SELECT * FROM students'); res.json(result.rows); } catch (error) { res.status(500).json({ message: 'Internal server error' }); } });
b. POST a new student:
app.post('/students', async (req, res) => { try { const { name, grade } = req.body; const result = await pool.query('INSERT INTO students (name, grade) VALUES ($1, $2) RETURNING *', [name, grade]); res.status(201).json(result.rows[0]); } catch (error) { res.status(500).json({ message: 'Internal server error' }); } });
c. PUT (update) an existing student:
app.put('/students/:id', async (req, res) => { try { const { name, grade } = req.body; const result = await pool.query('UPDATE students SET name = $1, grade = $2 WHERE id = $3 RETURNING *', [name, grade, req.params.id]); if (result.rows.length) { res.json(result.rows[0]); } else { res.status(404).json({ message: 'Student not found' }); } } catch (error) { res.status(500).json({ message: 'Internal server error' }); } });
d. DELETE a student:
app.delete('/students/:id', async (req, res) => { try { const result = await pool.query('DELETE FROM students WHERE id = $1 RETURNING *', [req.params.id]); if (result.rows.length) { res.json({ message: 'Student deleted successfully' }); } else { res.status(404).json({ message: 'Student not found' }); } } catch (error) { res.status(500).json({ message: 'Internal server error' }); } });
-
Start the server:
const PORT = 3000; app.listen(PORT, () => { console.log(`Server is running on port ${PORT}`); });
Use the command below to start the server:
nodemon server.js
-
Launch Postman.
-
GET all students: Set the HTTP method to
GET
and use the URLhttp://localhost:3000/students
. HitSend
. -
Add a student: Switch to
POST
, set the URL tohttp://localhost:3000/students
, and use the 'Body' tab to input student details in JSON format. ClickSend
. -
Update a student: Use
PUT
, adjust the URL tohttp://localhost:3000/students/[STUDENT_ID]
replacing[STUDENT_ID]
with a valid ID, and change the student's details in the 'Body' tab. HitSend
. -
Delete a student: Change the HTTP method to
DELETE
, modify the URL tohttp://localhost:3000/students/[STUDENT_ID]
where[STUDENT_ID]
is the ID of the student you want to remove, and pressSend
.