CRUD REST API With Node - JS, Express, and PostgreS
CRUD REST API With Node - JS, Express, and PostgreS
Join the
LogRocket Content Advisory Board today →
Table of contents
What is Express?
What is PostgreSQL?
What is node-postgres?
Creating a PostgreSQL
database
Connecting to a Postgres
database using a Client
What is Express?
What is PostgreSQL?
What is node-postgres?
Creating a PostgreSQL
database
Learn more →
Installation
PostgreSQL command
prompt
-h or --host=HOSTNAME : The
database server host or socket directory;
the default is local socket
-U or --username=USERNAME : The
database username; the default is
your_username
psql postgres
postgres=#
command:
postgres=# \conninfo
You are connected to database "postgres" as user "your_user
Creating a role in
Postgres
me | Create DB | {}
postgres | Superuser, Create role, Create DB | {}
postgres=# \q
with me :
psql -d postgres -U me
Creating a database in
Postgres
postgres=> \c api
You are now connected to database "api" as user "me".
api=>
Creating a table in
Postgres
api=>
CREATE TABLE users (
ID SERIAL PRIMARY KEY,
name VARCHAR(30),
email VARCHAR(30)
);
Setting up an Express
server
mkdir node-api-postgres
cd node-api-postgres
{
"name": "node-api-postgres",
"version": "1.0.0",
"description": "RESTful API with Node.js, Express, and Po
"main": "index.js",
"license": "MIT"
}
npm i express pg
app.use(bodyParser.json())
app.use(
bodyParser.urlencoded({
extended: true,
})
)
app.listen(port, () => {
console.log(`App running on port ${port}.`)
})
node index.js
App running on port 3000.
{
info: "Node.js, Express, and Postgres API"
}
Connecting to a
Postgres database using
a Client
Connecting to a
Postgres database from
Node.js
(https://pgbouncer.github.io/) ,a
lightweight connection pooler for
PostgreSQL.
GET : / | displayHome()
DELETE : /users/:id |
deleteUser()
pool.query(
'UPDATE users SET name = $1, email = $2 WHERE id = $3'
[name, email, id],
(error, results) => {
if (error) {
throw error
}
response.status(200).send(`User
}
)
}
DELETE a user
Exporting CRUD
functions in a REST API
module.exports = {
getUsers,
getUserById,
createUser,
updateUser,
deleteUser,
}
pool.query(
'UPDATE users SET name = $1, email = $2 WHERE id = $3'
[name, email, id],
(error, results) => {
if (error) {
throw error
}
response.status(200).send(`User
}
)
}
module.exports = {
getUsers,
getUserById,
createUser,
updateUser,
deleteUser,
}
Setting up CRUD
functions in a REST API
const db = require('./queries')
app.get('/users', db.getUsers)
app.get('/users/:id', db.getUserById)
app.post('/users', db.createUser)
app.put('/users/:id', db.updateUser)
app.delete('/users/:id', db.deleteUser)
app.use(bodyParser.json())
app.use(
bodyParser.urlencoded({
extended: true,
})
)
app.get('/users', db.getUsers)
app.get('/users/:id', db.getUserById
app.post('/users', db.createUser)
app.put('/users/:id', db.updateUser)
app.delete('/users/:id', db.deleteUser
app.listen(port, () => {
console.log(`App running on port $
})
node index.js
App running on port 3000.
Now, if you go to
http://localhost:3000/users or
http://localhost:3000/users/1 , you’ll
see the JSON response of the two GET
requests.
Solutions to common
issues encountered
while developing APIs
app.use(cors())
Authentication
methods.
passport.use(new LocalStrategy(
function(username, password, done) {
// Verify username and password
// Call done(null, user) if authentication is succe
}
));
Authorization
Input validation
app.post('/users', [
// add validation rules
], (req, res) => {
const errors = validationResult(
if (!errors.isEmpty()) {
return res.status(422).json({
}
// Process the request
});
Helmet middleware
Continuous integration/deployment
(CI/CD): Set up CI/CD pipelines to
automate the testing and deployment
processes. Use tools like Jenkins, Travis
CI, or GitHub Actions to streamline the
development/deployment workflow
Conclusion
Share this:
#node #postgresql
Recent posts:
Idorenyin Obong
Feb 15, 2024 ⋅ 15 min read
Yan Sun
Feb 15, 2024 ⋅ 13 min read
Isaac Okoro
Feb 13, 2024 ⋅ 8 min read
Jessica Srinivas
Feb 12, 2024 ⋅ 7 min read
: Reply
t 10:08 pm
Reply
t 6:49 am
t i’ve been looking for. great start that can be easily expanded by
.
t says: Reply
t 4:19 pm
h localhost -U me
se I got
not connect to server: FATAL: Peer authentication failed for
t says: Reply
t 4:41 pm
ctly what I was looking for. Note there is an error in the POST
ults’ should be ‘result’.
t says: Reply
t 4:50 pm
true.
t says: Reply
t 4:51 pm
Thanks for the help!
says: Reply
at 11:51 am
rything works except why would there be a json response on
ers ? I don’t see anything there. Am I supposed have a
ing the SQL statement correctly, with the “RETURNING id” bit
says: Reply
at 4:54 pm
while to figure it out. thanks
Reply
1 at 10:59 am
ught it was the apostrophe formatting, I actually had the
part but couldnt get the results.rows piece – thank you!
Reply
5:42 pm
anks for the work, it is very easy to follow and works like a
Reply
4:58 pm
ng this error when I run node index.js at the end: error:
ication failed for user “testuser”
his?
Reply
1:25 pm
files completely and when I try and localhost:3000/users it just
y way to trace the error?
ays: Reply
21 at 4:20 pm
ERT entries via $request.body, I had to use $request.query and
dy else had this issue
0].id thing isn’t working for me either
ays: Reply
t 12:11 am
ad the issue with $request.body as well and changing it to
fixed it.
results.rows[0] thing though, that one works on my machine.
: Reply
21 at 8:55 am
between the headlines “Installation” and “PostgreSQL command
sleading. I’m using Windows and it is unlear to me which of
e releveant to my OS and whether I have to run any brew-based
similar ones in npm after downloading the Windows installer
bviously, though not mentioned) and passin on to the
mand prompt section. Clarifications would be appreciated.
Reply
t 6:14 am
you so much
Reply
:03 pm
ex.js”? How do I run this?
ys: Reply
2 at 9:47 am
share your TypeScripit prject.
Reply
6 am
ve a problem with createUser, change code into:
01).send(`User added with ID: ${results.rows[0][“id”]}`)
Reply
at 9:35 am
e record in users table but both name and email has null values.
undefined. Any help appreciated.
says: Reply
3 at 2:23 pm
ut this could work for others.
dyParser should solve this problem
arser.json())
encoded({
s: Reply
t 4:18 pm
mebrew required a version for postgresql.
resql
g https://formulae.brew.sh/api/formula.jws.json
##########################################################
g https://formulae.brew.sh/api/cask.jws.json
##########################################################
me:
resql@15
« Previous 1 2 Next »